-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathde.py
More file actions
122 lines (94 loc) · 3.5 KB
/
de.py
File metadata and controls
122 lines (94 loc) · 3.5 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
#[1997]-"Differential evolution - A simple and efficient heuristic for global optimization over continuous spaces"
import numpy as np
from numpy.random import rand
from FS.functionHO import Fun
from FS.__basic import init_position, binary_conversion, boundary
def jfs(xtrain, ytrain, opts):
# Parameters
ub = opts['ub']
lb = opts['lb']
thres = 0.5
CR = 0.9 # crossover rate
F = 0.5 # factor
N = opts['N']
max_iter = opts['T']
if 'CR' in opts:
CR = opts['CR']
if 'F' in opts:
F = opts['F']
# Dimension
dim = np.size(xtrain, 1)
if np.size(lb) == 1:
ub = ub * np.ones([1, dim], dtype='float')
lb = lb * np.ones([1, dim], dtype='float')
# Initialize position
X = init_position(lb, ub, N, dim)
# Binary conversion
Xbin = binary_conversion(X, thres, N, dim)
# Fitness at first iteration
fit = np.zeros([N, 1], dtype='float')
Xgb = np.zeros([1, dim], dtype='float')
fitG = float('inf')
for i in range(N):
fit[i,0] = Fun(xtrain, ytrain, Xbin[i,:], opts)
if fit[i,0] < fitG:
Xgb[0,:] = X[i,:]
fitG = fit[i,0]
# Pre
curve = np.zeros([1, max_iter], dtype='float')
t = 0
curve[0,t] = fitG.copy()
print("Generation:", t + 1)
print("Best (DE):", curve[0,t])
t += 1
while t < max_iter:
V = np.zeros([N, dim], dtype='float')
U = np.zeros([N, dim], dtype='float')
for i in range(N):
# Choose r1, r2, r3 randomly, but not equal to i
RN = np.random.permutation(N)
for j in range(N):
if RN[j] == i:
RN = np.delete(RN, j)
break
r1 = RN[0]
r2 = RN[1]
r3 = RN[2]
# mutation (2)
for d in range(dim):
V[i,d] = X[r1,d] + F * (X[r2,d] - X[r3,d])
# Boundary
V[i,d] = boundary(V[i,d], lb[0,d], ub[0,d])
# Random one dimension from 1 to dim
index = np.random.randint(low = 0, high = dim)
# crossover (3-4)
for d in range(dim):
if (rand() <= CR) or (d == index):
U[i,d] = V[i,d]
else:
U[i,d] = X[i,d]
# Binary conversion
Ubin = binary_conversion(U, thres, N, dim)
# Selection
for i in range(N):
fitU = Fun(xtrain, ytrain, Ubin[i,:], opts)
if fitU <= fit[i,0]:
X[i,:] = U[i,:]
fit[i,0] = fitU
if fit[i,0] < fitG:
Xgb[0,:] = X[i,:]
fitG = fit[i,0]
# Store result
curve[0,t] = fitG.copy()
print("Generation:", t + 1)
print("Best (DE):", curve[0,t])
t += 1
# Best feature subset
Gbin = binary_conversion(Xgb, thres, 1, dim)
Gbin = Gbin.reshape(dim)
pos = np.asarray(range(0, dim))
sel_index = pos[Gbin == 1]
num_feat = len(sel_index)
# Create dictionary
de_data = {'sf': sel_index, 'c': curve, 'nf': num_feat}
return de_data