/
evaluate.py
183 lines (156 loc) · 6.2 KB
/
evaluate.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
import argparse
import copy
import os
import pdb
import sys
import numpy as np
import torch
from tabulate import tabulate
from models import MODELS
import src.dataset
from utils import cache
from constants import *
def get_prediction_folder(split, model_name, city):
return os.path.join("output", "predictions", split, model_name, city)
def main():
parser = argparse.ArgumentParser(description="Evaluate a given model")
parser.add_argument("-m",
"--model",
type=str,
required=True,
choices=MODELS,
help="which model to use")
parser.add_argument("-p",
"--model-path",
type=str,
help="path to the saved model")
parser.add_argument("-s",
"--split",
default="validation",
choices={"validation", "test"},
help="data split (for 'test' it only predicts)")
parser.add_argument("-c",
"--city",
required=True,
choices=CITIES,
help="which city to evaluate")
parser.add_argument("--overwrite",
default=False,
action="store_true",
help="overwrite existing predictions if they exist")
parser.add_argument("--channels",
nargs='+',
default=["Volume", "Speed", "Heading"],
help="List of channels to predict")
parser.add_argument("--tablefmt",
default="github",
help="how to format the results")
parser.add_argument("-v",
"--verbose",
action="count",
help="verbosity level")
args = parser.parse_args()
args.channels.sort(
key=lambda x: src.dataset.Traffic4CastSample.channel_to_index[x])
if args.verbose:
print(args)
Model = MODELS[args.model]
model = Model()
if args.model_path:
model.load_state_dict(torch.load(args.model_path))
model.eval()
if model.num_channels == len(args.channels):
if (model.num_channels != 3):
print(f"WARNING: Model predicts {model.num_channels} and "
f"{args.channels} were selected. Unselected channels will be "
"predicted as 0.")
selected_channels_transforms = [
src.dataset.Traffic4CastSample.Transforms.SelectChannels(
args.channels)
]
elif model.num_channels == 1:
print(f"WARNING: Model predicts {model.num_channels} channel but "
f"channels {args.channels} were selected. Iteration mode enabled."
"Unselected channels will be predicted as 0.")
selected_channels_transforms = [
src.dataset.Traffic4CastSample.Transforms.SelectChannels([c])
for c in args.channels
]
else:
print(f"ERROR: Model to channels missmatch. Model can predict "
f"{model.num_channels} channels. {len(args.channels)} were "
"selected.")
sys.exit(1)
transforms = [
lambda x: x.float(),
lambda x: x / 255,
src.dataset.Traffic4CastSample.Transforms.Permute("TCHW"),
]
dataset = src.dataset.Traffic4CastDataset(ROOT, args.split, [args.city],
transforms)
loader = torch.utils.data.DataLoader(
dataset,
batch_size=1,
shuffle=False,
num_workers=2,
collate_fn=src.dataset.Traffic4CastDataset.collate_list)
def predict(sample, channel_transforms):
predictions = np.zeros(EVALUATION_SHAPE)
for transform in channel_transforms:
s = copy.deepcopy(sample)
transform(s)
for f, p in model.predict(SUBMISSION_FRAMES[args.city], s).items():
for c_i, c in enumerate(transform.channels):
predictions[
SUBMISSION_FRAMES[args.city].index(f),
:,
:,
src.dataset.Traffic4CastSample.channel_to_index[c]
] = p[c_i]
predictions = predictions * 255.0
predictions = predictions.reshape(SUBMISSION_SHAPE)
return predictions
# Cache predictions to a specified path
to_overwrite = args.overwrite
cached_predict = lambda path, *args: cache(predict, path, to_overwrite,
*args)
if args.model_path:
model_name, _ = os.path.splitext(os.path.basename(args.model_path))
else:
model_name = args.model
dirname = get_prediction_folder(args.split, model_name, args.city)
os.makedirs(dirname, exist_ok=True)
to_str = lambda v: f"{v:.4f}"
errors = []
for sample in loader:
sample = sample[0]
predictions = cached_predict(
sample.predicted_path(dirname),
sample,
selected_channels_transforms,
)
if args.split == "validation":
# Prepare predictions
predictions = predictions / 255.0
predictions = predictions.reshape(*EVALUATION_SHAPE)
# Prepare groundtruth
sample.permute('THWC')
i = torch.tensor(SUBMISSION_FRAMES[args.city], dtype=torch.long)
gt = sample.data.index_select(0, i).numpy()
# Compute error
mse = np.mean((gt - predictions)**2, axis=(0, 1, 2))
errors.append(mse)
if args.verbose:
print(sample.date, "|", " | ".join(to_str(e) for e in mse))
elif args.split == "test":
if args.verbose:
print(sample.date)
if args.split == "validation":
errors = np.vstack(errors)
table = [[args.model] +
[to_str(v) for v in errors.mean(axis=0).tolist()] +
[to_str(errors.mean())]]
headers = ["model"] + CHANNELS + ["mean"]
print(tabulate(table, headers=headers, tablefmt=args.tablefmt))
if __name__ == "__main__":
main()