使用Moirai(LLM 转换器)进行时间序列预测

2025年03月19日 由 alex 发表 383 0

Moirai是Salesforce推出的一款时间序列语言模型。它以掌控命运的三位命运女神命名,易于使用且速度快捷(生成以下预测所用的墙钟时间仅为1.7秒)。Moirai是基于掩码编码器的通用时间序列预测Transformer,在大规模开放时间序列档案(LOTSA)[涵盖九个领域的270亿个观测值]上进行了训练。


Moirai的目标是打造一个具有泛化能力的模型。它通过专注于跨频率学习和利用大型数据集中不同的分布特性来实现这一目标。因此,它能够处理多元时间序列中任意数量的变量,实现零样本预测。


该数据集包含德克萨斯州电网平衡机构ERCOT的小时负荷值。Moirai要求数据采用GluonTS格式,因此我们需要将数据框转换为该格式。


import torch
import matplotlib.pyplot as plt
import pandas as pd
from gluonts.dataset.pandas import PandasDataset
from gluonts.dataset.split import split
from uni2ts.eval_util.plot import plot_single
from uni2ts.model.moirai import MoiraiForecast, MoiraiModule
SIZE = "small"  # Model size
PDT = 64  # Prediction length
CTX = 200  # Context length
PSZ = "auto"  # Patch size
BSZ = 32  # Batch size
TEST = 64  # Test set length
# Load data
df = pd.read_csv("Ercot_Native_Load_2025 (1).csv")
df["timestamp"] = pd.to_datetime(df["Date"])
df.set_index("timestamp", inplace=True)
df["ERCOT"] = pd.to_numeric(df["ERCOT"], errors="coerce")
df = df.asfreq("h")  # Hourly frequency
# Convert into GluonTS dataset
ds = PandasDataset(dict(df[["ERCOT"]]))


训练-测试集划分

我们将数据集分为训练集和测试集。测试集包含最后64小时的数据。


train, test_template = split(ds, offset=-TEST)
test_data = test_template.generate_instances(
    prediction_length=PDT,
    windows=TEST // PDT,
    distance=PDT,
)


模型设置

Moirai是一个大规模的时间序列Transformer模型。我们加载一个预训练版本,并对其进行配置以适用于ERCOT数据。


model = MoiraiForecast(
    module=MoiraiModule.from_pretrained(f"Salesforce/moirai-1.0-R-{SIZE}"),
    prediction_length=PDT,
    context_length=CTX,
    patch_size=PSZ,
    num_samples=100,
    target_dim=1,
    feat_dynamic_real_dim=ds.num_feat_dynamic_real,
    past_feat_dynamic_real_dim=ds.num_past_feat_dynamic_real,
)


我们创建一个预测器并生成预测结果。


predictor = model.create_predictor(batch_size=BSZ)
forecasts = predictor.predict(test_data.input)


可视化

我们提取一个示例并绘制结果。


input_it = iter(test_data.input)
label_it = iter(test_data.label)
forecast_it = iter(forecasts)
inp = next(input_it)
label = next(label_it)
forecast = next(forecast_it)
plot_single(
    inp,
    label,
    forecast,
    context_length=CTX,
    name="moirai_forecast",
    show_label=True,
)
plt.show()


4


Moirai仅需极少的设置即可预测ERCOT的负荷。它的不确定性范围较宽,但总体来说,这是一个不错的框架。

文章来源:https://medium.com/@kylejones_47003/time-series-forecasting-with-moirai-5d063a40e9ed
欢迎关注ATYUN官方公众号
商务合作及内容投稿请联系邮箱:bd@atyun.com
评论 登录
热门职位
Maluuba
20000~40000/月
Cisco
25000~30000/月 深圳市
PilotAILabs
30000~60000/年 深圳市
写评论取消
回复取消