/
sandbox.py
192 lines (151 loc) · 5.65 KB
/
sandbox.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
189
190
191
192
from readdata import read_data
from keras.models import model_from_json
import numpy as np
import utils as u
import network as nn
# import network_trellis as nn
# import network_basic as nn
import label_classifier as _classifier
from functools import reduce
np.random.seed(1)
def number_of_outputs(filtered_labels):
return max(map(lambda label: (label == 1).sum(), filtered_labels))
def classify_task(task_labels):
type = reduce(
lambda x, y: x * y
, map(lambda label: (label == 1).sum(), task_labels)
, 1
)
# print(type)
if type == 1:
return 'single_classification'
return 'multiclassification'
def transform_labels(task_labels, task_class):
if (task_class == 'single_classification'):
epitome = task_labels[0]
classes_ids = []
for i in len(epitome):
if (epitome[i] != 2):
classes_ids.append(i)
classes_ids.append(-1)
labels = []
for label_id in len(task_labels):
for parameter in task_labels[label_id]:
if (parameter == 1):
labels.append(classes_ids.index(parameter))
if (len(labels) == label_id):
labels.append(-1)
return labels
def transform_data(raw_images, raw_labels, task_id=None):
labels = _classifier.labels_remove_twos(raw_labels)
labels, representation = _classifier.transform_labels_with_representation(labels)
return raw_images, labels, representation
model = None
history = None
task_dims = []
def generate_trainingset(labels_count, true_labels):
data = [np.zeros((labels_count, dim)) for dim in task_dims]
data.append(true_labels)
return data
def train_network(X, Y, epochs=1, train=True, filename=None, load_model=False, finetune=False):
global model, history
if load_model:
print('Loading model')
input_model = open(filename[0], 'r')
model = model_from_json(input_model.read())
input_model.close()
model.compile(optimizer='rmsprop', loss='categorical_crossentropy')
model.load_weights(filename[1])
print('Loaded(probably)')
if finetune:
lastLayer = None
print(model.layers[0].__dict__)
for layer in model.layers:
if (layer.name == 'dense_1'):
nn.conv = layer
lastLayer = layer
import h5py
if not load_model or finetune:
X, Y, _ = transform_data(X, Y)
print('Labels shape: ' + str(Y.shape))
print('Labels look like this : ')
print(Y[0])
if not finetune:
nn.construct_model(X[0].shape)
nn.add_new_task(len(Y[0]))
model = nn.get_model()
if train:
print('Training started')
input_model = open(filename[0], 'w')
input_model.write(model.to_json())
input_model.close()
# model.summary()
print('Fitting')
history = model.fit(X, generate_trainingset(X.shape[0], Y), nb_epoch=epochs)
task_dims.append(Y.shape[1])
print('Training end')
if filename is not None:
input_model = open(filename[0], 'w')
input_model.write(model.to_json())
input_model.close()
model.save_weights(filename[1], overwrite=True)
return history
tasks = {}
def train_network_ui(task_id, difficulty, epochs=3):
tasks[(task_id, difficulty)] = len(tasks.keys())
X, Y = read_data(task_id=task_id, difficulty=difficulty)
return train_network(X, Y, epochs=epochs, train=True, load_model=False, filename=['model.txt', 'weights.hdf5'])
def accuracy(predicted, original, raw, errors):
acc = 0
for id in range(predicted.shape[0]):
if all(predicted[id] == original[id]):
acc += 1
else:
if (errors):
print(str(predicted[id]) + " " + str(original[id]) + " raw: " + str(list(map(u.round3, raw[id]))))
return acc * 1.0 / predicted.shape[0]
def evaluate_accuracy(task_id, difficulty, errors=False, outputFile='result.txt'):
print('reading and processing testing data')
X, Y = read_data(training=False, task_id=task_id, difficulty=difficulty)
print("Getting representation")
print('read')
Y = _classifier.labels_remove_twos(Y)
print('predicting..')
representation = _classifier.find_representation(Y)
if (task_id, difficulty) in tasks.keys():
model = nn.get_model(tasks[(task_id, difficulty)])
else:
raise Exception('Task unknown')
return
raw_predicted = model.predict(X, verbose=1)
predicted = _classifier.get_normal_output(raw_predicted, representation)
acc = accuracy(predicted, Y, raw_predicted, errors)
print('Accuracy %.4f' % acc)
return acc
def show_model():
# from IPython.display import SVG
from keras.utils.visualize_util import model_to_dot
#return SVG(model_to_dot(model).create(prog='dot', format='svg'))
if False:
while True:
print("task id:")
id = int(input())
print("difficulty")
diff = int(input())
print('train or test?(1/2)')
if input() == '1':
print('epochs')
epochs = int(input())
train_network_ui(id, diff, epochs)
else:
evaluate_accuracy(id, diff)
print('If you want to exit -- enter 0 ; 1 -- to test last trained task')
inp = input()
if inp == '0':
from keras.utils.visualize_util import plot
import os
os.chdir('/media/dewitt/FAB907B81E039285/GoodAI/')
plot(model, to_file='model.png')
raise SystemExit()
elif inp == '1':
evaluate_accuracy(id, diff)