-
Notifications
You must be signed in to change notification settings - Fork 3
/
TrainModel.py
76 lines (57 loc) · 2.32 KB
/
TrainModel.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
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
from keras.layers import Input, Dense, Activation, Flatten, Conv2D, Lambda
from keras.layers import MaxPooling2D, Dropout
from keras.utils import print_summary
import tensorflow as tf
from keras.models import Sequential
from keras.callbacks import ModelCheckpoint
import pickle
from keras.optimizers import Adam
def keras_model():
model = Sequential()
model.add(Lambda(lambda x: x / 127.5 - 1., input_shape=(40, 40, 1)))
model.add(Conv2D(32, (3, 3), padding='same'))
model.add(Activation('relu'))
model.add(MaxPooling2D((2, 2), padding='valid'))
model.add(Conv2D(64, (3, 3), padding='same'))
model.add(Activation('relu'))
model.add(MaxPooling2D((2, 2), padding='valid'))
model.add(Conv2D(128, (3, 3), padding='same'))
model.add(Activation('relu'))
model.add(MaxPooling2D((2, 2), padding='valid'))
model.add(Flatten())
model.add(Dropout(0.5))
model.add(Dense(128))
model.add(Dense(64))
model.add(Dense(1))
model.compile(optimizer=Adam(lr=0.0001), loss="mse")
filepath = "Autopilot.h5"
checkpoint1 = ModelCheckpoint(filepath, verbose=1, save_best_only=True)
callbacks_list = [checkpoint1]
return model, callbacks_list
def loadFromPickle():
with open("features_40", "rb") as f:
features = np.array(pickle.load(f))
with open("labels", "rb") as f:
labels = np.array(pickle.load(f))
return features, labels
def augmentData(features, labels):
features = np.append(features, features[:, :, ::-1], axis=0)
labels = np.append(labels, -labels, axis=0)
return features, labels
def main():
features, labels = loadFromPickle()
features, labels = augmentData(features, labels)
features, labels = shuffle(features, labels)
train_x, test_x, train_y, test_y = train_test_split(features, labels, random_state=0,
test_size=0.1)
train_x = train_x.reshape(train_x.shape[0], 40, 40, 1)
test_x = test_x.reshape(test_x.shape[0], 40, 40, 1)
model, callbacks_list = keras_model()
model.fit(train_x, train_y, validation_data=(test_x, test_y), epochs=5, batch_size=64,
callbacks=callbacks_list)
print_summary(model)
model.save('Autopilot.h5')
main()