-
Notifications
You must be signed in to change notification settings - Fork 4
/
mamba_train.py
245 lines (211 loc) · 7.42 KB
/
mamba_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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
"""
Proprioception Is All You Need: Terrain Classification for Boreal Forests
Damien LaRocque*, William Guimont-Martin, David-Alexandre Duclos, Philippe Giguère, Francois Pomerleau
---
This script was inspired by the MAIN.m script in the T_DEEP repository from Ph0bi0 : https://github.com/Ph0bi0/T_DEEP
"""
from pathlib import Path
import os
import numpy as np
import pandas as pd
from utils import models, preprocessing
cwd = Path.cwd()
DATASET = os.environ.get("DATASET", "vulpi") # 'husky' or 'vulpi' or 'combined'
COMBINED_PRED_TYPE = os.environ.get(
"COMBINED_PRED_TYPE", "class"
) # 'class' or 'dataset'
CHECKPOINT = os.environ.get("CHECKPOINT", None)
if DATASET == "husky":
csv_dir = cwd / "data" / "borealtc"
elif DATASET == "vulpi":
csv_dir = cwd / "data" / "vulpi"
elif DATASET == "combined":
csv_dir = dict(vulpi=cwd / "data" / "vulpi", husky=cwd / "data" / "borealtc")
results_dir = cwd / "results"
mat_dir = cwd / "data"
if CHECKPOINT is not None:
CHECKPOINT = cwd / "checkpoints" / CHECKPOINT
RANDOM_STATE = 21
# Define channels
columns = {
"imu": {
"wx": True,
"wy": True,
"wz": True,
"ax": True,
"ay": True,
"az": True,
},
"pro": {
"velL": True,
"velR": True,
"curL": True,
"curR": True,
},
}
if DATASET == "combined":
summary = {}
for key in csv_dir.keys():
summary[key] = pd.DataFrame({"columns": pd.Series(columns)})
else:
summary = pd.DataFrame({"columns": pd.Series(columns)})
# Get recordings
if DATASET == "combined":
terr_dfs = {}
terrains = []
terr_df_husky = preprocessing.get_recordings(csv_dir["husky"], summary["husky"])
terr_df_vulpi = preprocessing.get_recordings(csv_dir["vulpi"], summary["vulpi"])
terr_dfs["husky"] = terr_df_husky
terr_dfs["vulpi"] = terr_df_vulpi
if COMBINED_PRED_TYPE == "class":
for key in csv_dir.keys():
terrains += sorted(terr_dfs[key]["imu"].terrain.unique())
elif COMBINED_PRED_TYPE == "dataset":
terrains = list(csv_dir.keys())
else:
terr_dfs = preprocessing.get_recordings(csv_dir, summary)
terrains = sorted(terr_dfs["imu"].terrain.unique())
# Set data partition parameters
N_FOLDS = 5
PART_WINDOW = 5 # seconds
# MOVING_WINDOWS = [1.5, 1.6, 1.7, 1.8] # seconds
MOVING_WINDOWS = [1.7] # seconds
# Data partition and sample extraction
if DATASET == "combined":
train_folds = {}
test_folds = {}
for key in csv_dir.keys():
_train_folds, _test_folds = preprocessing.partition_data(
terr_dfs[key],
summary[key],
PART_WINDOW,
N_FOLDS,
random_state=RANDOM_STATE,
)
train_folds[key] = _train_folds
test_folds[key] = _test_folds
else:
train_folds, test_folds = preprocessing.partition_data(
terr_dfs,
summary,
PART_WINDOW,
N_FOLDS,
random_state=RANDOM_STATE,
)
# Data augmentation parameters
# 0 < STRIDE < MOVING_WINDOWS
STRIDE = 0.1 # seconds
# If True, balance the classes while augmenting
# If False, imbalance the classes while augmenting
HOMOGENEOUS_AUGMENTATION = True
# Parameters
ssm_cfg_imu = {"d_state": 16, "d_conv": 4, "expand": 4}
ssm_cfg_pro = {"d_state": 16, "d_conv": 3, "expand": 6}
mamba_train_opt = {
"d_model_imu": 32,
"d_model_pro": 8,
"norm_epsilon": 6.3e-6,
"valid_perc": 0.1,
"init_learn_rate": 1.5e-3,
"learn_drop_factor": 0.25,
"reduce_lr_patience": 4,
"max_epochs": 60,
"minibatch_size": 16,
"valid_patience": 8,
"valid_frequency": None,
"gradient_threshold": None, # None to disable
"focal_loss": True,
"focal_loss_alpha": 0.75,
"focal_loss_gamma": 2.25,
"num_classes": len(terrains),
"out_method": "last_state", # "max_pool", "last_state"
}
# Model settings
MODEL = "mamba"
results = {}
for mw in MOVING_WINDOWS:
if DATASET == "combined":
aug_train_folds = {}
aug_test_folds = {}
for key in csv_dir.keys():
_aug_train_folds, _aug_test_folds = preprocessing.augment_data(
train_folds[key],
test_folds[key],
summary[key],
moving_window=mw,
stride=STRIDE,
homogeneous=HOMOGENEOUS_AUGMENTATION,
)
aug_train_folds[key] = _aug_train_folds
aug_test_folds[key] = _aug_test_folds
else:
aug_train_folds, aug_test_folds = preprocessing.augment_data(
train_folds,
test_folds,
summary,
moving_window=mw,
stride=STRIDE,
homogeneous=HOMOGENEOUS_AUGMENTATION,
)
print(f"Training models for a sampling window of {mw} seconds")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
results_per_fold = []
for k in range(N_FOLDS):
if DATASET == "combined":
aug_train_fold = {}
aug_test_fold = {}
for key in csv_dir.keys():
_aug_train_fold, _aug_test_fold = preprocessing.cleanup_data(
aug_train_folds[key][k], aug_test_folds[key][k]
)
_aug_train_fold, _aug_test_fold = preprocessing.normalize_data(
_aug_train_fold, _aug_test_fold
)
aug_train_fold[key] = _aug_train_fold
aug_test_fold[key] = _aug_test_fold
if COMBINED_PRED_TYPE == "class":
num_classes_vulpi = len(np.unique(aug_train_fold["vulpi"]["labels"]))
aug_train_fold["husky"]["labels"] += num_classes_vulpi
aug_test_fold["husky"]["labels"] += num_classes_vulpi
elif COMBINED_PRED_TYPE == "dataset":
aug_train_fold["vulpi"]["labels"] = np.full_like(
aug_train_fold["vulpi"]["labels"], 0
)
aug_test_fold["vulpi"]["labels"] = np.full_like(
aug_test_fold["vulpi"]["labels"], 0
)
aug_train_fold["husky"]["labels"] = np.full_like(
aug_train_fold["husky"]["labels"], 1
)
aug_test_fold["husky"]["labels"] = np.full_like(
aug_test_fold["husky"]["labels"], 1
)
else:
aug_train_fold, aug_test_fold = preprocessing.cleanup_data(
aug_train_folds[k], aug_test_folds[k]
)
aug_train_fold, aug_test_fold = preprocessing.normalize_data(
aug_train_fold, aug_test_fold
)
out = models.mamba_network(
aug_train_fold,
aug_test_fold,
mamba_train_opt,
ssm_cfg_imu,
ssm_cfg_pro,
dict(mw=mw, fold=k + 1, dataset=DATASET),
random_state=RANDOM_STATE,
test=True,
checkpoint=CHECKPOINT,
)
results_per_fold.append(out)
results["pred"] = np.hstack([r["pred"] for r in results_per_fold])
results["true"] = np.hstack([r["true"] for r in results_per_fold])
# results["conf"] = np.hstack([r["conf"] for r in results_per_fold])
results["ftime"] = np.hstack([r["ftime"] for r in results_per_fold])
results["ptime"] = np.hstack([r["ptime"] for r in results_per_fold])
# Store channels settings
results["channels"] = columns
# Store terrain labels
results["terrains"] = terrains
np.save(results_dir / f"results_{MODEL}_mw_{mw}.npy", results)