步骤 1:在 Azure 上设置 TimeGEN-1 端点帐户并生成 API 密钥

  • 访问 ml.azure.com
  • 登录或创建 Microsoft 帐户
  • 点击侧边栏中的“模型”
  • 在模型目录中搜索“TimeGEN”
  • 选择 TimeGEN-1
  • 点击“部署”,这将创建一个端点
  • 转到侧边栏中的“端点”,您将看到您的 TimeGEN-1 端点
  • 在该端点中,您将找到要使用的基础 URL 和 API 密钥

步骤 2:安装 Nixtla

在您喜欢的 Python 开发环境中

使用 pip 安装 nixtla

pip install nixtla

步骤 3:导入 Nixtla TimeGPT 客户端

from nixtla import NixtlaClient

您可以通过提供您的身份验证 API 密钥来实例化 NixtlaClient 类。

nixtla_client = NixtlaClient(
    base_url = "YOUR_BASE_URL",
    api_key = "YOUR_API_KEY"
)

步骤 4:开始进行预测!

现在您可以开始进行预测了!让我们导入一个使用经典 AirPassengers 数据集的示例。该数据集包含 1949 年至 1960 年澳大利亚每月航空乘客数量。首先,加载数据集并绘制图表

import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/Nixtla/transfer-learning-time-series/main/datasets/air_passengers.csv')
df.head()
时间戳
01949-01-01112
11949-02-01118
21949-03-01132
31949-04-01129
41949-05-01121
nixtla_client.plot(df, time_col='timestamp', target_col='value')

📘 数据要求

  • 确保目标变量列没有缺失或非数值。
  • 在第一个和最后一个日期戳之间(对于给定的频率)不要包含日期戳中的间隔/跳跃。预测函数不会填充缺失的日期。
  • 日期戳列的格式应能被 Pandas 读取(详情请参阅此链接)。

更多详情请参阅数据要求

👍 保存使用 TimeGEN 制作的图表

在 notebook 环境中,plot 方法会自动显示图表。要在本地保存图表,您可以这样做

fig = nixtla_client.plot(df, time_col='timestamp', target_col='value')

fig.savefig('plot.png', bbox_inches='tight')

进行预测

接下来,使用 SDK 的 forecast 方法预测未来 12 个月。设置以下参数

  • df: 包含时间序列数据的 pandas DataFrame。
  • h: horizons 是要预测的未来步数。
  • freq: 时间序列的频率,采用 Pandas 格式。参阅pandas 的可用频率。(如果您不提供任何频率,SDK 将尝试推断它)
  • time_col: 标识日期戳的列。
  • target_col: 要预测的变量。
timegen_fcst_df = nixtla_client.forecast(df=df, h=12, freq='MS', time_col='timestamp', target_col='value')
timegen_fcst_df.head()
INFO:nixtla.nixtla_client:Validating inputs...
INFO:nixtla.nixtla_client:Preprocessing dataframes...
INFO:nixtla.nixtla_client:Restricting input...
INFO:nixtla.nixtla_client:Calling Forecast Endpoint...
时间戳TimeGPT
01961-01-01437.837921
11961-02-01426.062714
21961-03-01463.116547
31961-04-01478.244507
41961-05-01505.646484
nixtla_client.plot(df, timegen_fcst_df, time_col='timestamp', target_col='value')