-
Notifications
You must be signed in to change notification settings - Fork 1
/
nn_wip.py
189 lines (158 loc) · 5.96 KB
/
nn_wip.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 25 13:21:47 2020
@author: Aditya Agarwal
"""
from sklearn.metrics import classification_report, confusion_matrix
import sys
import tensorflow as tf
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import cross_val_score
from sklearn.linear_model import LogisticRegression
import random
import numpy as np
import pandas as pd
from sklearn.neural_network import MLPClassifier
from sklearn.preprocessing import StandardScaler # doctest: +SKIP
scaler = StandardScaler()
def avg(l):
"""
Returns the average between list elements
"""
return (sum(l)/float(len(l)))
def getFitness(individual, X, y):
"""
Feature subset fitness function
"""
# individual = individual.tolist()
if(individual.count(0) != len(individual)):
# get index with value 0
cols = [index for index in range(
len(individual)) if individual[index] == 0]
# get features subset
X_parsed = X.drop(X.columns[cols], axis=1)
X_subset = pd.get_dummies(X_parsed)
X_train, X_test, y_train, y_test = train_test_split(
X_subset, y, test_size=0.30)
# apply classification algorithm
# clf = LogisticRegression(max_iter = 10000)
# clf = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(5, 2), random_state=1)
nn_model = model = tf.keras.Sequential([tf.keras.layers.Flatten(),
tf.keras.layers.Dense(
128, activation='relu'),
tf.keras.layers.Dense(7)])
nn_model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(
from_logits=True),
metrics=['accuracy'])
nn_model.fit(X_subset, y, epochs=100)
test_loss, test_acc = nn_model.evaluate(X_subset, y, verbose=2)
return test_acc
else:
return(0,)
def populate(features, size=50):
initial = []
for _ in range(size):
entity = []
for feature in features:
val = np.random.randint(0, 2)
entity.append(val)
initial.append(entity)
# print(entity)
return np.array(initial)
def mutate(population, mutation_rate):
# n = np.random.randint(0, len(population))
# p = population[np.random.randint(0, len(population))]
# l = np.random.randint(0, len(p))
# population[n][l] = np.random.randint(0,2)
# print("\n\ninside mutate" + str(population))
# return population
mutated_pop = []
for p in population:
p_list = p.tolist()
und = np.random.choice(2, 1, p = [1 - mutation_rate, mutation_rate])
if(und > 0):
m_index = np.random.randint(0, len(p_list))
if p_list[m_index] == 0:
p_list[m_index] = 1
else:
p_list[m_index] = 0
mutated_pop.append(p_list)
else:
mutated_pop.append(p_list)
return np.array(mutated_pop)
def cross(population, crossover_rate):
new_pop = population.tolist()
for _ in range(int(crossover_rate*len(population))):
p = population[np.random.randint(0, len(population))].tolist()
m = population[np.random.randint(0, len(population))].tolist()
entity = p[0:len(p)//2]
for i in m[len(m)//2:len(m)]:
entity.append(i)
new_pop.append(entity)
return np.array(new_pop)
def geneticAlgorithm(X, y, n_population, n_generation, mutation_rate, crossover_rate):
population = populate(X.columns, n_population)
a, prev_fitness, b = bestIndividual(population, X, y)
for i in range(n_generation):
population = mutate(population, mutation_rate)
population = cross(population, crossover_rate)
a, current_fitness, b = bestIndividual(population, X, y)
if(i < int(n_generation/2)):
continue
#break if not more than 1% change in fitness values
if(current_fitness - prev_fitness < 0.01*prev_fitness):
# print("i at break:" + str(i) + "\n")
break
prev_fitness = current_fitness
return population
def bestIndividual(hof, X, y):
"""
Get the best individual
"""
_individual = []
maxAccurcy = 0.0
for individual in hof:
individual = individual.tolist()
val = getFitness(individual, X, y)
if(val > maxAccurcy):
maxAccurcy = val
_individual = individual
_individualHeader = [list(X)[i] for i in range(
len(_individual)) if _individual[i] == 1]
# _individual = _individual.tolist()
return _individual, maxAccurcy ,_individualHeader
# dataFramePath = input("Please enter csv path\n")
n_pop = 50
n_gen = 5
mutation_rate = 0.03
crossover_rate = 0.05
dataFramePath = "/home/rudraj1t/eContent/AI/Coding Assignment/labelled-combined.csv"
df = pd.read_csv(f"{dataFramePath}")
# df=pd.read_csv("labelled-combined.csv")
# print(df.head)
le = LabelEncoder()
le.fit(df.iloc[:, -1])
y = le.transform(df.iloc[:, -1])
X = df.iloc[:, :-1]
# print(y)
# print("\nX: ")
# print(X)
# print("\n")
individual = [1 for i in range(len(X.columns))]
print("Accuracy with all features: \t" + str(getFitness(individual, X, y)) + "\n")
hof = geneticAlgorithm(X, y, n_pop, n_gen, mutation_rate, crossover_rate)
# select the best individual
individual, accuracy, header = bestIndividual(hof, X, y)
# print(individual)
# individual = individual.tolist()
print('Best Accuracy: \t' + str(accuracy))
print('Number of Features in Subset: \t' + str(individual.count(1)))
# print('Individual: \t\t' + str(individual))
X = df[header]
# clf = LogisticRegression(max_iter = 10000)
# clf = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(5, 2), random_state=1)
# scores = cross_val_score(clf, X, y, cv=5)
# print("Accuracy with Feature Subset: \t" + str(avg(scores)) + "\n")