表征模型使用教程

表征模型属于自监督模型里的一种,主要是希望能够学习到一种通用的特征表达用于下游任务;当前主流的自监督学习主要有基于生成式和基于对比学习的方法,当前案例使用的TS2Vec模型是一种基于对比学习的自监督模型

目前支持的表征模型
自监督模型的使用一般分为两个阶段
  • 不涉及任何下游任务,使用无标签的数据进行预训练

  • 使用带标签的数据在下游任务上 Fine-tune

表征模型结合下游任务的使用同样遵循自监督模型的使用范式,分为2个阶段:
  • 表征模型训练

  • 将表征模型的输出用于下游任务(当前案例的下游任务为预测任务)

为兼顾初学者和有一定的经验的开发者,本文给出两种表征任务的使用方法:
  • 表征模型和下游任务相结合的pipeline,初学者容易上手使用

  • 表征模型和下游任务解耦,详细展示表征模型和下游任务如何相结合使用

1. 方法一

内部集成的表征模型任务

目前支持的表征任务

1.1 准备数据集

import numpy as np
np.random.seed(2022)
import pandas as pd

import paddle
paddle.seed(2022)
from paddlets.models.representation import TS2Vec
from paddlets.datasets.repository import get_dataset
from paddlets.models.representation import ReprForecasting

data = get_dataset('ETTh1')
data, _ = data.split('2016-09-22 06:00:00')
train_data, test_data = data.split('2016-09-21 05:00:00')

1.2 训练

更多关于表征预测的信息请查看 ReprForecasting API

ts2vec_params = {"segment_size": 200,
                 "repr_dims": 320,
                 "batch_size": 32,
                 "sampling_stride": 200,
                 "max_epochs": 20}
model = ReprForecasting(in_chunk_len=200,
                        out_chunk_len=24,
                        sampling_stride=1,
                        repr_model=TS2Vec,
                        repr_model_params=ts2vec_params)
model.fit(train_data)

1.3 预测

model.predict(train_data)

1.4 回测

from paddlets.utils.backtest import backtest
score, predicts = backtest(
         data,
         model,
         start="2016-09-21 06:00:00",
         predict_window=24,
         stride=24,
         return_predicts=True)

1.5 模型的保存和加载

#save model
model.save(path="/tmp/rper_test/")

#load model
model = ReprForecasting.load(path="/tmp/rpr_test/")

2. 方法二

表征模型和下游回归任务解耦. 分为两个阶段,第一阶段是表征模型的训练和预测,第二阶段是下游任务模型的训练和预测

第一阶段:

  • 表征模型训练

  • 输出训练集和测试集的表征结果

第二阶段:

  • 构建回归模型的训练和测试样本

  • 训练和预测

准备数据集

import numpy as np
np.random.seed(2022)
import pandas as pd

import paddle
paddle.seed(2022)
from paddlets.models.representation.dl.ts2vec import TS2Vec
from paddlets.datasets.repository import get_dataset

data = get_dataset('ETTh1')
data, _ = data.split('2016-09-22 06:00:00')
train_data, test_data = data.split('2016-09-21 05:00:00')

表征模型训练

# initialize the TS2Vect object
ts2vec = TS2Vec(
 segment_size=200,
 repr_dims=320,
 batch_size=32,
 max_epochs=20,
)

# training
ts2vec.fit(train_data)

输出训练集和测试集的表征结果

sliding_len = 200 # Use past sliding_len length points to infer the representation of the current point in time
all_reprs = ts2vec.encode(data, sliding_len=sliding_len)
split_tag = len(train_data['OT'])
train_reprs = all_reprs[:, :split_tag]
test_reprs = all_reprs[:, split_tag:]

构建回归模型的训练和测试样本

# generate samples
def generate_pred_samples(features, data, pred_len, drop=0):
    n = data.shape[1]
    features = features[:, :-pred_len]
    labels = np.stack([ data[:, i:1+n+i-pred_len] for i in range(pred_len)], axis=2)[:, 1:]
    features = features[:, drop:]
    labels = labels[:, drop:]
    return features.reshape(-1, features.shape[-1]), \
             labels.reshape(-1, labels.shape[2]*labels.shape[3])

pre_len = 24 # prediction lengths

# generate training samples
train_to_numpy = train_data.to_numpy()
train_to_numpy = np.expand_dims(train_to_numpy, 0) # keep the same dimensions as the encode output
train_features, train_labels = generate_pred_samples(train_reprs, train_to_numpy, pre_len, drop=sliding_len)

# generate test samples
test_to_numpy = test_data.to_numpy()
test_to_numpy = np.expand_dims(test_to_numpy, 0)
test_features, test_labels = generate_pred_samples(test_reprs, test_to_numpy, pre_len)

训练和预测

# training
from sklearn.linear_model import Ridge
lr = Ridge(alpha=0.1)
lr.fit(train_features, train_labels)

# predict
test_pred = lr.predict(test_features)