-
Notifications
You must be signed in to change notification settings - Fork 118
/
train.py
196 lines (174 loc) · 7.23 KB
/
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
import os
import numpy as np
import random
import argparse
import warnings
import paddle
from paddlets.utils.config import Config
from paddlets.datasets.repository import get_dataset
from paddlets.transform.sklearn_transforms import StandardScaler
from paddlets.utils.manager import MODELS
from paddlets.metrics import MSE, MAE
from paddlets.utils import backtest
from paddlets.logger import Logger
logger = Logger(__name__)
warnings.filterwarnings("ignore")
def parse_args():
parser = argparse.ArgumentParser(description='Time Series Forecasting')
# Common params
parser.add_argument("--config", help="The path of config file.", type=str)
parser.add_argument(
'--device',
help='Set the device place for training model.',
default='gpu',
choices=['cpu', 'gpu', 'xpu', 'npu', 'mlu'],
type=str)
parser.add_argument(
'--save_dir',
help='The directory for saving the model snapshot.',
type=str,
default='./output/')
parser.add_argument(
'--do_eval',
help='Whether to do evaluation after training.',
action='store_true')
parser.add_argument(
'--checkpoints',
help='model checkpoints for eval.',
type=str,
default=None)
parser.add_argument(
'--time_feat',
help='Whether to do evaluation after training.',
action='store_true')
# Runntime params
parser.add_argument(
'--csv_path', help='input test csv format file in predict.', type=str)
parser.add_argument('--seq_len', help='input length in training.', type=int)
parser.add_argument(
'--predict_len', help='output length in training.', type=int)
parser.add_argument('--epoch', help='Iterations in training.', type=int)
parser.add_argument(
'--batch_size', help='Mini batch size of one gpu or cpu. ', type=int)
parser.add_argument('--learning_rate', help='Learning rate.', type=float)
# Other params
parser.add_argument(
'--seed', help='Set the random seed in training.', default=42, type=int)
parser.add_argument(
'--iters', help='Set the iters in training.', default=1, type=int)
parser.add_argument(
'--opts', help='Update the key-value pairs of all options.', nargs='+')
return parser.parse_args()
def main(args):
paddle.set_device(args.device)
seed = args.seed
paddle.seed(seed)
np.random.seed(seed)
random.seed(seed)
assert args.config is not None, \
'No configuration file specified, please set --config'
for iter in range(args.iters):
cfg = Config(
args.config,
learning_rate=args.learning_rate,
epoch=args.epoch,
seq_len=args.seq_len,
predict_len=args.predict_len,
batch_size=args.batch_size,
opts=args.opts)
batch_size = cfg.batch_size
dataset = cfg.dataset
predict_len = cfg.predict_len
seq_len = cfg.seq_len
epoch = cfg.epoch
split = dataset.get('split', None)
do_eval = cfg.dic.get('do_eval', True)
logger.info(cfg.__dict__)
ts_val, ts_test = None, None
if dataset['name'] == 'TSDataset':
import pandas as pd
from paddlets import TSDataset
df = pd.read_csv(dataset['train_path'])
ts_train = TSDataset.load_from_dataframe(df,
**cfg.dic['info_params'])
if dataset.get('val_path', False):
df = pd.read_csv(dataset['val_path'])
ts_val = TSDataset.load_from_dataframe(df,
**cfg.dic['info_params'])
else:
if split:
ts_train, ts_val, ts_test = get_dataset(dataset['name'], split,
seq_len)
else:
assert do_eval == False, 'if not split test data, please set do_eval False'
ts_train = get_dataset(dataset['name'], split, seq_len)
model = MODELS.components_dict[cfg.model['name']](
in_chunk_len=seq_len,
out_chunk_len=cfg.predict_len,
batch_size=batch_size,
max_epochs=epoch,
**cfg.model['model_cfg'])
scaler = StandardScaler()
scaler.fit(ts_train)
ts_train = scaler.transform(ts_train)
ts_val = scaler.transform(ts_val)
if ts_test is not None:
ts_test = scaler.transform(ts_test)
if args.time_feat:
logger.info('generate times feature')
from paddlets.transform import TimeFeatureGenerator
if dataset.get('use_holiday', False):
ts_all = get_dataset(dataset['name'])
time_feature_generator = TimeFeatureGenerator(feature_cols=[
'minuteofhour', 'hourofday', 'dayofmonth', 'dayofweek',
'dayofyear', 'monthofyear', 'weekofyear', 'holidays'
])
ts_all = time_feature_generator.fit_transform(ts_all)
ts_train._known_cov = ts_all._known_cov[split['train'][0]:split[
'train'][1]]
ts_val._known_cov = ts_all._known_cov[split['val'][0] - seq_len:
split['val'][1]]
ts_test._known_cov = ts_all._known_cov[split['test'][0] -
seq_len:split['test'][1]]
else:
time_feature_generator = TimeFeatureGenerator(feature_cols=[
'hourofday', 'dayofmonth', 'dayofweek', 'dayofyear'
])
ts_train = time_feature_generator.fit_transform(ts_train)
ts_val = time_feature_generator.fit_transform(ts_val)
ts_test = time_feature_generator.fit_transform(ts_test)
setting = cfg.model['name'] + '_' + dataset['name'] + '_' + str(
seq_len) + '_' + str(predict_len) + '_' + str(iter) + '/'
if args.checkpoints is None:
logger.info('start training...')
model.fit(ts_train, ts_val)
logger.info('save best model...')
save_dir = os.path.join(args.save_dir, setting)
if not os.path.exists(save_dir):
os.makedirs(save_dir)
else:
import shutil
shutil.rmtree(save_dir)
os.makedirs(save_dir)
model.save(save_dir + '/checkpoints/')
else:
from paddlets.models.model_loader import load
model = load(args.checkpoints + '/checkpoints')
metric = model.eval(ts_val)
logger.info(metric)
logger.info('start backtest...')
if do_eval and ts_test is not None:
metrics_score = backtest(
data=ts_test,
model=model,
predict_window=predict_len,
stride=1,
metric=[MSE(), MAE()], )
logger.info(setting + f"{metrics_score}")
for metric in metrics_score.keys():
logger.info(
f"{metric}: {np.mean([v for v in metrics_score[metric].values()])}"
)
if __name__ == '__main__':
args = parse_args()
main(args)