-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathmodel.py
More file actions
195 lines (156 loc) · 6.7 KB
/
Copy pathmodel.py
File metadata and controls
195 lines (156 loc) · 6.7 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
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
193
194
195
"""
Walk-Assistant : Recognizing sidewalk for the visually impaired
Copyright (C) 2018 Yoongi Kim (devlifecode@outlook.com)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import tensorflow as tf
from keras import Sequential
from keras import layers
from keras.layers import Reshape, Conv2D, MaxPool2D, UpSampling2D, Lambda, Input, Dense, GlobalAveragePooling2D, Flatten
from keras.layers import TimeDistributed as Dist
from keras.layers import BatchNormalization, Activation, DepthwiseConv2D, Bidirectional, CuDNNLSTM, LSTM
from keras.layers.core import Activation, Reshape, Permute
from keras.optimizers import Adam
from keras import Model
from keras.utils import to_categorical
from keras import backend as K
import cv2
import numpy as np
import csv
import matplotlib.pyplot as plt
import mobilenet_v2
import random
from keras.utils.generic_utils import CustomObjectScope
import keras
import glob
import os
from keras.models import Model, model_from_json
import datetime
from keras.callbacks import EarlyStopping
import argparse
from tqdm import tqdm
from filter import Filter
from data_loader import DataLoader
from keras.models import load_model
from keras.backend.tensorflow_backend import set_session
Graph = None
class MyModel:
def __init__(self, load, height, width, kernel, stride, lr, model_name):
"""
:param load: bool load model
:param height: 720
:param width: 1280
:param kernel: 80
:param stride: 80
:param lr: learning rate
:param model_name: 'main' or 'road'
"""
self.load = load
self.height = height
self.width = width
self.lr = lr
self.model_name = model_name
self.epoch = 0
self.kernel = kernel
self.stride = stride
DataLoader.mkdir('models/{}'.format(self.model_name))
if self.load:
self.model = self.load_model()
else:
self.model = self.build_model(self.kernel, self.stride)
opt = Adam(lr=lr)
self.model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['acc'])
def save_model(self, epoch, acc):
Model(self.model).save('models/{}/model.{}-{:.3f}.h5'.format(self.model_name, int(epoch), acc))
print('Saved model')
def load_model(self):
global Graph # multiprocess-able
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
config.gpu_options.per_process_gpu_memory_fraction = 0.3
set_session(tf.Session(config=config))
# model.99-0.98.h5
files = glob.glob('models/{}/model.*.h5'.format(self.model_name))
if len(files) == 0:
print('Trained model not found from "models/{}/model.*.h5"'.format(self.model_name))
print('Building new model because model file not found...')
return self.build_model(self.kernel, self.stride)
last_file = max(files, key=os.path.getctime)
file_name = last_file.replace('\\', '/').split('/')[-1].replace('model.', '').replace('.h5', '')
self.epoch = int(file_name.split('-')[0])
acc = float(file_name.split('-')[1])
with CustomObjectScope({'relu6': tf.nn.relu6, 'DepthwiseConv2D': keras.layers.DepthwiseConv2D, 'tf': tf}):
model = load_model(last_file)
model.summary()
Graph = tf.get_default_graph()
print('Loaded last model - {}, epoch: {}, acc: {}'.format(last_file, self.epoch, acc))
return model
def predict(self, X): # multiprocess-able
global Graph
with Graph.as_default():
Y = self.model.predict(X)
return Y
def build_model(self, kernel=80, stride=80):
i = Input(batch_shape=(None, self.height, self.width, 3))
x = Lambda(lambda x: tf.extract_image_patches(
x, ksizes=[1, kernel, kernel, 1], strides=[1, stride, stride, 1], rates=[1, 1, 1, 1], padding='VALID'))(i)
out_width = int((self.width - kernel)/stride + 1)
out_height = int((self.height - kernel)/stride + 1)
print(out_height, out_width)
x = Reshape([out_height, out_width, kernel, kernel, 3])(x)
x = Reshape([out_height*out_width, kernel, kernel, 3])(x) # [144, 80, 80, 3]
x = Dist(Conv2D(64, (3, 3), strides=(2, 2), padding='same'))(x)
x = Dist(BatchNormalization())(x)
x = Dist(Activation('relu'))(x)
x = Dist(MaxPool2D())(x)
x = Dist(Conv2D(128, (3, 3), strides=(2, 2), padding='same'))(x)
x = Dist(BatchNormalization())(x)
x = Dist(Activation('relu'))(x)
x = Dist(MaxPool2D())(x)
x = Dist(Conv2D(256, (3, 3), strides=(2, 2), padding='same'))(x)
x = Dist(BatchNormalization())(x)
x = Dist(Activation('relu'))(x)
x = Dist(MaxPool2D())(x)
x = Dist(Conv2D(512, (3, 3), strides=(2, 2), padding='same'))(x)
x = Dist(BatchNormalization())(x)
x = Dist(Activation('relu'))(x)
x = Dist(Flatten())(x)
x = Bidirectional(CuDNNLSTM(64, return_sequences=True))(x)
x = Bidirectional(CuDNNLSTM(64, return_sequences=True))(x)
x = Dist(Dense(2, activation='softmax'))(x)
x = Reshape([out_height, out_width, 2])(x)
model = Model(inputs=[i], outputs=[x])
model.summary()
return model
# def build_model(self, kernel=80, stride=80):
# i = Input(batch_shape=(None, self.height, self.width, 3))
# x = Lambda(lambda x: tf.extract_image_patches(
# x, ksizes=[1, kernel, kernel, 1], strides=[1, stride, stride, 1], rates=[1, 1, 1, 1], padding='VALID'))(i)
#
# out_width = int((self.width - kernel) / stride + 1)
# out_height = int((self.height - kernel) / stride + 1)
# print(out_height, out_width)
#
# x = Reshape([out_height, out_width, kernel, kernel, 3])(x)
# x = Reshape([out_height * out_width, kernel, kernel, 3])(x)
#
# x = mobilenet_v2.MobileNetv2(x)
#
# x = Dist(GlobalAveragePooling2D())(x)
# x = Dist(Dense(2, activation='softmax'))(x)
# x = Reshape([out_height, out_width, 2])(x)
#
# model = Model(inputs=[i], outputs=[x])
#
# model.summary()
#
# return model