-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGA.py
More file actions
172 lines (153 loc) · 7.8 KB
/
GA.py
File metadata and controls
172 lines (153 loc) · 7.8 KB
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
from multiprocessing.dummy import Pool as ThreadPool
import numpy as np
import pickle
import pandas as pd
import pdb
import copy
from sklearn.model_selection import KFold
from sklearn.metrics import roc_curve, auc
class GeneticAlgSelect():
# initial model type, model pool and load in data_in,
def __init__(self, data_in, data_out, mdl_type, mdl_para, **para):
# load input and output data, para
self.data_in = data_in
self.data_out = data_out
self.para = para
# define model type
self.mdl_type = mdl_type
self.mdl_para = mdl_para
# init model pool and elite list
self.mdl_pool = []
self.elite_list = []
# load in para
self.__set_constant()
def __set_constant(self):
# define default constants
self.num_worker = self.para['num_worker'] if 'num_worker' in self.para else 1
self.max_iter = self.para['max_iter'] if 'max_iter' in self.para else 5
self.pool_size = self.para['pool_size'] if 'pool_size' in self.para else 10
self.mutateLR = self.para['mutateLR'] if 'mutateLR' in self.para else 0.5
self.mutateUR = self.para['mutateUR'] if 'mutateUR' in self.para else 0.9
self.mutateBIT = self.para['mutateBIT'] if 'mutateBIT' in self.para else 0.1
self.crossLR = self.para['crossLR'] if 'crossLR' in self.para else 0.5
self.crossUR = self.para['crossUR'] if 'crossUR' in self.para else 0.9
self.eliteR = self.para['elite_rate'] if 'elite_rate' in self.para else 0.2
self.savefileName = self.para['savefile'] if 'savefile' in self.para else 'GeneticAlgResult_best.pkl'
self.dim_out = self.para['dim_out'] if 'dim_out' in self.para else 600
# perform interation and evaluate local model in parallel
def _perform_iter(self):
self.__gen_pool()
for i in range(self.max_iter):
# process data_in in parallel
p = ThreadPool(self.num_worker)
l=range(0,self.pool_size)
# train the local models
result=p.map(self._train_mdl,l)
p.close()
p.join()
# eliticism, cross_over and mutation
self.__eliticism()
self.__cross_over()
self.__mutation()
self._save_mdl()
self.print_best_mdl()
#print('Iteration: {} Best accuracy: {:.2f}'.format(i+1, self.elite_list[-1]))
# generate model pool
def __gen_pool(self):
self.gene_len = self.data_in.shape[0] if len(self.data_in.shape)==1 else self.data_in.shape[1]
for i in range(self.pool_size):
gene = (np.random.permutation(self.gene_len) < self.dim_out).astype(int)
#gene = np.random.random_integers(0,high=1,size=self.gene_len)
while gene[np.nonzero(gene)].size==0:
gene = (np.random.permutation(self.gene_len) < self.dim_out).astype(int)
self.mdl_pool.append(GeneticAlgLocalModel(gene, self.mdl_type, self.mdl_para))
# train local model
def _train_mdl(self,i):
#t 'training model: %d /n' %(i)
data_in = self.data_in[:,self.mdl_pool[i].gene==1]
self.mdl_pool[i]._train_mdl(data_in,self.data_out)
# get model with highest score (best performance)
def __eliticism(self):
score_arr=np.zeros(self.pool_size)
for i in range(self.pool_size):
score_arr[i] = self.mdl_pool[i].score
num_elite = round(self.pool_size*self.eliteR)
self.elite_list = np.argsort(score_arr)[-int(num_elite):]
#print(score_arr)
for i in range(self.pool_size):
if i in self.elite_list:
pass
else:
self.mdl_pool[i] = copy.deepcopy(self.mdl_pool[self.elite_list[int(i%(self.pool_size*self.eliteR))]])
# exchange gene pieces
def __cross_over(self):
min_c, max_c = round(self.pool_size*self.crossLR), round(self.pool_size*self.crossUR+1)
num_cross = np.random.randint(min_c, high=max_c)
for i in range(num_cross):
# randomly pick model A and model B
idxA = np.random.randint(0, high=self.pool_size)
idxB = np.random.randint(0, high=self.pool_size)
while idxA in self.elite_list:
idxA = np.random.randint(0, high=self.pool_size)
while (idxB in self.elite_list) or (idxB == idxA):
idxB = np.random.randint(0, high=self.pool_size)
# generate cross over start pt and end pt
pt_s = np.random.randint(0, high=self.gene_len)
pt_e = np.random.randint(0, high=self.gene_len)
pt_s, pt_e = (pt_e, pt_s) if pt_s>pt_e else (pt_s, pt_e)
# exchange gene
self.mdl_pool[idxA].gene[pt_s:pt_e], self.mdl_pool[idxB].gene[pt_s:pt_e] = (self.mdl_pool[idxB].gene[pt_s:pt_e],self.mdl_pool[idxA].gene[pt_s:pt_e])
self.mdl_pool[idxA].changed = True
self.mdl_pool[idxB].changed = True
# mutate some bits
def __mutation(self):
min_m, max_m = round(self.pool_size*self.mutateLR), round(self.pool_size*self.mutateUR+1)
num_mute = np.random.randint(min_m, high=max_m)
bit_mute = int(round(self.mutateBIT*self.dim_out))
for i in range(num_mute):
idx = np.random.randint(0, high=self.pool_size, size=1).astype(int)
while idx in self.elite_list:
idx = np.random.randint(0, high=self.pool_size, size=1).astype(int)
#pts = np.random.randint(0, high=self.gene_len, size=bit_mute).astype(int)
#pdb.set_trace()
sel1 = self.mdl_pool[int(idx)].gene.nonzero()
sel1 = np.random.permutation(sel1[0])
sel0 = np.ones([self.gene_len])
sel0[sel1] = 0
sel0 = np.arange(self.gene_len)[sel0.astype(bool)]
#maintain the same density 0/1
self.mdl_pool[int(idx)].gene[sel1[0:bit_mute/2]] = (1-self.mdl_pool[int(idx)].gene[sel1[0:bit_mute/2]])
self.mdl_pool[int(idx)].gene[sel0[0:bit_mute/2]] = (1-self.mdl_pool[int(idx)].gene[sel0[0:bit_mute/2]])
self.mdl_pool[int(idx)].changed = True
def print_best_mdl(self):
score_arr=np.zeros(len(self.elite_list))
for i in range(len(score_arr)):
score_arr[i] = self.mdl_pool[self.elite_list[i]].score
max_idx = score_arr.argmax()
#print 'The best model calculated is as following'
#print self.mdl_pool[self.elite_list[i]].gene
#print self.mdl_pool[self.elite_list[i]].score
def _save_mdl(self):
pickle.dump(self.mdl_pool[self.elite_list[-1]], open(self.savefileName,"wb"))
#pickle.dump(self.mdl_pool, open(self.savefileName,"wb"))
# local model structure for genetic algorithm that stores local model and gene structure
class GeneticAlgLocalModel():
def __init__(self, gene, mdl_type, mdl_para):
self.gene=gene
self.mdl=mdl_type(**mdl_para)
self.changed = True
self.score=0
def _train_mdl(self, data_in, data_out):
if self.changed:
kf = KFold(n_splits=10,shuffle=False, random_state=None)
i = 0
for train_idx, cross_idx in kf.split(data_in):
if (i<1):
self.mdl.fit(data_in[train_idx,:], data_out[train_idx])
self.changed = False
#fpr, tpr, _ = roc_curve(data_out[test_idx], self.mdl.predict(data_in[test_idx]))
#self.score = auc(fpr, tpr) #self.mdl.score
self.score = self.mdl.score(data_in[cross_idx],data_out[cross_idx])
#print("Accuracy SVM: Test:", self.score)
#import pdb; pdb.set_trace()
i = i+1