forked from udacity/CarND-Behavioral-Cloning-P3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.py
87 lines (69 loc) · 2.59 KB
/
model.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
from keras.layers import Input, Dense, Flatten, Lambda, Dropout
from keras.layers.convolutional import Conv2D
from keras.models import Model, Sequential
from processor import DataProcessor
NUM_EPOCHS = 15
class CNN(object):
"""
An implementation of Nvidia deep learning model for self driving.
See https://devblogs.nvidia.com/parallelforall/deep-learning-self-driving-cars/
"""
def __init__(self):
self.model = self._get_model()
def fit(self,
train_generator,
train_size,
valid_generator,
valid_size,
n_epochs):
"""
Train model with generators
:param train_generator: train data generator
:param train_size: number of training data points
:param valid_generator: validation data generator
:param valid_size: number of validation data points
:param n_epochs: number of epochs
:return: None
"""
self.model.fit_generator(train_generator,
samples_per_epoch=train_size,
validation_data=valid_generator,
nb_val_samples=n_epochs,
nb_epoch=n_epochs)
def save(self):
"""
Save model as hdf5 file.
:return: None
"""
self.model.save('model.h5')
def _get_model(self):
"""
Get model architecture
:return: keras model object
"""
input_shape = (DataProcessor.HEIGHT,
DataProcessor.WIDTH,
DataProcessor.NUM_CHANNELS)
model = Sequential()
model.add(Conv2D(24, 5, 5, subsample=(2, 2), activation='elu', input_shape=input_shape))
model.add(Conv2D(36, 5, 5, subsample=(2, 2), activation='elu'))
model.add(Conv2D(48, 5, 5, subsample=(2, 2), activation='elu'))
model.add(Conv2D(64, 3, 3, subsample=(1, 1), activation='elu'))
model.add(Conv2D(64, 3, 3, subsample=(1, 1), activation='elu'))
model.add(Flatten())
model.add(Dropout(0.5))
model.add(Dense(100))
model.add(Dropout(0.5))
model.add(Dense(50))
model.add(Dropout(0.5))
model.add(Dense(10))
model.add(Dense(1))
model.compile(loss='mse', optimizer='adam')
return model
def main():
train_generator, valid_generator, n_train, n_valid = DataProcessor.load()
model = CNN()
model.fit(train_generator, n_train, valid_generator, n_valid, NUM_EPOCHS)
model.save()
if __name__ == '__main__':
main()