项目
在 GitHub 查看
LongxingTan/Time-series-prediction
关于
tfts:基于 TensorFlow 的时间序列深度学习模型
人工智能与机器学习实测星标增长
- 24小时
- 0
- 7天
- 0
- 15天
- 0
- 1个月
- 正在收集历史
各周期内的星标净变化,周期相互重叠,并非每日新增。缺失的测量保持空白。星标代表关注度,不代表软件质量。
README_CN.md
原文青山遮不住,毕竟东流去。江晚正愁余,山深闻鹧鸪。
东流TFTS (TensorFlow Time Series) 是一个高效易用的时间序列框架,基于TensorFlow/ Keras。
快速使用
安装
- python >= 3.8
- tensorflow >= 2.4
pip install tfts matplotlib
入门使用
import matplotlib.pyplot as plt
import tensorflow as tf
import tfts
from tfts import AutoConfig, AutoModel, AutoModelForForecasting, KerasTrainer
train_length = 24
predict_sequence_length = 8
# 其中,train是包含(x_train, y_train)的tuple, valid包含(x_valid, y_valid)
(x_train, y_train), (x_valid, y_valid) = tfts.get_data("sine", train_length, predict_sequence_length, test_size=0.2)
model_name_or_path = 'seq2seq' # 'wavenet', 'transformer', 'rnn', 'tcn', 'bert', 'dlinear', 'nbeats', 'informer', 'autoformer'
config = AutoConfig.for_model(model_name_or_path)
model = AutoModelForForecasting.from_config(config, output_chunk_length=predict_sequence_length)
trainer = KerasTrainer(model)
trainer.train(
(x_train, y_train),
(x_valid, y_valid),
optimizer=tf.keras.optimizers.Adam(0.0007),
epochs=30,
)
model_dir = "./outputs/quickstart_forecasting"
trainer.save_model(model_dir)
restored_model = AutoModel.from_pretrained(model_dir, sample_batch=x_valid[:1])
pred = restored_model(x_valid, training=False).predictions.numpy()
trainer.plot(history=x_valid, true=y_valid, pred=pred)
plt.show()
训练自己的数据
为方便使用,将数据转化为三维作为tfts的输入
- 选项1
np.ndarray - 选项2
tf.data.Dataset - 选项3
tf.keras.utils.Sequence
编码类模型输入
import numpy as np
from tfts import AutoConfig, AutoModel, AutoModelForForecasting, KerasTrainer
train_length = 24
predict_sequence_length = 8
n_feature = 2
x_train = np.random.rand(1, train_length, n_feature)
y_train = np.random.rand(1, predict_sequence_length, 1)
x_valid = np.random.rand(1, train_length, n_feature)
y_valid = np.random.rand(1, predict_sequence_length, 1)
config = AutoConfig.for_model("rnn")
model = AutoModelForForecasting.from_config(config, output_chunk_length=predict_sequence_length)
trainer = KerasTrainer(model)
trainer.train(train_dataset=(x_train, y_train), valid_dataset=(x_valid, y_valid), epochs=1)
model_dir = "./outputs/encoder_only"
trainer.save_model(model_dir)
restored_model = AutoModel.from_pretrained(model_dir, sample_batch=x_valid[:1])
inference = restored_model(x_valid[:1], training=False).predictions.numpy()
print(inference.shape)
编码-解码类模型输入
# option1: np.ndarray — 使用规范的 TimeSeriesBatch 字段,以 dict 形式传入特征
import numpy as np
from tfts import AutoConfig, AutoModel, AutoModelForForecasting, KerasTrainer
train_length = 24
predict_sequence_length = 8
n_encoder_feature = 2
n_decoder_feature = 3
x_train = {
"past_values": np.random.rand(1, train_length, 1), # 观测序列: (batch, train_length, 1)
"past_time_features": np.random.rand(1, train_length, n_encoder_feature), # 编码器特征: (batch, train_length, encoder_features)
"future_time_features": np.random.rand(1, predict_sequence_length, n_decoder_feature), # 解码器特征: (batch, predict_sequence_length, decoder_features)
}
y_train = np.random.rand(1, predict_sequence_length, 1)
x_valid = {
"past_values": np.random.rand(1, train_length, 1),
"past_time_features": np.random.rand(1, train_length, n_encoder_feature),
"future_time_features": np.random.rand(1, predict_sequence_length, n_decoder_feature),
}
y_valid = np.random.rand(1, predict_sequence_length, 1)
config = AutoConfig.for_model("seq2seq")
model = AutoModelForForecasting.from_config(config, output_chunk_length=predict_sequence_length)
trainer = KerasTrainer(model)
trainer.train((x_train, y_train), (x_valid, y_valid), epochs=1)
model_dir = "./outputs/encoder_decoder"
trainer.save_model(model_dir)
restored_model = AutoModel.from_pretrained(model_dir, sample_batch=x_valid)
inference = restored_model(x_valid, training=False).predictions.numpy()
print(inference.shape)
# option2
import numpy as np
import tensorflow as tf
from tfts import AutoConfig, AutoModel, AutoModelForForecasting, KerasTrainer
class FakeReader(object):
def __init__(self, predict_sequence_length):
train_length = 24
n_encoder_feature = 2
n_decoder_feature = 3
self.x = np.random.rand(15, train_length, 1)
self.encoder_feature = np.random.rand(15, train_length, n_encoder_feature)
self.decoder_feature = np.random.rand(15, predict_sequence_length, n_decoder_feature)
self.target = np.random.rand(15, predict_sequence_length, 1)
def __len__(self):
return len(self.x)
def __getitem__(self, idx):
return {
"past_values": self.x[idx],
"past_time_features": self.encoder_feature[idx],
"future_time_features": self.decoder_feature[idx],
}, self.target[idx]
def iter(self):
for i in range(len(self.x)):
yield self[i]
predict_sequence_length = 10
train_reader = FakeReader(predict_sequence_length=predict_sequence_length)
train_loader = tf.data.Dataset.from_generator(
train_reader.iter,
({"past_values": tf.float32, "past_time_features": tf.float32, "future_time_features": tf.float32}, tf.float32),
)
train_loader = train_loader.batch(batch_size=1)
valid_reader = FakeReader(predict_sequence_length=predict_sequence_length)
valid_loader = tf.data.Dataset.from_generator(
valid_reader.iter,
({"past_values": tf.float32, "past_time_features": tf.float32, "future_time_features": tf.float32}, tf.float32),
)
valid_loader = valid_loader.batch(batch_size=1)
config = AutoConfig.for_model("seq2seq")
model = AutoModelForForecasting.from_config(config, output_chunk_length=predict_sequence_length)
trainer = KerasTrainer(model)
trainer.train(train_dataset=train_loader, valid_dataset=valid_loader, epochs=1)
model_dir = "./outputs/encoder_decoder_tfdata"
trainer.save_model(model_dir)
inference_inputs = next(iter(valid_loader.take(1)))[0]
restored_model = AutoModel.from_pretrained(model_dir, sample_batch=inference_inputs)
inference = restored_model(inference_inputs, training=False).predictions.numpy()
print(inference.shape)
修改模型配置参数
from tfts import AutoConfig, AutoModelForForecasting
config = AutoConfig.for_model('rnn')
print(config)
config.rnn_hidden_size = 128
model = AutoModelForForecasting.from_config(config, output_chunk_length=7)
搭建自己的模型
检查tfts AutoModel已支持的模型
- rnn
- tcn
- bert
- dlinear
- nbeats
- seq2seq
- wavenet
- transformer
- informer
- autoformer
import tensorflow as tf
from tensorflow.keras.layers import Input, Dense
from tfts import AutoBackbone, AutoConfig
train_length = 24
num_train_features = 15
predict_sequence_length = 8
def build_model():
class CustomForecaster(tf.keras.Model):
def __init__(self):
super().__init__()
config = AutoConfig.for_model("seq2seq")
self.backbone = AutoBackbone.from_config(config, output_chunk_length=predict_sequence_length)
self.projection = Dense(1, activation="sigmoid")
def call(self, inputs, training=None):
output = self.backbone(inputs, training=training)
return self.projection(output.native_forecast)
model = CustomForecaster()
model.compile(loss="mse", optimizer="rmsprop")
return model
示例
东流tfts专注业界领先的深度模型
- 时序预测:训练、恢复模型并进行预测
- 时序分类:训练、恢复并评估 FordA 分类模型
- 异常检测:训练、恢复、校准并检测 ECG 窗口
- 参数调优:保存每个 Optuna trial,并恢复最佳模型进行推理
- Bert模型 获得KDD CUP2022-百度风机功率预测第3名
- Seq2seq模型 获得阿里天池-AI earth人工智能气象挑战赛第4名
- 更多示例参考examples
引用
@misc{tfts2020,
author = {Longxing Tan},
title = {TFTS: Time series prediction},
year = {2020},
publisher = {GitHub},
journal = {GitHub repository},
howpublished = {\url{https://github.com/longxingtan/time-series-prediction}},
}
探索相关项目
加载中…