-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUCIthyroid.py
177 lines (154 loc) · 6.31 KB
/
UCIthyroid.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
''',
Created on Nov 24, 2020,
@author: david
'''
import csv
import numpy as np
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import RepeatedStratifiedKFold
from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier
from sklearn.model_selection import GridSearchCV, RandomizedSearchCV
from sklearn.preprocessing import OneHotEncoder
from skopt.space import Integer
from skopt.space import Real
from skopt.space import Categorical
from time import time
import os.path
import matplotlib.pyplot as plt
from Experiment import Experiment
def vectorize(row):
return row
def load_data(filename):
X,y = [],[]
with open(filename) as data_file:
data_reader = csv.reader(data_file, delimiter = ',')
for row in data_reader:
print(row)
X.append(vectorize(row[:-1]))
y.append(row[-1].split('.', 1)[0])
data_file.close()
X = np.array(X)
y = np.array(y)
return X,y
idx1 = [0,17,19,21,23,25]
idx2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 20, 22, 24, 26, 28]
X_train,y_train = load_data('datasets/allbp.data')
X_test,y_test = load_data('datasets/allbp.test')
enc = OneHotEncoder(dtype=np.int)
enc.fit(X_train[:, idx2])
def max_array(arr):
new_arr = []
min = float('inf')
for i in range(len(arr)):
if min > arr[i]:
min = arr[i]
new_arr.append(min)
return np.array(new_arr)
def monte_carlo_grid_search(means, stds, n_repeats):
avg_means = np.zeros(len(means))
avg_stds = np.zeros(len(means))
for _ in range(n_repeats):
shuffler = np.random.permutation(len(means))
new_means = max_array(1 - means[shuffler])
new_stds = stds[shuffler]
avg_means = new_means + avg_means
avg_stds = new_stds + avg_stds
avg_means /= n_repeats
avg_stds /= n_repeats
return avg_means, avg_stds
def evaluate_model(params):
model = RandomForestClassifier(n_estimators=params[0], max_samples=params[1],
max_features=params[2])
cv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1)
n_scores = cross_val_score(model, X_train, y_train, scoring='accuracy', cv=cv, n_jobs=-1, verbose=1)
return 1 - np.mean(n_scores)
def save_results(params,means,stds, tarfile):
with open(tarfile, mode='w', newline='') as result_file:
result_writer = csv.writer(result_file, delimiter=',')
for mean, stdev, param in zip(means, stds, params):
result_writer.writerow([param, mean, stdev])
def load_results(tarfile):
points, means, stds = [], [], []
with open(tarfile, mode='r') as result_file:
result_reader = csv.reader(result_file, delimiter=',')
for row in result_reader:
points.append(row[2])
means.append(row[0])
stds.append(row[1])
result_file.close()
return points, np.array(means).astype(np.float), \
np.array(stds).astype(np.float)
def convert_categorical(X):
X = enc.transform(X).toarray().astype(np.int)
#np.savetxt('test.txt', X_train, delimiter=',', fmt='%.0f')
return X
def impute_continuous(X):
for i in range(X.shape[1]): #handle continuous
avg = 0
num = 0
for j in range(X.shape[0]):
if not X[j,i] == '?':
avg += X[j,i].astype(np.float)
num += 1
#===========================================================================
# if num != 0:
# avg /= num
#===========================================================================
for j in range(X.shape[0]):
if X[j,i] == '?':
X[j,i] = avg
X = X.astype(np.float)
return X
X_continuous = X_train[:, idx1] # ignore TBG since all its values are ?
X_categorical = X_train[:, idx2]
X_categorical = convert_categorical(X_categorical)
X_continuous = impute_continuous(X_continuous)
X_train = np.concatenate((X_continuous,X_categorical), axis=1)
X_continuous = X_test[:, idx1] # ignore TBG since all its values are ?
X_categorical = X_test[:, idx2]
X_categorical = convert_categorical(X_categorical)
X_continuous = impute_continuous(X_continuous)
X_test = np.concatenate((X_continuous,X_categorical), axis=1)
def init_space():
search_space = list()
search_space.append(Integer(10, 500, 'log-uniform', name='n_estimators'))
search_space.append(Real(0.1, 0.95, 'uniform', name='max_samples'))
search_space.append(Integer(4, 16, 'log-uniform', name='max_features'))
return search_space
if __name__ == '__main__':
grid = dict()
grid['n_estimators'] = [10, 50, 100, 500]
grid['max_samples'] = [0.3, 0.6, 0.9]
grid['max_features'] = [4,8,10,12,16]
model = RandomForestClassifier()
cv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1)
start1 = time()
grid_search = GridSearchCV(estimator=model, param_grid=grid, n_jobs=-1, cv=cv, scoring='accuracy', verbose=1)
grid_result = grid_search.fit(X_train, y_train)
end1 = time()
means = grid_result.cv_results_['mean_test_score']
stds = grid_result.cv_results_['std_test_score']
params = grid_result.cv_results_['params']
save_results(means,stds,params, 'datasets/thyroidGS.csv')
search_space = init_space()
start2 = time()
experiment = Experiment(evaluate_model, search_space, numberOfEpochs=108, numberOfRepetitions=5, numberOfRandom=10)
experiment.run(['EI'])
end2 = time()
experiment.plot_convergence()
#===========================================================================
# axes = plt.gca()
# axes.set_ylim([0.01,0.035])
#===========================================================================
GS_mean, GS_std = monte_carlo_grid_search(means, stds, 100000)
plt.plot(range(180), max_array(GS_mean), 'b', label='GS')
plt.legend()
plt.show()
print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_))
print(end1 - start1)
print(end2 - start2)
#===============================================================================
# Literatura in viri:
# https://en.wikipedia.org/wiki/Gradient_boosting
# https://machinelearningmastery.com/gradient-boosting-machine-ensemble-in-python/
#=======================,========================================================,