-
Notifications
You must be signed in to change notification settings - Fork 19
/
gen_test.py
174 lines (147 loc) · 5.8 KB
/
gen_test.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
import itertools
from pathlib import Path
import numpy as np
import tensorflow as tf
from config import Config
import model as _model
from data_loader import get_datasets
import matplotlib.pyplot as plt
plt.style.use("seaborn-darkgrid")
def get_np_array(session, model, next_element):
all_true = []
all_predicted = []
while True:
try:
x, y = session.run(next_element)
predictions = session.run(
model.predictions,
{model.driving_series: x, model.past_history: y},
)
true = np.reshape(y[:, -1], [-1]).tolist()
predicted = np.reshape(predictions, [-1]).tolist()
all_true += true
all_predicted += predicted
except tf.errors.OutOfRangeError:
break
return np.array(all_true), np.array(all_predicted)
def plot(
session,
model,
train_next_element,
val_next_element,
test_next_element,
name="tmp",
show=True,
):
val_true, val_predicted = get_np_array(session, model, val_next_element)
test_true, test_predicted = get_np_array(session, model, test_next_element)
val_size, test_size = len(val_true), len(test_true)
plt.figure()
plt.plot(range(val_size), val_true, label="val true")
plt.plot(range(val_size), val_predicted, label="val predicted")
plt.plot(
range(val_size, val_size + test_size), test_true, label="test true"
)
plt.plot(
range(val_size, val_size + test_size),
test_predicted,
label="test predicted",
)
plt.ylabel("target serie")
plt.xlabel("time steps")
plt.legend(loc="upper left")
plt.title(name)
if show:
plt.show()
else:
plt.savefig(name, dpi=400)
plt.close()
def evaluate(config, show=True, name="tmp"):
with tf.Graph().as_default():
train_set, val_set, test_set = get_datasets(config, shuffled=False)
train_set = train_set.batch(config.batch_size, drop_remainder=True)
val_set = val_set.batch(config.batch_size, drop_remainder=True)
test_set = test_set.batch(config.batch_size, drop_remainder=True)
model = _model.TimeAttnModel(config)
saver = tf.train.Saver(max_to_keep=1)
with tf.Session() as session:
session.run(tf.global_variables_initializer())
train_iterator = train_set.make_initializable_iterator()
val_iterator = val_set.make_initializable_iterator()
test_iterator = test_set.make_initializable_iterator()
train_next_element = train_iterator.get_next()
val_next_element = val_iterator.get_next()
test_next_element = test_iterator.get_next()
# Restore from last evaluated epoch
print(
"Restoring from: {}".format(config.log_path / "model-max-ckpt")
)
saver.restore(session, str(config.log_path / "model-max-ckpt"))
session.run(train_iterator.initializer)
train_scores = model.evaluate(session, train_next_element)
print("============Train=============")
print("RMSE: {:.5f}".format(train_scores["RMSE"]))
print("MAE: {:.5f}".format(train_scores["MAE"]))
print("MAPE: {:.5f}".format(train_scores["MAPE"]))
session.run(val_iterator.initializer)
val_scores = model.evaluate(session, val_next_element)
print("============Validation=============")
print("RMSE: {:.5f}".format(val_scores["RMSE"]))
print("MAE: {:.5f}".format(val_scores["MAE"]))
print("MAPE: {:.5f}".format(val_scores["MAPE"]))
session.run(test_iterator.initializer)
test_scores = model.evaluate(session, test_next_element)
print("============Test=============")
print("RMSE: {:.5f}".format(test_scores["RMSE"]))
print("MAE: {:.5f}".format(test_scores["MAE"]))
print("MAPE: {:.5f}".format(test_scores["MAPE"]))
session.run(train_iterator.initializer)
session.run(val_iterator.initializer)
session.run(test_iterator.initializer)
plot(
session,
model,
train_next_element,
val_next_element,
test_next_element,
show=show,
name=name,
)
return train_scores, val_scores, test_scores
def main(argv=None):
# load hyper-parameters from configuration file
config_files = list(Path("gen_confs").glob("**/*.json"))
conf_names = [filepath.name for filepath in config_files]
configs = [Config.from_file(conf_file) for conf_file in config_files]
sets = ["train", "val", "test"]
scores = ["rmse", "mae", "mape"]
header = "conf," + (
",".join(["_".join(tup) for tup in itertools.product(sets, scores)])
)
with open("results.csv", "w") as f:
f.write(header + "\n")
for name, config in zip(conf_names, configs):
train_scores, val_scores, test_scores = evaluate(
config,
show=False,
name="gen_imgs/" + str(Path(name).with_suffix("")),
)
f.write(
",".join(
[
name,
str(train_scores["RMSE"]),
str(train_scores["MAE"]),
str(train_scores["MAPE"]),
str(val_scores["RMSE"]),
str(val_scores["MAE"]),
str(val_scores["MAPE"]),
str(test_scores["RMSE"]),
str(test_scores["MAE"]),
str(test_scores["MAPE"]),
]
)
+ "\n"
)
if __name__ == "__main__":
tf.app.run(main=main)