关于 timesfm-forecasting
timesfm-forecasting 是使用 Google Research 的 TimesFM 进行时间序列预测的 Agent 技能,面向需要零样本预测的分析人员。它提供硬件与数据集内存预检、批量预测、分位数区间及外生变量预测流程。
主要功能
- 01零样本单变量时间序列预测
- 02输出点预测与分位数区间
- 03支持批量预测多个序列
- 04使用外生变量进行预测
- 05模型加载前检查系统与数据集内存
适用场景
- 01预测销售、需求或传感器序列
- 02批量预测多家门店的数据
- 03以预测区间识别异常值
- 04结合促销或节假日等变量预测
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ google-research/ timesfm --skill timesfm-forecasting安装后在 Claude Code 中输入/timesfm-forecasting确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
examples/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/finetuning/finetune_lora.pyREADME.mdexamples/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.mdsystem_requirements.mdscripts/check_system.pyforecast_csv.py详细介绍
TimesFM 预测
概述
TimesFM(时间序列基础模型)是由 Google Research 开发的、用于时间序列预测的预训练仅解码器基础模型。它支持零样本工作——输入任意单变量时间序列,即可返回点预测以及经过校准的分位数预测区间,无需训练。
本技能包含一个强制性的预检系统检查器,在加载模型之前会先验证 RAM、GPU 显存和磁盘空间,从而确保 Agent 永远不会导致用户机器崩溃。
关键数字:TimesFM 2.5 使用 2 亿参数(磁盘上约 800 MB,CPU 上 RAM 约 1.5 GB,GPU 上 VRAM 约 1 GB)。已归档的 v1/v2 5 亿参数模型需要约 32 GB RAM。务必先运行系统检查器。
何时使用本技能
在以下情况下使用本技能:
- 预测任意单变量时间序列(销售、需求、传感器、生命体征、价格、天气)
- 你需要零样本预测,而无需训练自定义模型
- 你想要概率预测,并带有经过校准的预测区间(分位数)
- 你的时间序列具有任意长度(模型可处理 1–16,384 个上下文点)
- 你需要高效地批量预测数百或数千条序列
- 你想要基础模型方案,而不是手动调优 ARIMA/ETS 参数
- 你需要使用外生变量进行协变量预测(价格、促销、节假日、星期几效应)→ 使用
forecast_with_covariates()(TimesFM 2.5 +pip install timesfm[xreg])
在以下情况下不要使用本技能:
- 你需要具有系数可解释性的经典统计模型 → 使用
statsmodels - 你需要时间序列分类或聚类 → 使用
aeon - 你需要多变量向量自回归或 Granger 因果关系 → 使用
statsmodels - 你的数据是表格数据(非时间序列)→ 使用
scikit-learn - 你无法安装可选依赖项 → XReg 需要 scikit-learn 和 JAX
关于异常检测的说明:TimesFM 没有内置异常检测,但你可以使用分位数预测作为预测区间——超出 90% CI(q10–q90)的值在统计上属于异常。完整示例见
examples/anomaly-detection/。
⚠️ 强制性预检:系统要求检查
关键——在首次加载模型之前,务必运行系统检查器。
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
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"]
数据集预检(新增)
在加载实际数据之前,先验证它是否能放入内存:
# Quick estimate for your dataset
python scripts/check_system.py \
--num-series 1000 \
--context-length 1024 \
--horizon 24 \
--batch-size 32 \
--estimate-only
这会显示预计的内存需求,并在你的数据集过大时发出警告。
内存估算公式:
RAM ≈ 0.8 GB (model) + 0.5 GB (overhead) + (0.2 MB × num_series × context_length / 1000)
示例输出:
✅ 数据集可容纳:
Total CPU memory: 2.34 GB
Total GPU memory: 2.15 GB
⚠️ 数据集过大:
Dataset requires ~12.5 GB RAM but system has 8.0 GB.
Try: context_length=512 or process in chunks of 50 series.
各模型版本的硬件要求
| Model | Parameters | RAM (CPU) | VRAM (GPU) | Disk | Context |
|---|---|---|---|---|---|
| TimesFM 2.5(推荐) | 200M | ≥ 4 GB | ≥ 2 GB | ~800 MB | 最多 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。它更小、更快,并支持 8 倍长的上下文。
🔧 安装
步骤 1:验证系统(始终第一步)
python scripts/check_system.py
步骤 2:安装 TimesFM
# Using uv (fast)
uv pip install timesfm[torch]
# Or using pip
pip install timesfm[torch]
# For JAX/Flax backend (faster on TPU/GPU)
uv pip install timesfm[flax]
步骤 3:为你的硬件安装 PyTorch
# CUDA 12.1 (NVIDIA GPU)
pip install torch>=2.0.0 --index-url https://download.pytorch.org/whl/cu121
# CPU only
pip install torch>=2.0.0 --index-url https://download.pytorch.org/whl/cpu
# Apple Silicon (MPS)
pip install torch>=2.0.0 # MPS support is built-in
🎯 快速开始
最小示例
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
使用协变量进行预测(XReg)
TimesFM 2.5+ 通过 forecast_with_covariates() 支持外生变量。
需要 pip install timesfm[xreg]。
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, q = model.forecast(horizon=H, inputs=[values])
lower_90 = q[0, :, 1] # 10th percentile
upper_90 = q[0, :, 9] # 90th percentile
actual = test_values
anomalies = (actual < lower_90) | (actual > upper_90)
| 严重程度 | 条件 | 解释 |
|---|---|---|
| 正常 | 在 80% CI 内 | 预期行为 |
| 警告 | 在 80% CI 外 | 不寻常但可能发生 |
| 严重 | 在 90% CI 外 | 统计上罕见(< 10% 概率) |
完整示例(含可视化)见
examples/anomaly-detection/。
📊 理解输出
TimesFM 返回 (point_forecast, quantile_forecast):
point_forecast:形状(batch, horizon)—— 中位数(0.5 分位数)quantile_forecast:形状(batch, horizon, 10)—— 十个分位数切片:
| 索引 | 分位数 | 用途 |
|---|---|---|
| 0 | 均值 | 平均预测 |
| 1 | 0.1 | 80% PI 的下界 |
| 2 | 0.2 | 60% PI 的下界 |
| 5 | 0.5 | 中位数(= point_forecast) |
| 8 | 0.8 | 60% PI 的上界 |
| 9 | 0.9 | 80% PI 的上界 |
point, q = model.forecast(horizon=H, inputs=data)
lower_80 = q[:, :, 1] # 10th percentile
upper_80 = q[:, :, 9] # 90th percentile
median = q[:, :, 5]
🔧 ForecastConfig 参考
所有预测行为均由 timesfm.ForecastConfig 控制:
timesfm.ForecastConfig(
max_context=1024, # Max context window
max_horizon=256, # Max forecast horizon
normalize_inputs=True, # RECOMMENDED — prevents scale instability
per_core_batch_size=32, # Tune for memory
use_continuous_quantile_head=True, # Better quantile accuracy for long horizons
force_flip_invariance=True, # Ensures f(-x) = -f(x)
infer_is_positive=True, # Clamp forecasts ≥ 0 when all inputs > 0
fix_quantile_crossing=True, # Ensure q10 ≤ q20 ≤ ... ≤ q90
return_backcast=False, # Return backcast (for covariate workflows)
)
| 参数 | 默认值 | 何时更改 |
|---|---|---|
max_context | 0 | 设置为与您最长的历史窗口匹配 |
normalize_inputs | False | 始终设置为 True |
use_continuous_quantile_head | False | 为获得校准的 PI,设置为 True |
infer_is_positive | True | 对于可能为负的序列,设置为 False |
fix_quantile_crossing | False | 为获得单调分位数,设置为 True |
完整参数参考见 references/api_reference.md。
📋 常见工作流
单序列预测
import torch, numpy as np, pandas as pd, timesfm, matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
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=512, max_horizon=52, normalize_inputs=True,
use_continuous_quantile_head=True, fix_quantile_crossing=True,
))
df = pd.read_csv("weekly_demand.csv", parse_dates=["week"])
values = df["demand"].values.astype(np.float32)
point, quantiles = model.forecast(horizon=52, inputs=[values])
fig, ax = plt.subplots(figsize=(12, 5))
ax.plot(values[-104:], label="Historical")
x_fc = range(len(values[-104:]), len(values[-104:]) + 52)
ax.plot(x_fc, point[0], label="Forecast", color="tab:orange")
ax.fill_between(x_fc, quantiles[0, :, 1], quantiles[0, :, 9],
alpha=0.2, color="tab:orange", label="80% PI")
ax.legend(); ax.set_title("52-Week Demand Forecast")
plt.tight_layout(); plt.savefig("forecast.png", dpi=150)
批量预测(多个序列)
df = pd.read_csv("all_stores.csv", parse_dates=["date"], index_col="date")
inputs = [df[col].dropna().values.astype(np.float32) for col in df.columns]
point, quantiles = model.forecast(horizon=30, inputs=inputs)
import json
results = {col: {"forecast": point[i].tolist(),
"lower_80": quantiles[i, :, 1].tolist(),
"upper_80": quantiles[i, :, 9].tolist()}
for i, col in enumerate(df.columns)}
with open("batch_forecasts.json", "w") as f:
json.dump(results, f, indent=2)
评估预测准确度
H = 24
train, actual = values[:-H], values[-H:]
point, quantiles = model.forecast(horizon=H, inputs=[train])
pred = point[0]
mae = np.mean(np.abs(actual - pred))
rmse = np.sqrt(np.mean((actual - pred) ** 2))
mape = np.mean(np.abs((actual - pred) / actual)) * 100
coverage = np.mean((actual >= quantiles[0, :, 1]) & (actual <= quantiles[0, :, 9])) * 100
print(f"MAE: {mae:.2f} | RMSE: {rmse:.2f} | MAPE: {mape:.1f}% | 80% PI Coverage: {coverage:.1f}%")
⚙️ 性能调优
# Always set on Ampere+ GPUs (A100, RTX 3090+)
torch.set_float32_matmul_precision("high")
# Batch size guidelines:
# GPU 8 GB VRAM: per_core_batch_size=64
# GPU 16 GB VRAM: per_core_batch_size=128
# CPU 8 GB RAM: per_core_batch_size=8
# CPU 16 GB RAM: per_core_batch_size=32
# Memory-constrained: process in chunks
CHUNK = 50
results = []
for i in range(0, len(inputs), CHUNK):
p, q = model.forecast(horizon=H, inputs=inputs[i:i+CHUNK])
results.append((p, q))
📚 可用脚本
scripts/check_system.py
强制预检检查器 —— 在首次加载模型前运行。 现在包括数据集感知内存估算,以防止在加载数据前出现 OOM 错误。
# Basic system check
python scripts/check_system.py
# Check if your specific dataset will fit
python scripts/check_system.py \
--num-series 1000 \
--context-length 1024 \
--horizon 24 \
--batch-size 32
# Quick memory estimate without system checks
python scripts/check_system.py \
--num-series 5000 \
--context-length 2048 \
--estimate-only
它检查的内容:
- 可用 RAM —— 低于 4 GB 时警告,低于 2 GB 时阻止
- GPU 可用性 —— 检测 CUDA/MPS 设备和 VRAM
- 磁盘空间 —— 验证是否有足够空间下载约 800 MB 的模型
- Python 版本 —— 要求 3.10+
- 现有安装 —— 检查是否安装了
timesfm和torch - 数据集适配(新增)—— 为您的特定数据集估算内存,如果不适应则警告
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/system_requirements.md | 硬件层级、GPU/CPU 选择、内存估算 |
references/api_reference.md | 完整的 ForecastConfig 文档、输出形状、模型选项 |
references/data_preparation.md | 输入格式、NaN 处理、CSV 加载、协变量设置 |
🧪 示例
| 示例 | 目录 | 演示内容 |
|---|---|---|
| 全球温度预测 | examples/global-temperature/ | 基本 model.forecast()、CSV → PNG → GIF 流水线 |
| 异常检测 | examples/anomaly-detection/ | 两阶段去趋势 + Z-score + 分位数 PI、2 面板可视化 |
| 协变量(XReg) | examples/covariates-forecasting/ | forecast_with_covariates()、2×2 共享轴可视化 |
# Run all three examples:
cd examples/global-temperature && python run_forecast.py && python visualize_forecast.py
cd examples/anomaly-detection && python detect_anomalies.py
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) |
| covariates-forecasting | output/sales_with_covariates.csv、output/covariates_data.png | 108 行(3 家门店 × 36 周);各门店的 price 数组不同 |
模型版本
| 版本 | 参数量 | 上下文 | 状态 | HuggingFace checkpoint |
|---|---|---|---|---|
| 2.5 | 200M | 16,384 | 最新 | google/timesfm-2.5-200m-pytorch |
| 2.0 | 500M | 2,048 | 已归档 | google/timesfm-2.0-500m-pytorch |
| 1.0 | 200M | 2,048 | 已归档 | google/timesfm-1.0-200m-pytorch |
- TimesFM 1.0/2.0:对于月度数据必须传入
freq=[0] - TimesFM 2.5:无需频率标志 —— 该参数已被移除
资源
- 论文:A Decoder-Only Foundation Model for Time-Series Forecasting(ICML 2024)
- HuggingFace: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
质量检查清单
每次完成 TimesFM 任务后、宣布成功前运行:
- 输出形状 ——
point_fc为(n_series, horizon),quant_fc为(n_series, horizon, 10) - 分位数索引 —— 索引 0 = 均值,1 = q10 …… 9 = q90。不是 0 = q0。
- 频率标志 —— TimesFM 1.0/2.0:月度数据传入
freq=[0]。TimesFM 2.5:省略。 - 序列长度 —— 上下文必须 ≥ 32 个数据点。
- 无 NaN ——
np.isnan(point_fc).any()必须为 False。 - 坐标轴 —— 共享数据的多个面板必须使用
sharex=True。 -
matplotlib.use('Agg')—— 无头运行时需在任何 pyplot 导入之前调用。 -
infer_is_positive—— 对于温度、金融收益率、负值,设为 False。
常见错误
-
分位数索引差一 ——
quant_fc[..., 0]是均值,不是 q0。q10 = 索引 1,q90 = 索引 9。定义:IDX_Q10, IDX_Q90 = 1, 9。 -
协变量循环中的变量遮蔽 —— 构建逐序列协变量字典时,不要将外层循环变量用作推导式变量。
-
CSV 列名错误 —— global-temperature 的 CSV 使用
anomaly_c,而不是anomaly。先打印df.columns。 -
forecast_with_covariates()需要 TimesFM 2.5 —— TimesFM 1.0 没有此方法。 -
未来协变量必须覆盖整个预测期 —— 动态协变量需要同时为上下文窗口和预测窗口提供值。
-
上下文异常检测使用残差 —— 先去趋势,再计算 Z-score。原始 Z-score 在趋势数据上会产生误导。
验证与核实
# Anomaly detection regression:
python -c "
import json
d = json.load(open('examples/anomaly-detection/output/anomaly_detection.json'))
assert d['context_summary']['critical'] >= 1, 'Sep 2023 must be CRITICAL'
print('Anomaly detection: PASS')"
# Covariates regression:
python -c "
import pandas as pd
df = pd.read_csv('examples/covariates-forecasting/output/sales_with_covariates.csv')
assert len(df) == 108, f'Expected 108 rows, got {len(df)}'
print('Covariates: PASS')"