This repository has been archived by the owner on Sep 19, 2023. It is now read-only.
/
make_mlp.py
66 lines (50 loc) · 1.82 KB
/
make_mlp.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
import gc
import sys
import joblib
import pandas as pd
from sklearn.pipeline import make_pipeline
import scipy
from ..data import df_to_X_y, df_to_X
from .mlp import MLPRegressor
from . import tscv
from .early_stopping import early_stopping_fit
BATCH_SIZE = 1024
LR = 1e-5
def optimize_n_epochs(train_set_path, preprocessor):
print('Loading dataset')
train_set = pd.read_parquet(train_set_path)
X_train, y_train, X_val, y_val = tscv.train_test_split(
*df_to_X_y(train_set),
date_vec=train_set['date_block_num'].values,
train_start=16)
del train_set
X_train = preprocessor.transform(X_train)
X_val = preprocessor.transform(X_val)
print('Finding optimal number of epochs')
_, n_epochs = early_stopping_fit(MLPRegressor(batch_size=BATCH_SIZE,
lr=LR),
X_train, y_train, X_val, y_val,
max_iter=50)
print(f'Best n_epochs={n_epochs}')
return n_epochs
if __name__ == '__main__':
train_set_path = sys.argv[1]
preprocessor = joblib.load(sys.argv[2])
output_path = sys.argv[3]
n_epochs = optimize_n_epochs(train_set_path, preprocessor)
gc.collect()
print('Loading dataset again')
train_set = pd.read_parquet(train_set_path)
X, y = df_to_X_y(train_set, window=16)
del train_set
gc.collect()
print('Transforming X before fit')
X = scipy.sparse.vstack([preprocessor.transform(X[:1000000, :]),
preprocessor.transform(X[1000000:, :])])
print('Building final estimator')
mlp = MLPRegressor(n_epochs=n_epochs, batch_size=BATCH_SIZE,
lr=LR)
print('Fitting final estimator')
mlp.fit(X, y)
reg = make_pipeline(preprocessor, mlp)
joblib.dump(reg, output_path)