-
Notifications
You must be signed in to change notification settings - Fork 0
/
train.py
191 lines (153 loc) · 6.39 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
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
import os
# os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
import wandb
from wandb.keras import WandbCallback
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow import keras
from tensorflow.keras.layers import Dense, Dropout, LSTM, LeakyReLU, Flatten, BatchNormalization, SimpleRNN, GRU, BatchNormalization, TimeDistributed, Lambda, ReLU, PReLU
import numpy as np
import random
import json
import matplotlib.pyplot as plt
import pickle
from sklearn.model_selection import train_test_split
from tensorflow.keras.models import load_model
import seaborn as sns
# from utils.auto_df_support import DataProcessor
from utils.BASEDIR import BASEDIR
from utils.tokenizer import split_list, tokenize
import ast
import matplotlib.gridspec as gridspec
# from keras.callbacks.tensorboard_v1 import TensorBoard
# config = tf.ConfigProto()
# config.gpu_options.per_process_gpu_memory_fraction = 0.8
# set_session(tf.Session(config=config))
# sns.distplot(data_here)
# gpus = tf.config.experimental.list_physical_devices('GPU')
# if gpus:
# tf.config.experimental.set_virtual_device_configuration(
# gpus[0],
# [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=2048)])
# logical_gpus = tf.config.experimental.list_logical_devices('GPU')
if "CUDA_VISIBLE_DEVICES" not in os.environ:
physical_devices = tf.config.list_physical_devices('GPU')
tf.config.experimental.set_memory_growth(physical_devices[0], True)
# support = AutoDFSupport()
# support.init()
os.chdir(BASEDIR)
fig, ax = plt.subplots(5, 4)
ax = ax.flatten()
def show_pred_new(epoch=0, sample_idx=None, figure_idx=0):
if sample_idx is None:
sample_idx = random.randrange(len(auto.x_test))
x = auto.x_test[sample_idx]
y = auto.y_test[sample_idx]
pred = auto.model.predict_on_batch(np.array([x]))[0]
ax[figure_idx].cla()
ax[figure_idx].bar(range(3), y, label='ground')
ax[figure_idx].bar(range(3), pred, label='pred')
# ax[figure_idx].legend()
plt.show()
plt.pause(0.01)
# plt.savefig('models/model_imgs/{}'.format(epoch))
class ShowPredictions(tf.keras.callbacks.Callback):
def __init__(self):
super().__init__()
self.every = 20
self.sample_idxs = [random.randrange(len(auto.x_test)) for _ in range(len(ax))]
def on_epoch_end(self, epoch, logs=None):
if not (epoch + self.every) % self.every:
for idx, sample_idx in enumerate(self.sample_idxs):
show_pred_new(epoch, sample_idx, idx)
class AutoDynamicFollow:
def __init__(self, cfg):
self.test_size = 0.15
self.config = cfg
def start(self):
self.load_data()
self.train()
def load_data(self):
print("Loading data...", flush=True)
self.x_train = np.load('model_data/x_train.npy', allow_pickle=True)
self.y_train = np.load('model_data/y_train.npy', allow_pickle=True)
# self.x_test = np.load('model_data/x_test.npy')
# self.y_test = np.load('model_data/y_test.npy')
with open("model_data/scales", "rb") as f:
self.scales = json.load(f)
samples = 'all'
if samples != 'all':
self.x_train = np.array(self.x_train[:samples])
self.y_train = np.array(self.y_train[:samples])
flatten = False # already flattened in data processor
if flatten:
self.x_train = np.array([i.flatten() for i in self.x_train])
self.x_train, self.x_test, self.y_train, self.y_test = train_test_split(self.x_train, self.y_train, test_size=self.test_size)
print(self.x_train.shape)
print(self.y_train.shape)
print('{} traffic samples'.format(len([i for i in self.y_train if i[0] == 1])))
print('{} relaxed samples'.format(len([i for i in self.y_train if i[1] == 1])))
print('{} roadtrip samples'.format(len([i for i in self.y_train if i[2] == 1])))
def train(self):
# opt = keras.optimizers.Adadelta(lr=2) #lr=.000375)
# opt = keras.optimizers.RMSprop(lr=0.001)#, decay=1e-5)
# opt = keras.optimizers.Adagrad(lr=0.00025)
# opt = keras.optimizers.SGD(lr=0.1, momentum=0.3)
# opt = keras.optimizers.Adagrad()
# opt = 'rmsprop'
# opt = keras.optimizers.Adadelta()
# opt = 'adam'
opt = keras.optimizers.Adam(lr=self.config.learning_rate, amsgrad=True)
a_function = self.config.activation
self.model = Sequential()
# model.add(Dropout(0.2))
# model.add(GRU(128, return_sequences=True, input_shape=x_train.shape[1:]))
# model.add(GRU(64, return_sequences=True))
# model.add(GRU(64, return_sequences=True))
# model.add(GRU(64, return_sequences=True))
# model.add(GRU(y_train.shape[1], return_sequences=False))
# model.add(Lambda(lambda x: x[:,0,:,:], output_shape=(1, 50, 1) + x_train.shape[2:]))
# denses = [128, 64, 32]
self.model.add(Dense(self.config.dense_one, activation=a_function, input_shape=self.x_train.shape[1:]))
self.model.add(Dropout(config.dropout_one))
self.model.add(Dense(self.config.dense_two, activation=a_function))
self.model.add(Dropout(config.dropout_two))
self.model.add(Dense(self.y_train.shape[1], activation='softmax'))
self.model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['acc'])
# name = ', '.join(['{}'.format(n) for n in denses])
# print(name)
w_and_b = WandbCallback()
callbacks = [w_and_b, ShowPredictions()]
self.model.fit(self.x_train, self.y_train,
shuffle=True,
batch_size=self.config.batch_size,
epochs=self.config.epochs,
validation_data=(self.x_test, self.y_test),
# sample_weight=np.full((len(y_train)), 100),
callbacks=callbacks)
hyperparameter_defaults = dict(
dropout_one=0.175,
dropout_two=0.26,
dense_one=128,
dense_two=96,
activation='relu',
batch_size=96,
learning_rate=0.00044,
epochs=140,
)
wandb.init(project="auto-df", config=hyperparameter_defaults)
config = wandb.config
auto = AutoDynamicFollow(config)
auto.start()
# preds = model.predict(x_test).reshape(1, -1)
# diffs = [abs(pred - ground) for pred, ground in zip(preds[0], y_test[0])]
#
# print("Test accuracy: {}%".format(round(np.interp(sum(diffs) / len(diffs), [0, 1], [1, 0]) * 100, 4)))
#
# for i in range(20):
# c = random.randint(0, len(x_test))
# print('Ground truth: {}'.format(support.unnorm(y_test[c][0], 'eps_torque')))
# print('Prediction: {}'.format(support.unnorm(model.predict(np.array([x_test[c]]))[0][0], 'eps_torque')))
# print()
def save_model(name='model'):
auto.model.save('models/{}.h5'.format(name))