-
Notifications
You must be signed in to change notification settings - Fork 3
/
train_rocket.py
172 lines (144 loc) · 6.25 KB
/
train_rocket.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
########################################################################
#
# @author : Emmanouil Sylligardos
# @when : Winter Semester 2022/2023
# @where : LIPADE internship Paris
# @title : MSAD (Model Selection Anomaly Detection)
# @component: root
# @file : train_rocket
#
########################################################################
import argparse
import os
import re
from time import perf_counter
from tqdm import tqdm
from datetime import datetime
import numpy as np
import pandas as pd
from sklearn.pipeline import make_pipeline
from sklearn.utils import shuffle
from sktime.transformations.panel.rocket import MiniRocket
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import SGDClassifier
from utils.timeseries_dataset import create_splits, TimeseriesDataset
from utils.data_loader import DataLoader
from utils.metrics_loader import MetricsLoader
from utils.evaluator import save_classifier
from utils.config import *
from eval_rocket import eval_rocket
def run_rocket(data_path, split_per=0.7, seed=None, read_from_file=None, eval_model=False, path_save=None):
# Set up
window_size = int(re.search(r'\d+', data_path).group())
classifier_name = f"rocket_{window_size}"
if read_from_file is not None and "unsupervised" in read_from_file:
classifier_name += f"_{read_from_file.split('/')[-1].replace('unsupervised_', '')[:-len('.csv')]}"
training_stats = {}
# Load the splits
train_set, val_set, test_set = create_splits(
data_path,
split_per=split_per,
seed=seed,
read_from_file=read_from_file,
)
# Uncomment for testing
# train_set, val_set, test_set = train_set[:10], val_set[:10], test_set[:5]
# Load the data
training_data = TimeseriesDataset(data_path, fnames=train_set)
val_data = TimeseriesDataset(data_path, fnames=val_set)
test_data = TimeseriesDataset(data_path, fnames=test_set)
# Split data from labels
X_train, y_train = training_data.__getallsamples__().astype('float32'), training_data.__getalllabels__()
X_val, y_val = val_data.__getallsamples__().astype('float32'), val_data.__getalllabels__()
# For rocket 16 use only a random subset of the dataset to train (otherwise its untrainable)
print(f"Size of train dataset: {len(y_train)}, size of validation dataset: {len(y_val)}")
if len(y_train) > 1e6:
rand_ind = np.random.randint(low=0, high=len(y_train), size=int(len(y_train)/10))
X_train = X_train[rand_ind]
y_train = y_train[rand_ind]
rand_ind = np.random.randint(low=0, high=len(y_val), size=int(len(y_val)/10))
X_val = X_val[rand_ind]
y_val = y_val[rand_ind]
print(f"After... size of train dataset: {len(y_train)}, size of validation dataset: {len(y_val)}")
# Create the feature extractor, the scaler, and the classifier
minirocket = MiniRocket(num_kernels=10000, n_jobs=24)
scaler = StandardScaler(with_mean=False, copy=False)
clf = SGDClassifier(loss='log_loss', n_jobs=24)
tic = perf_counter()
X_train = minirocket.fit_transform(X_train).to_numpy()
print("minirocket fitted: {:.3f} secs".format(perf_counter()-tic))
# Setup batching
batch_size = 32768
indexes = np.arange(X_train.shape[0])
indexes_shuffled = shuffle(indexes)
# Fit scaler
for iterator_train in tqdm(range(0, X_train.shape[0], batch_size), desc='fitting-scaler'):
curr_batch = indexes_shuffled[iterator_train:iterator_train+batch_size]
X = X_train[curr_batch]
scaler.partial_fit(X)
# Transform the data in batches
for iterator_train in tqdm(range(0, X_train.shape[0], batch_size), desc='transforming'):
curr_batch = indexes_shuffled[iterator_train:iterator_train+batch_size]
X_train[curr_batch] = scaler.transform(X_train[curr_batch])
# Fit the classifier
for iterator_train in tqdm(range(0, X_train.shape[0], batch_size), desc='training'):
curr_batch = indexes_shuffled[iterator_train:iterator_train+batch_size]
X = X_train[curr_batch]
Y = y_train[curr_batch]
clf.partial_fit(X, Y, classes=list(np.arange(12)))
toc = perf_counter()
# Put every fitted component into a pipeline
classifier = make_pipeline(
minirocket,
scaler,
clf
)
del X_train
del y_train
# Print training time
training_stats["training_time"] = toc-tic
print(f"training time: {training_stats['training_time']:.3f} secs")
# Print valid accuracy and inference time
tic = perf_counter()
classifier_score = classifier.score(X_val, y_val)
toc = perf_counter()
training_stats["val_acc"] = classifier_score
training_stats["avg_inf_time"] = ((toc-tic)/X_val.shape[0]) * 1000
print(f"valid accuracy: {training_stats['val_acc']:.3%}")
print(f"inference time: {training_stats['avg_inf_time']:.3} ms")
# Save training stats
timestamp = datetime.now().strftime('%d%m%Y_%H%M%S')
df = pd.DataFrame.from_dict(training_stats, columns=["training_stats"], orient="index")
df.to_csv(os.path.join(save_done_training, f"{classifier_name}_{timestamp}.csv"))
# Save pipeline
saving_dir = os.path.join(path_save, classifier_name) if classifier_name.lower() not in path_save.lower() else path_save
saved_model_path = save_classifier(classifier, saving_dir, fname=None)
# Evaluate on test set or val set
if eval_model:
eval_set = test_set if len(test_set) > 0 else val_set
eval_rocket(
data_path=data_path,
model_path=saved_model_path,
path_save=path_save_results,
fnames=eval_set,
)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
prog='train_rocket',
description='Script for training the MiniRocket feature_extractor+classifier',
)
parser.add_argument('-p', '--path', type=str, help='path to the dataset to use', required=True)
parser.add_argument('-sp', '--split_per', type=float, help='split percentage for train and val sets', default=0.7)
parser.add_argument('-s', '--seed', type=int, help='seed for splitting train, val sets (use small number)', default=None)
parser.add_argument('-f', '--file', type=str, help='path to file that contains a specific split', default=None)
parser.add_argument('-e', '--eval-true', action="store_true", help='whether to evaluate the model on test data after training')
parser.add_argument('-ps', '--path_save', type=str, help='path to save the trained classifier', default="results/weights")
args = parser.parse_args()
run_rocket(
data_path=args.path,
split_per=args.split_per,
seed=args.seed,
read_from_file=args.file,
eval_model=args.eval_true,
path_save=args.path_save,
)