关于 alterlab-timesfm
alterlab-timesfm 是封装 TimesFM 的本地时间序列预测技能,面向需要免训练预测的分析与建模任务。它提供资源预检、分位数区间预测,并支持批量序列和协变量工作流。
主要功能
- 01零样本时间序列预测
- 02点预测与分位数区间
- 03批量预测多个序列
- 04TimesFM 2.5 协变量支持
- 05加载前检查系统资源
适用场景
- 01免训练预测销售或需求序列
- 02生成概率预测区间
- 03批量处理多条时间序列
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ alterlab-ieu/ alterlab-academic-skills --skill alterlab-timesfm安装后在 Claude Code 中输入/alterlab-timesfm确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
evals/evals.jsonexamples/anomaly-detection/detect_anomalies.pyexamples/anomaly-detection/output/anomaly_detection.jsonexamples/covariates-forecasting/demo_covariates.pyexamples/covariates-forecasting/output/covariates_metadata.jsonsales_with_covariates.csvexamples/global-temperature/generate_animation_data.pygenerate_gif.pygenerate_html.pyREADME.mdrun_example.shrun_forecast.pytemperature_anomaly.csvvisualize_forecast.pyexamples/global-temperature/output/animation_data.jsonforecast_output.csvforecast_output.jsoninteractive_forecast.htmlreferences/api_reference.mddata_preparation.mdoutput_and_config.mdpitfalls_and_validation.mdsystem_requirements.mdworkflows.mdscripts/check_system.pyforecast_csv.py详细介绍
TimesFM 预测
概述
TimesFM(时间序列基础模型)是 Google Research 开发的预训练、仅解码器的基础模型,用于时间序列预测。它支持零样本使用——输入时间序列,即可获得点预测和分位数预测区间,无需训练。timesfm 软件包(当前版本为 3.0.2)提供两个模型 API:
- TimesFM 2.5(200M,Apache-2.0 权重)——
timesfm.TimesFM_2p5_200M_torch,搭配ForecastConfig使用;支持单变量预测,也可通过 XReg 使用可选协变量。本技能的默认选择,也是商业或生产用途的唯一选择。 - TimesFM 3.0(约 330M,2026 年 8 月发布)——
timesfm3.TimesFM3Forecaster;支持单变量和多变量预测,并原生支持仅过去值和过去值加未来值协变量。其权重采用timesfm-non-commercial-license-v1.0许可,因此只能用于非商业研究,并告知用户相关限制。
本技能封装了 TimesFM,提供安全且适合 Agent 使用的本地推理。它包含一个强制预检系统检查器,会在加载模型前验证 RAM、GPU 显存和磁盘空间,确保 Agent 不会导致用户的设备崩溃。
关键数据:TimesFM 2.5 使用 2 亿参数(0.93 GB safetensors);TimesFM 3.0 使用约 3.3 亿参数(1.3 GB)。首次加载前请运行系统检查器,让资源不足的设备能够快速报错,避免发生交换或崩溃。
何时使用此技能
适用于以下情况:
- 预测任意单变量时间序列(销售、需求、传感器、生理指标、价格、天气)
- 需要零样本预测,且不想训练自定义模型
- 需要带校准预测区间(分位数)的概率预测
- 时间序列长度不限(模型可处理 1–16,384 个上下文点)
- 需要高效地对数百或数千条序列进行批量预测
- 想采用基础模型方法,而不是手动调整 ARIMA/ETS 参数
- 有相关通道或已知的未来驱动因素(使用 TimesFM 3.0 多变量预测加协变量,或 TimesFM 2.5 XReg)
不适用的情况
| 场景 | 改用 |
|---|---|
| 需要具有可解释系数的经典模型(ARIMA/SARIMAX 表)、VAR 或 Granger 因果关系检验 | alterlab-statsmodels |
| 时间序列分类、聚类、分段或相似性搜索 | alterlab-aeon |
| 预测前探索时间序列文件的结构和质量 | alterlab-eda |
| 表格数据(非时间序列)预测 | alterlab-scikit-learn |
异常检测说明:TimesFM 没有内置异常检测功能,但可以将分位数预测用作预测区间——区间 80% CI(q10–q90)以外的值在统计上较为异常。完整示例请参阅
examples/anomaly-detection/目录。
预检:系统需求检查
首次在一台设备上加载模型前,请运行系统检查器:加载模型会下载约 1 GB 的权重并分配数 GB 的 RAM。检查器会提前停止并给出清晰提示,避免加载过程崩溃或触发交换。
python scripts/check_system.py
此脚本会检查:
- 可用 RAM——低于 4 GB 时发出警告,低于 2 GB 时阻止加载
- GPU 可用性——检测 CUDA/MPS 设备和 VRAM
- 磁盘空间——确认有足够空间下载约 800 MB 的模型
- Python 版本——要求 3.10+
- 现有安装——检查是否已安装
timesfm和torch
注意:模型权重不会存储在此仓库中。TimesFM 权重(约 800 MB)会在首次使用时按需从 HuggingFace 下载,并缓存到
~/.cache/huggingface/。 预检检查器会在开始任何下载前确认资源充足。
flowchart TD
accTitle: Preflight System Check
accDescr: Decision flowchart showing the system requirement checks that must pass before loading TimesFM.
start["🚀 Run check_system.py"] --> ram{"RAM ≥ 4 GB?"}
ram -->|"Yes"| gpu{"GPU available?"}
ram -->|"No (2-4 GB)"| warn_ram["⚠️ Warning: tight RAM<br/>CPU-only, small batches"]
ram -->|"No (< 2 GB)"| block["🛑 BLOCKED<br/>Insufficient memory"]
warn_ram --> disk
gpu -->|"CUDA / MPS"| vram{"VRAM ≥ 2 GB?"}
gpu -->|"CPU only"| cpu_ok["✅ CPU mode<br/>Slower but works"]
vram -->|"Yes"| gpu_ok["✅ GPU mode<br/>Fast inference"]
vram -->|"No"| cpu_ok
gpu_ok --> disk{"Disk ≥ 2 GB free?"}
cpu_ok --> disk
disk -->|"Yes"| ready["✅ READY<br/>Safe to load model"]
disk -->|"No"| block_disk["🛑 BLOCKED<br/>Need space for weights"]
classDef ok fill:#dcfce7,stroke:#16a34a,stroke-width:2px,color:#14532d
classDef warn fill:#fef9c3,stroke:#ca8a04,stroke-width:2px,color:#713f12
classDef block fill:#fee2e2,stroke:#dc2626,stroke-width:2px,color:#7f1d1d
classDef neutral fill:#f3f4f6,stroke:#6b7280,stroke-width:2px,color:#1f2937
class ready,gpu_ok,cpu_ok ok
class warn_ram warn
class block,block_disk block
class start,ram,gpu,vram,disk neutral
各模型版本的硬件要求
| 模型 | 参数量 | RAM(CPU) | VRAM(GPU) | 磁盘空间 | 上下文长度 |
|---|---|---|---|---|---|
| TimesFM 3.0(非商业权重) | ~330M | ≥ 6 GB | ≥ 4 GB | ~1.3 GB | 最多 15,360 |
| TimesFM 2.5(默认) | 200M | ≥ 4 GB | ≥ 2 GB | ~0.9 GB | 最多 16,384 |
| TimesFM 2.0(已归档) | 500M | ≥ 16 GB | ≥ 8 GB | ~2 GB | 最多 2,048 |
| TimesFM 1.0(已归档) | 200M | ≥ 8 GB | ≥ 4 GB | ~800 MB | 最多 2,048 |
建议:默认使用 TimesFM 2.5(体积最小,采用 Apache-2.0 许可证,可完全通过
ForecastConfig控制)。如果非商业许可证适用于项目,可使用 TimesFM 3.0 处理多变量目标或原生协变量。1.0/2.0 检查点需要timesfm==1.3.0, 仅在复现旧结果时值得使用。实测 32 个序列 × 1,024 上下文长度时的 CPU 峰值内存(timesfm 3.0.2):2.5 约为 2.0 GB,3.0 约为 2.7 GB;上述阈值留有余量。使用python scripts/check_system.py --model v3.0检查 3.0。
🔧 安装
步骤 1:检查系统(始终先执行)
python scripts/check_system.py
步骤 2:安装 TimesFM
uv pip install "timesfm[torch]" # TimesFM 2.5 + 3.0, PyTorch backend
uv pip install "timesfm[torch,xreg]" # + XReg covariates for TimesFM 2.5 (adds JAX, scikit-learn)
uv pip install "timesfm[mlx]" # TimesFM 3.0 on Apple silicon without PyTorch
uv pip install "timesfm[flax]" # TimesFM 2.5 JAX/Flax backend
步骤 3:为硬件安装 PyTorch
# CPU-only wheels (small download, no CUDA libraries)
uv pip install torch --index-url https://download.pytorch.org/whl/cpu
# NVIDIA GPU: take the CUDA-specific index URL from https://pytorch.org/get-started/locally/
# Apple Silicon: the default PyPI wheel already includes MPS support
uv pip install torch
步骤 4:验证安装
from importlib.metadata import version
import timesfm # noqa: F401 (import check)
print(f"TimesFM version: {version('timesfm')}") # the package defines no __version__
print("Installation OK")
🎯 快速入门
最简示例(5 行)
import torch, numpy as np, timesfm
torch.set_float32_matmul_precision("high")
model = timesfm.TimesFM_2p5_200M_torch.from_pretrained(
"google/timesfm-2.5-200m-pytorch"
)
model.compile(timesfm.ForecastConfig(
max_context=1024, max_horizon=256, normalize_inputs=True,
use_continuous_quantile_head=True, force_flip_invariance=True,
infer_is_positive=True, fix_quantile_crossing=True,
))
point, quantiles = model.forecast(horizon=24, inputs=[
np.sin(np.linspace(0, 20, 200)), # any 1-D array
])
# point.shape == (1, 24) — median forecast
# quantiles.shape == (1, 24, 10) — 10th–90th percentile bands
TimesFM 3.0(多变量、原生协变量)
import numpy as np
from timesfm3 import TimesFM3Forecaster # non-commercial weights — see license note above
forecaster = TimesFM3Forecaster.from_pretrained("google/timesfm-3.0-pytorch", device="cpu") # or "cuda"
out = forecaster.predict(np.sin(np.linspace(0, 40, 512)).astype(np.float32),
horizon=24, return_quantiles=True)
# out.forecast.shape == (24,) — median forecast
# out.quantiles.shape == (24, 9) — q10..q90; index 4 is the median (no mean column)
# Two target channels plus one known-future covariate (context 256, horizon 32)
target = np.stack([np.sin(np.linspace(0, 24, 256)), np.cos(np.linspace(0, 24, 256))]).astype(np.float32)
future_cov = np.sin(np.linspace(0, 30, 256 + 32))[None, :].astype(np.float32)
out = forecaster.predict(target, horizon=32, past_future_covariates=future_cov, return_quantiles=True)
# out.forecast.shape == (2, 32); out.quantiles.shape == (2, 32, 9)
完整参数列表(predict_batch、past_only_covariates、make_positive 等):
references/api_reference.md。
从 CSV 进行预测
import pandas as pd, numpy as np
df = pd.read_csv("monthly_sales.csv", parse_dates=["date"], index_col="date")
# Convert each column to a list of arrays
inputs = [df[col].dropna().values.astype(np.float32) for col in df.columns]
point, quantiles = model.forecast(horizon=12, inputs=inputs)
# Build a results DataFrame
for i, col in enumerate(df.columns):
last_date = df[col].dropna().index[-1]
future_dates = pd.date_range(last_date, periods=13, freq="MS")[1:]
forecast_df = pd.DataFrame({
"date": future_dates,
"forecast": point[i],
"lower_80": quantiles[i, :, 1], # q10 — lower bound of 80% PI
"upper_80": quantiles[i, :, 9], # q90 — upper bound of 80% PI
})
print(f"\n--- {col} ---")
print(forecast_df.to_string(index=False))
使用协变量进行预测(XReg)
TimesFM 2.5 通过 forecast_with_covariates() 支持外生变量。该功能需要
timesfm[xreg],并且模型必须以 return_backcast=True 编译(否则会引发
ValueError)。TimesFM 3.0 可直接在 predict() 中接收协变量(见上文)。
# Requires: uv pip install "timesfm[torch,xreg]"
model.compile(timesfm.ForecastConfig(
max_context=1024, max_horizon=256, normalize_inputs=True,
use_continuous_quantile_head=True, fix_quantile_crossing=True,
return_backcast=True,
))
point, quantiles = model.forecast_with_covariates(
inputs=inputs,
dynamic_numerical_covariates={"price": price_arrays},
dynamic_categorical_covariates={"holiday": holiday_arrays},
static_categorical_covariates={"region": region_labels},
xreg_mode="xreg + timesfm", # or "timesfm + xreg"
)
# point / quantiles: one array per series — (horizon,) and (horizon, 10)
| 协变量类型 | 描述 | 示例 |
|---|---|---|
dynamic_numerical | 随时间变化的数值 | 价格、温度、促销支出 |
dynamic_categorical | 随时间变化的类别 | 节假日标记、星期几 |
static_numerical | 每个序列对应的数值 | 门店规模、账户年限 |
static_categorical | 每个序列对应的类别 | 门店类型、地区、产品类别 |
XReg 模式:
"xreg + timesfm"(默认):先根据协变量拟合上下文线性回归,再由 TimesFM 预测回归残差"timesfm + xreg":先由 TimesFM 进行预测,再根据协变量通过线性回归拟合 TimesFM 的残差
完整示例(含合成零售数据)请参见
examples/covariates-forecasting/。
异常检测(通过分位数区间)
TimesFM 没有内置异常检测功能,但分位数预测会自然地提供预测区间,可用于检测异常:
point, q = model.forecast(horizon=H, inputs=[values])
# 80% prediction interval
lower_80 = q[0, :, 1] # 10th percentile
upper_80 = q[0, :, 9] # 90th percentile
# Detect anomalies: values outside the 80% CI
actual = test_values # your holdout data
anomalies = (actual < lower_80) | (actual > upper_80)
# Severity levels
is_warning = (actual < q[0, :, 2]) | (actual > q[0, :, 8]) # outside 60% CI
is_critical = anomalies # outside 80% CI
| 严重程度 | 条件 | 说明 |
|---|---|---|
| 正常 | 在 60% 置信区间内 | 符合预期 |
| 警告 | 超出 60% 置信区间 | 不寻常,但有可能 |
| 严重 | 超出 80% 置信区间 | 统计上很罕见(概率 < 20%) |
完整示例(含可视化)请参见
examples/anomaly-detection/。
📊 输出、配置与工作流
输出结构和完整的 ForecastConfig 参考请参见
references/output_and_config.md。
分位数布局(TimesFM 2.5):
quantile_forecast的形状为(batch, horizon, 10)。 索引 0 是均值;q10 = 索引 1,q50(中位数)= 索引 5,q90 = 索引 9,因此 80% 预测区间为q[:,:,1]–q[:,:,9]。TimesFM 3.0 返回 9 列(q10–q90),中位数位于 索引 4;切换模型时请重新检查索引。
可复制粘贴的工作流(单序列、批处理、准确性评估)、GPU/内存性能调优,以及与
statsmodels / matplotlib / EDA 的集成,请参见
references/workflows.md。
📚 脚本
scripts/check_system.py— 必须运行的预检程序;首次加载模型前运行。报告 RAM/GPU/磁盘/Python/安装状态,并给出建议的per_core_batch_size。scripts/forecast_csv.py— 带自动系统检查的端到端 CSV 预测:python scripts/forecast_csv.py input.csv --horizon 24 \ --date-col date --value-cols sales,revenue --output forecasts.csv
📖 参考文档
详细指南位于 references/:
| 文件 | 内容 |
|---|---|
references/output_and_config.md | 输出形状、分位数索引映射、完整的 ForecastConfig 参数参考 |
references/workflows.md | 单次/批量/评估工作流、GPU 和内存调优、statsmodels/matplotlib/EDA 集成 |
references/pitfalls_and_validation.md | 常见陷阱、质量检查清单、已知错误、回归基线验证 |
references/system_requirements.md | 硬件等级、GPU/CPU 选择、内存估算公式 |
references/api_reference.md | 完整的 from_pretrained 选项、API 接口、输出形状 |
references/data_preparation.md | 输入格式、NaN 处理、CSV 加载、协变量设置 |
在宣布任何任务完成前,请运行质量检查清单,并查看
references/pitfalls_and_validation.md中的常见陷阱/错误 — 尤其要注意分位数索引的差一错误,以及负值序列的infer_is_positive。
模型版本
timeline
accTitle: TimesFM Version History
accDescr: Timeline of TimesFM model releases showing parameter counts and key improvements.
section 2024
TimesFM 1.0 : 200M params, 2K context, JAX only
TimesFM 2.0 : 500M params, 2K context, PyTorch + JAX
section 2025
TimesFM 2.5 : 200M params, 16K context, quantile head, no frequency indicator
section 2026
TimesFM 3.0 : ~330M params, 15K context, multivariate + covariates, non-commercial weights
| 版本 | 参数量 | 上下文长度 | 分位数头 | 频率标记 | 状态 |
|---|---|---|---|---|---|
| 3.0 | ~330M | 15,360 | ✅ 9 个十分位数 | ❌ | 最新(非商业用途权重) |
| 2.5 | 200M | 16,384 | ✅ 连续型(30M) | ❌ 已移除 | 默认(Apache-2.0) |
| 2.0 | 500M | 2,048 | ✅ 固定分桶 | ✅ 必需 | 已归档 |
| 1.0 | 200M | 2,048 | ✅ 固定分桶 | ✅ 必需 | 已归档 |
Hugging Face 检查点:
google/timesfm-3.0-pytorch(TimesFM 3.0;非商业许可证)google/timesfm-2.5-200m-pytorch(默认)google/timesfm-2.5-200m-flaxgoogle/timesfm-2.5-200m-transformers(🤗 Transformers 移植版,TimesFm2_5ModelForPrediction)google/timesfm-2.0-500m-pytorch(已归档)google/timesfm-1.0-200m-pytorch(已归档)
资源
- 论文:用于时间序列预测的仅解码器基础模型(ICML 2024)
- 代码仓库:https://github.com/google-research/timesfm
- Hugging Face:https://huggingface.co/collections/google/timesfm-release-66e4be5fdb56e960c1e482a6
- Google 博客:https://research.google/blog/a-decoder-only-foundation-model-for-time-series-forecasting/
- BigQuery 集成:https://cloud.google.com/bigquery/docs/timesfm-model
示例
examples/ 中提供了三个参考示例;它们均使用 TimesFM 2.5 API(输出于 2026-09 使用 timesfm 3.0.2 重新生成)。可将它们作为正确 API 用法和预期输出形状的依据。
| 示例 | 目录 | 演示内容 | 适用场景 |
|---|---|---|---|
| 全球气温预测 | examples/global-temperature/ | 基本的 model.forecast() 调用、CSV -> PNG -> GIF 流程、36 个月 NOAA 上下文、60%/80% 预测区间 | 入门示例;适用于任何单变量序列的复制粘贴基线 |
| 异常检测 | examples/anomaly-detection/ | 两阶段检测:对上下文进行线性去趋势 + Z-score 计算,对预测进行分位数 PI 检测;双面板可视化 | 任何需要检测历史数据和预测数据中异常值的任务 |
| 协变量(XReg) | examples/covariates-forecasting/ | forecast_with_covariates() API(TimesFM 2.5)、协变量分解、2x2 共享坐标轴可视化 | 零售、能源,或任何具有已知外生驱动因素的序列 |
运行示例
# Global temperature (TimesFM 2.5)
cd examples/global-temperature && python run_forecast.py && python visualize_forecast.py
# Anomaly detection (TimesFM 2.5)
cd examples/anomaly-detection && python detect_anomalies.py
# Covariates (data + API walkthrough; real inference needs timesfm[torch,xreg])
cd examples/covariates-forecasting && python demo_covariates.py
预期输出
| 示例 | 关键输出文件 | 验收标准 |
|---|---|---|
| global-temperature | output/forecast_output.json、output/forecast_visualization.png | point_forecast 有 12 个值;PNG 显示上下文、预测和 PI 区间 |
| anomaly-detection | output/anomaly_detection.json、output/anomaly_detection.png | 2023 年 9 月标记为 CRITICAL(z >= 3.0);注入异常中至少有 2 个预测结果为 CRITICAL |
| covariates-forecasting | output/sales_with_covariates.csv、output/covariates_data.png | CSV 有 108 行(3 家门店 x 36 周);各门店的价格数组各不相同 |
质量、常见错误与验证
在宣布任何任务完成之前,请运行任务后的质量检查清单,查看
已知错误(分位数差一、协变量预测跨度覆盖、基于残差的异常检测等),并运行
回归基线验证代码片段——详见 references/pitfalls_and_validation.md。
AlterLab Academic Skills 套件的一部分。