-
Notifications
You must be signed in to change notification settings - Fork 37
/
trAISformer.py
196 lines (172 loc) · 7.42 KB
/
trAISformer.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
192
193
194
195
196
#!/usr/bin/env python
# coding: utf-8
# coding=utf-8
# Copyright 2021, Duong Nguyen
#
# Licensed under the CECILL-C License;
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.cecill.info
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Pytorch implementation of TrAISformer---A generative transformer for
AIS trajectory prediction
https://arxiv.org/abs/2109.03958
"""
import numpy as np
from numpy import linalg
import matplotlib.pyplot as plt
import os
import sys
import pickle
from tqdm import tqdm
import math
import logging
import pdb
import torch
import torch.nn as nn
from torch.nn import functional as F
import torch.optim as optim
from torch.optim.lr_scheduler import LambdaLR
from torch.utils.data import Dataset, DataLoader
import models, trainers, datasets, utils
from config_trAISformer import Config
cf = Config()
TB_LOG = cf.tb_log
if TB_LOG:
from torch.utils.tensorboard import SummaryWriter
tb = SummaryWriter()
# make deterministic
utils.set_seed(42)
torch.pi = torch.acos(torch.zeros(1)).item() * 2
if __name__ == "__main__":
device = cf.device
init_seqlen = cf.init_seqlen
## Logging
# ===============================
if not os.path.isdir(cf.savedir):
os.makedirs(cf.savedir)
print('======= Create directory to store trained models: ' + cf.savedir)
else:
print('======= Directory to store trained models: ' + cf.savedir)
utils.new_log(cf.savedir, "log")
## Data
# ===============================
moving_threshold = 0.05
l_pkl_filenames = [cf.trainset_name, cf.validset_name, cf.testset_name]
Data, aisdatasets, aisdls = {}, {}, {}
for phase, filename in zip(("train", "valid", "test"), l_pkl_filenames):
datapath = os.path.join(cf.datadir, filename)
print(f"Loading {datapath}...")
with open(datapath, "rb") as f:
l_pred_errors = pickle.load(f)
for V in l_pred_errors:
try:
moving_idx = np.where(V["traj"][:, 2] > moving_threshold)[0][0]
except:
moving_idx = len(V["traj"]) - 1 # This track will be removed
V["traj"] = V["traj"][moving_idx:, :]
Data[phase] = [x for x in l_pred_errors if not np.isnan(x["traj"]).any() and len(x["traj"]) > cf.min_seqlen]
print(len(l_pred_errors), len(Data[phase]))
print(f"Length: {len(Data[phase])}")
print("Creating pytorch dataset...")
# Latter in this scipt, we will use inputs = x[:-1], targets = x[1:], hence
# max_seqlen = cf.max_seqlen + 1.
if cf.mode in ("pos_grad", "grad"):
aisdatasets[phase] = datasets.AISDataset_grad(Data[phase],
max_seqlen=cf.max_seqlen + 1,
device=cf.device)
else:
aisdatasets[phase] = datasets.AISDataset(Data[phase],
max_seqlen=cf.max_seqlen + 1,
device=cf.device)
if phase == "test":
shuffle = False
else:
shuffle = True
aisdls[phase] = DataLoader(aisdatasets[phase],
batch_size=cf.batch_size,
shuffle=shuffle)
cf.final_tokens = 2 * len(aisdatasets["train"]) * cf.max_seqlen
## Model
# ===============================
model = models.TrAISformer(cf, partition_model=None)
## Trainer
# ===============================
trainer = trainers.Trainer(
model, aisdatasets["train"], aisdatasets["valid"], cf, savedir=cf.savedir, device=cf.device, aisdls=aisdls, INIT_SEQLEN=init_seqlen)
## Training
# ===============================
if cf.retrain:
trainer.train()
## Evaluation
# ===============================
# Load the best model
model.load_state_dict(torch.load(cf.ckpt_path))
v_ranges = torch.tensor([2, 3, 0, 0]).to(cf.device)
v_roi_min = torch.tensor([model.lat_min, -7, 0, 0]).to(cf.device)
max_seqlen = init_seqlen + 6 * 4
model.eval()
l_min_errors, l_mean_errors, l_masks = [], [], []
pbar = tqdm(enumerate(aisdls["test"]), total=len(aisdls["test"]))
with torch.no_grad():
for it, (seqs, masks, seqlens, mmsis, time_starts) in pbar:
seqs_init = seqs[:, :init_seqlen, :].to(cf.device)
masks = masks[:, :max_seqlen].to(cf.device)
batchsize = seqs.shape[0]
error_ens = torch.zeros((batchsize, max_seqlen - cf.init_seqlen, cf.n_samples)).to(cf.device)
for i_sample in range(cf.n_samples):
preds = trainers.sample(model,
seqs_init,
max_seqlen - init_seqlen,
temperature=1.0,
sample=True,
sample_mode=cf.sample_mode,
r_vicinity=cf.r_vicinity,
top_k=cf.top_k)
inputs = seqs[:, :max_seqlen, :].to(cf.device)
input_coords = (inputs * v_ranges + v_roi_min) * torch.pi / 180
pred_coords = (preds * v_ranges + v_roi_min) * torch.pi / 180
d = utils.haversine(input_coords, pred_coords) * masks
error_ens[:, :, i_sample] = d[:, cf.init_seqlen:]
# Accumulation through batches
l_min_errors.append(error_ens.min(dim=-1))
l_mean_errors.append(error_ens.mean(dim=-1))
l_masks.append(masks[:, cf.init_seqlen:])
l_min = [x.values for x in l_min_errors]
m_masks = torch.cat(l_masks, dim=0)
min_errors = torch.cat(l_min, dim=0) * m_masks
pred_errors = min_errors.sum(dim=0) / m_masks.sum(dim=0)
pred_errors = pred_errors.detach().cpu().numpy()
## Plot
# ===============================
plt.figure(figsize=(9, 6), dpi=150)
v_times = np.arange(len(pred_errors)) / 6
plt.plot(v_times, pred_errors)
timestep = 6
plt.plot(1, pred_errors[timestep], "o")
plt.plot([1, 1], [0, pred_errors[timestep]], "r")
plt.plot([0, 1], [pred_errors[timestep], pred_errors[timestep]], "r")
plt.text(1.12, pred_errors[timestep] - 0.5, "{:.4f}".format(pred_errors[timestep]), fontsize=10)
timestep = 12
plt.plot(2, pred_errors[timestep], "o")
plt.plot([2, 2], [0, pred_errors[timestep]], "r")
plt.plot([0, 2], [pred_errors[timestep], pred_errors[timestep]], "r")
plt.text(2.12, pred_errors[timestep] - 0.5, "{:.4f}".format(pred_errors[timestep]), fontsize=10)
timestep = 18
plt.plot(3, pred_errors[timestep], "o")
plt.plot([3, 3], [0, pred_errors[timestep]], "r")
plt.plot([0, 3], [pred_errors[timestep], pred_errors[timestep]], "r")
plt.text(3.12, pred_errors[timestep] - 0.5, "{:.4f}".format(pred_errors[timestep]), fontsize=10)
plt.xlabel("Time (hours)")
plt.ylabel("Prediction errors (km)")
plt.xlim([0, 12])
plt.ylim([0, 20])
# plt.ylim([0,pred_errors.max()+0.5])
plt.savefig(cf.savedir + "prediction_error.png")
# Yeah, done!!!