-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathKerasModel.py
More file actions
executable file
·154 lines (112 loc) · 4.8 KB
/
KerasModel.py
File metadata and controls
executable file
·154 lines (112 loc) · 4.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
import ROOT
ROOT.PyConfig.IgnoreCommandLineOptions = True # disable ROOT internal argument parser
import numpy as np
from pandas import DataFrame,concat
import json
np.random.seed(0)
import conf.keras_models as keras_models
from keras.callbacks import EarlyStopping, ModelCheckpoint
from keras.models import load_model as lm
from keras.utils.np_utils import to_categorical
from collections import deque
import time
import os
class KerasObject():
def __init__(self, parameter_file = "", variables=[], target_names = {}, filename = "" ):
self.variables = variables
self.models = []
try:
if filename: self.load(filename)
elif not parameter_file or not variables:
raise Warning("Warning! Object not defined. Load from file or set 'params' and 'variables'")
else:
with open(parameter_file,"r") as FSO:
params = json.load(FSO)
self.params = params["model"]
except Warning as e:
print e
self.params = []
if target_names: self.target_names = target_names
def load(self, filename):
with open(filename + ".dict", 'rb') as FSO:
tmp_dict = json.load(FSO)
print "Loading model from: " + filename
self.__dict__.clear()
self.__dict__.update(tmp_dict)
self.models = []
for model in tmp_dict["models"]:
self.models.append( lm(model) )
def save(self, filename):
placeholders = []
tmp_models = []
for i,model in enumerate(self.models):
modelname = filename + ".fold{0}".format(i)
model.save( modelname )
tmp_models.append(model)
placeholders.append( modelname )
self.models = placeholders
with open(filename + ".dict", 'wb') as FSO:
json.dump(self.__dict__, FSO)
self.models = tmp_models
def train(self, samples):
if type(samples) is list:
samples = deque(samples)
for i in xrange( len(samples) ):
test = samples[0]
train = [ samples[1] ]
for j in xrange(2, len(samples) ):
train.append( samples[j] )
train = concat(train , ignore_index=True).reset_index(drop=True)
self.models.append( self.trainSingle( train, test ) )
samples.rotate(-1)
print "Finished training!"
def trainSingle(self, train, test):
# writing targets in keras readable shape
best = str(int(time.time()))
y_train = to_categorical( train["target"].values )
y_test = to_categorical( test["target"].values )
N_classes = len(y_train[0])
model_impl = getattr(keras_models, self.params["name"])
model = model_impl(len(self.variables), N_classes)
model.summary()
history = model.fit(
train[self.variables].values,
y_train,
sample_weight=train["train_weight"].values,
validation_split = 0.25,
# validation_data=(test[self.variables].values, y_test, test["train_weight"].values),
batch_size=self.params["batch_size"],
epochs=self.params["epochs"],
shuffle=True,
callbacks=[EarlyStopping(patience=self.params["early_stopping"]), ModelCheckpoint( best + ".model", save_best_only=True, verbose = 1) ])
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
print "plotting training"
epochs = xrange(1, len(history.history["loss"]) + 1)
plt.plot(epochs, history.history["loss"], lw=3, label="Training loss")
plt.plot(epochs, history.history["val_loss"], lw=3, label="Validation loss")
plt.xlabel("Epoch")
plt.ylabel("Loss")
plt.legend()
if not os.path.exists("plots"):
os.mkdir("plots")
plt.savefig("plots/fold_{0}_loss.png".format(best), bbox_inches="tight")
print "Reloading best model"
model = lm(best + ".model")
os.remove( best + ".model" )
return model
def predict(self, samples, where=""):
predictions = []
if type(samples) is list:
samples = deque(samples)
for i in xrange( len(samples) ):
predictions.append( self.testSingle( samples[0], i ) )
samples.rotate(-1)
samples[0].drop(samples[0].index, inplace = True)
samples[1].drop(samples[1].index, inplace = True)
return predictions
def testSingle(self, test,fold ):
prediction = DataFrame( self.models[fold].predict(test[self.variables].values) )
return DataFrame(dtype = float, data = {"predicted_class":prediction.idxmax(axis=1).values,
"predicted_prob": prediction.max(axis=1).values } )