-
Notifications
You must be signed in to change notification settings - Fork 0
/
train.py
144 lines (112 loc) · 4.9 KB
/
train.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
from keras.callbacks import EarlyStopping
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.models import Sequential, model_from_json
from keras.optimizers import SGD
from keras.preprocessing.image import ImageDataGenerator
from sklearn.cross_validation import train_test_split
from utils import process_data
from utils import TRAIN_PATH, MODEL_PATH, WEIGHTS_PATH, BATCH_SIZE, IMG_SIZE, VAL_PROP, SPECIALIST_SETTINGS
import argparse
import numpy as np
import pandas as pd
def build_model():
model = Sequential()
model.add(Convolution2D(32, 3, 3, border_mode='valid', input_shape=(1, IMG_SIZE, IMG_SIZE)))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.1))
model.add(Convolution2D(64, 2, 2, border_mode="valid"))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.2))
model.add(Convolution2D(128, 2, 2, border_mode="valid"))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.3))
model.add(Flatten())
model.add(Dense(1024))
model.add(Activation("relu"))
model.add(Dropout(0.50))
model.add(Dense(1024))
model.add(Activation("relu"))
model.add(Dense(30))
return model
class FlippedImageDataGenerator(ImageDataGenerator):
flip_idxs = [ (0, 2), (1, 3), (4, 8), (5, 9),
(6, 10), (7, 11), (12, 16), (13, 17),
(14, 18), (15, 19), (22, 24), (23, 25)
]
def next(self):
X_batch, y_batch = super(FlippedImageDataGenerator, self).next()
batch_size = X_batch.shape[0]
idxs = np.random.choice(batch_size, batch_size / 2, replace=False)
# Flip image horizontally
X_batch[idxs] = X_batch[idxs, :, :, ::-1]
if y_batch is not None:
y_batch[idxs, ::2] = y_batch[idxs, ::2] * -1
for a, b in self.flip_idxs:
y_batch[idxs, a], y_batch[idxs, b] = (y_batch[idxs, b] , y_batch[idxs, a])
return X_batch, y_batch
def train_model(pretrain):
X, y = process_data(TRAIN_PATH)
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=VAL_PROP)
if pretrain:
model = model_from_json(open(MODEL_PATH).read())
model.load_weights(WEIGHTS_PATH)
else:
model = build_model()
flipgen = FlippedImageDataGenerator()
sgd = SGD(lr=0.08, decay=1e-4, momentum=0.9, nesterov=True)
model.compile(loss="mse", optimizer=sgd)
early_stop = EarlyStopping(monitor="val_loss", patience=100, mode="min")
model.fit_generator(flipgen.flow(X_train, y_train),
samples_per_epoch=X_train.shape[0],
nb_epoch=5000,
validation_data=(X_val, y_val),
callbacks=[early_stop])
print("Saving model to ", MODEL_PATH)
print("Saving weights to ", WEIGHTS_PATH)
open(MODEL_PATH, 'w').write(model.to_json())
model.save_weights(WEIGHTS_PATH, overwrite=True)
mse = model.evaluate(X_val, y_val, batch_size=BATCH_SIZE)
print("MSE: ", mse)
print("RMSE: ", np.sqrt(mse)*IMG_SIZE)
def train_specialists(pretrain):
for setting in SPECIALIST_SETTINGS:
cols = setting["columns"]
X, y = process_data(TRAIN_PATH, cols)
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=VAL_PROP)
if pretrain:
model = model_from_json(open(MODEL_PATH).read())
model.load_weights(WEIGHTS_PATH)
else:
model = build_model()
model.layers.pop()
model.outputs = [model.layers[-1].output]
model.layers[-1].outbound_nodes = []
model.add(Dense(len(cols), name="dense_3"))
flipgen = FlippedImageDataGenerator()
flipgen.flip_idxs = setting["flip_idxs"]
sgd = SGD(lr=0.08, decay=1e-4, momentum=0.9, nesterov=True)
model.compile(loss="mse", optimizer=sgd)
early_stop = EarlyStopping(monitor="val_loss", patience=100, mode="min")
print("Training {}...".format(cols[0]))
model.fit_generator(flipgen.flow(X_train, y_train),
samples_per_epoch=X_train.shape[0],
nb_epoch=1000,
validation_data=(X_val, y_val),
callbacks=[early_stop])
model_path = "data/model_{}.json".format(cols[0])
weights_path = "data/weights_{}.h5".format(cols[0])
print("Saving model to ", model_path)
print("Saving weights to ", weights_path)
open(model_path, 'w').write(model.to_json())
model.save_weights(weights_path, overwrite=True)
# RMSE: 2.597
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-p', action='store_true')
args = parser.parse_args()
# train_model(args.p)
train_specialists(args.p)