Communitygithub.com

timesfm-forecasting

使用 Google 的零样本时间序列预测技能。

timesfm-forecasting 是什么?

TimesFM(时间序列基础模型)是由 Google Research 开发的一种预训练解码器-only 基础模型,专为时间序列预测而设计。它采用零样本方式工作——无需训练即可直接对任何单变量时间序列进行点预测,并提供校准的分位数预测区间(如 10%-90% 分位数)。该技能将 TimesFM 封装为安全、对 AI 代理友好的本地推理工具,并包含一个强制性的预检系统检查器,可在加载模型前验证系统的 RAM、GPU 内存和磁盘空间,从而避免代理耗尽用户机器资源。TimesFM 2.5 版本拥有 2 亿参数(约 800 MB 磁盘存储,CPU 模式下约 1.5 GB 内存,GPU 模式下约 1 GB VRAM),支持长达 16,384 个上下文点,并兼容 PyTorch 和 JAX 后端。该技能支持批量预测、协变量(外生变量)和异常检测功能,可应用于销售、需求、传感器、生命体征、价格和天气等多种场景。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/K-Dense-AI/scientific-agent-skills/tree/main/skills/timesfm-forecasting

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

TimesFM 预测

概述

TimesFM(时间序列基础模型)是 Google Research 开发的一种预训练解码器-only 基础模型,专用于时间序列预测。它以零样本方式工作——输入任意单变量时间序列,即可返回点预测和校准的分位数预测区间,无需任何训练。

该技能封装了 TimesFM,以提供安全、对代理友好的本地推理。它包含一个强制性的预检系统检查器,可在加载模型前验证 RAM、GPU 内存和磁盘空间,确保代理不会导致用户机器崩溃。

关键数字: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 参数

不要在以下情况下使用该技能:

  • 需要经典统计模型和系数解释 → 使用 statsmodels
  • 需要时间序列分类或聚类 → 使用 aeon
  • 需要多变量向量自回归或格兰杰因果关系 → 使用 statsmodels
  • 数据是表格型(非时间序列) → 使用 scikit-learn

关于异常检测的说明:TimesFM 没有内置的异常检测功能,但您可以使用分位数预测作为预测区间——落在 90% 置信区间(q10–q90)之外的值在统计上属于异常。完整示例请参见 examples/anomaly-detection/ 目录。

⚠️ 强制预检:系统要求检查

关键——在首次加载模型前务必运行系统检查器。

python scripts/check_system.py

此脚本检查:

  1. 可用 RAM — 低于 4 GB 时发出警告,低于 2 GB 时阻止
  2. GPU 可用性 — 检测 CUDA/MPS 设备和 VRAM
  3. 磁盘空间 — 验证是否有空间容纳约 800 MB 的模型下载
  4. Python 版本 — 需要 3.10 或更高版本
  5. 现有安装 — 检查是否已安装 timesfm 和 torch

注意: 模型权重不存储在此仓库中。TimesFM 权重(约 800 MB)会在首次使用时按需从 HuggingFace 下载,并缓存到 ~/.cache/huggingface/。预检检查器确保在开始任何下载之前具备足够的资源。

flowchart TD
    accTitle: 预检系统检查
    accDescr: 显示在加载 TimesFM 前必须通过的系统要求检查的决策流程图。

    start["🚀 运行 check_system.py"] --> ram{"RAM ≥ 4 GB?"}
    ram -->|"是"| gpu{"有 GPU?"}
    ram -->|"否 (2-4 GB)"| warn_ram["⚠️ 警告:内存紧张<br/>仅 CPU 模式,小批量"]
    ram -->|"否 (< 2 GB)"| block["🛑 阻止<br/>内存不足"]
    warn_ram --> disk
    gpu -->|"CUDA / MPS"| vram{"VRAM ≥ 2 GB?"}
    gpu -->|"仅 CPU"| cpu_ok["✅ CPU 模式<br/>速度较慢但可用"]
    vram -->|"是"| gpu_ok["✅ GPU 模式<br/>推理速度快"]
    vram -->|"否"| cpu_ok
    gpu_ok --> disk{"磁盘 ≥ 2 GB 空闲?"}
    cpu_ok --> disk
    disk -->|"是"| ready["✅ 就绪<br/>安全加载模型"]
    disk -->|"否"| block_disk["🛑 阻止<br/>需要空间存储权重"]

    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 2.5(推荐)2 亿≥ 4 GB≥ 2 GB约 800 MB最多 16,384
TimesFM 2.0(已归档)5 亿≥ 16 GB≥ 8 GB约 2 GB最多 2,048
TimesFM 1.0(已归档)2 亿≥ 8 GB≥ 4 GB约 800 MB最多 2,048

建议:除非有特定原因需要使用旧检查点,否则始终使用 TimesFM 2.5。它更小、更快,并且支持 8 倍以上的上下文长度。

🔧 安装

第 1 步:验证系统(始终第一步)

python scripts/check_system.py

第 2 步:安装 TimesFM

# 使用 uv(本仓库推荐)
uv pip install timesfm[torch]

# 使用 JAX/Flax 后端(在 TPU/GPU 上更快)
uv pip install timesfm[flax]

第 3 步:为您的硬件安装 PyTorch

# CUDA 12.1(NVIDIA GPU)
uv pip install torch>=2.0.0 --index-url https://download.pytorch.org/whl/cu121

# 仅 CPU
uv pip install torch>=2.0.0 --index-url https://download.pytorch.org/whl/cpu

# Apple Silicon(MPS)
uv pip install torch>=2.0.0  # MPS 支持已内置

第 4 步:验证安装

import timesfm
import numpy as np
print(f"TimesFM 版本: {timesfm.__version__}")
print("安装成功")

🎯 快速开始

最小示例(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)),  # 任意 1-D 数组
])
# point.shape == (1, 24)        — 中位数预测
# quantiles.shape == (1, 24, 10) — 10th–90th 百分位区间

从 CSV 进行预测

import pandas as pd, numpy as np

df = pd.read_csv("monthly_sales.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=12, inputs=inputs)

# 构建结果 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, :, 2],  # 20th 百分位
        "upper_80": quantiles[i, :, 8],  # 80th 百分位
    })
    print(f"\n--- {col} ---")
    print(forecast_df.to_string(index=False))

使用协变量进行预测(XReg)

TimesFM 2.5+ 通过 forecast_with_covariates() 支持外生变量。需要 timesfm[xreg]。

# 需要:uv 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",  # 或 "timesfm + xreg"
)
协变量类型描述示例
dynamic_numerical随时间变化的数值price, temperature, promotion spend
dynamic_categorical随时间变化的分类holiday flag, day of week
static_numerical每个序列的静态数值store size, account age
static_categorical每个序列的静态分类store type, region, product category

XReg 模式:

  • "xreg + timesfm"(默认):先进行 TimesFM 预测,然后 XReg 调整残差
  • "timesfm + xreg":先进行 XReg 拟合,然后 TimesFM 预测残差

完整示例请参见 examples/covariates-forecasting/,其中包含合成零售数据。

异常检测(通过分位数区间)

TimesFM 没有内置的异常检测功能,但分位数预测自然地提供了预测区间,可用于检测异常:

point, q = model.forecast(horizon=H, inputs=[values])

# 90% 预测区间
lower_90 = q[0, :, 1]  # 10th 百分位
upper_90 = q[0, :, 9]  # 90th 百分位

# 检测异常:落在 90% CI 之外的值
actual = test_values  # 您的留存数据
anomalies = (actual < lower_90) | (actual > upper_90)

# 严重程度级别
is_warning = (actual < q[0, :, 2]) | (actual > q[0, :, 8])  # 落在 80% CI 之外
is_critical = anomalies  # 落在 90% CI 之外
严重程度条件解释
正常在 80% CI 内预期行为
警告在 80% CI 外不寻常但可能
严重在 90% CI 外统计上罕见(< 10% 概率)

完整示例及可视化请参见 examples/anomaly-detection/。

输出、配置、工作流与调优

🔗 与其他技能的集成

与 statsmodels 结合

使用 statsmodels 的经典模型(ARIMA、SARIMAX)作为比较基线:

# TimesFM 预测
tfm_point, tfm_q = model.forecast(horizon=H, inputs=[values])

# statsmodels ARIMA 预测
from statsmodels.tsa.arima.model import ARIMA
arima = ARIMA(values, order=(1,1,1)).fit()
arima_forecast = arima.forecast(steps=H)

# 比较
print(f"TimesFM MAE: {np.mean(np.abs(actual - tfm_point[0])):.2f}")
print(f"ARIMA MAE:   {np.mean(np.abs(actual - arima_forecast)):.2f}")

与 matplotlib / scientific-visualization 结合

绘制带有预测区间的预测图,作为出版级别的图表。

与 exploratory-data-analysis 结合

在预测前对时间序列进行探索性数据分析,以了解趋势、季节性和平稳性。

📚 可用脚本

scripts/check_system.py

强制预检查器。 在首次加载模型前运行。

python scripts/check_system.py

输出示例:

=== TimesFM 系统要求检查 ===

[RAM]       总共:32.0 GB | 可用:24.3 GB  ✅ 通过
[GPU]       NVIDIA RTX 4090 | VRAM:24.0 GB      ✅ 通过
[磁盘]      空闲:142.5 GB                        ✅ 通过
[Python]    3.12.1                                 ✅ 通过
[timesfm]   已安装 (2.5.0)                         ✅ 通过
[torch]     已安装 (2.4.1+cu121)                  ✅ 通过

结论:✅ 系统已准备好运行 TimesFM 2.5(GPU 模式)
推荐:per_core_batch_size=128

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/system_requirements.md硬件层级、GPU/CPU 选择、内存估算公式
references/api_reference.md完整的 ForecastConfig 文档、from_pretrained 选项、输出形状
references/data_preparation.md输入格式、NaN 处理、CSV 加载、协变量设置

常见陷阱

  1. 未运行系统检查 → 在低 RAM 机器上模型加载会崩溃。请始终先运行 check_system.py。
  2. 忘记调用 model.compile() → RuntimeError: Model is not compiled。必须在 forecast() 之前调用 compile()。
  3. 未设置 normalize_inputs=True → 对较大值的序列预测不稳定。
  4. 在内存小于 32 GB 的机器上使用 v1/v2 → 改用 TimesFM 2.5(2 亿参数)。
  5. 未设置 fix_quantile_crossing=True → 分位数可能不是单调的(q10 > q50)。
  6. 在小 GPU 上使用过大的 per_core_batch_size → CUDA 内存不足。从小开始,逐步增加。
  7. 传递 2-D 数组 → TimesFM 期望一个1-D 数组列表,而不是 2-D 矩阵。
  8. 忘记设置 torch.set_float32_matmul_precision("high") → 在 Ampere+ GPU 上推理速度较慢。
  9. 输出中未处理 NaN → 非常短序列的边界情况。请始终检查 np.isnan(point).any()。
  10. 对可能为负的序列使用 infer_is_positive=True → 会将预测值限制为零。对于温度、收益率等,请设置为 False。

模型版本

timeline
    accTitle: TimesFM 版本历史
    accDescr: TimesFM 模型发布的时序图,显示参数量和关键改进。

    section 2024 年
        TimesFM 1.0 : 2 亿参数, 2K 上下文, 仅 JAX
        TimesFM 2.0 : 5 亿参数, 2K 上下文, PyTorch + JAX
    section 2025 年
        TimesFM 2.5 : 2 亿参数, 16K 上下文, 分位头, 无频率指示器
版本参数上下文分位头频率标志状态
2.52 亿16,384是否推荐
2.05 亿2,048否是已归档
1.02 亿2,048否是已归档

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

adaptyv

How to use the Adaptyv Bio Foundry API and Python SDK for protein experiment design, submission, and results retrieval. Use this skill whenever the user mentions Adaptyv, Foundry API, protein binding assays, protein screening experiments, BLI/SPR assays, thermostability assays, or wants to submit protein sequences for experimental characterization. Also trigger when code imports `adaptyv`, `adaptyv_sdk`, or `FoundryClient`, or references `foundry-api-public.adaptyvbio.com`.

aeon

This skill should be used for time series machine learning tasks including classification, regression, clustering, forecasting, anomaly detection, segmentation, and similarity search. Use when working with temporal data, sequential patterns, or time-indexed observations requiring specialized algorithms beyond standard ML approaches. Particularly suited for univariate and multivariate time series analysis with scikit-learn compatible APIs.

alphagenome

Look up precomputed AlphaGenome Atlas effects for any GRCh38 single-nucleotide variant (AVI score with Phred and 18 SHAP feature attributions, plus raw and quantile scores for RNA-seq, DNase, ATAC, ChIP-TF, ChIP-histone, CAGE, PRO-cap, splicing, polyadenylation and contact-map tracks), score variants or scan windows on demand with the AlphaGenome model for human and mouse (variant scoring, in silico mutagenesis, REF-versus-ALT track prediction), and build Atlas website deep links. Use when the user mentions AlphaGenome, AlphaGenome Atlas, AVI or AlphaGenome Variant Impact, DeepMind variant effect prediction, or wants to prioritise or mechanistically interpret non-coding, regulatory, splicing, enhancer, promoter, or chromatin-accessibility effects of SNVs from a VCF, credible set, or region. Research use only; not a clinical tool.

analytical-method-validation

Plan, execute, and document validation, verification, and transfer of analytical procedures under the governing framework - ICH Q2(R2) and Q14, USP <1220>/<1225>/<1226>, ICH M10 bioanalytical, CLSI EP, or ISO/IEC 17025. Use for HPLC, LC-MS/MS, GC, CE, ICP-MS, dissolution, qNMR, qPCR, NIR, and ligand binding or cell-based assays whenever the question is whether a procedure is fit for its intended purpose. Triggers include

anndata

Data structure for annotated matrices in single-cell analysis. Use when working with .h5ad files or integrating with the scverse ecosystem. This is the data format skill—for analysis workflows use scanpy; for probabilistic models use scvi-tools; for population-scale queries use cellxgene-census.

arbor

Autonomously improve a real artifact (code, training recipe, agent harness, data pipeline, prompt) against an objective and an evaluator, using Hypothesis Tree Refinement (HTR) from the Arbor paper. Use this whenever someone wants to iteratively optimize something over many experiments without overfitting — e.g.

arboreto

Infer gene regulatory networks (GRNs) from gene expression data using scalable algorithms (GRNBoost2, GENIE3). Use when analyzing transcriptomics data (bulk RNA-seq, single-cell RNA-seq) to identify transcription factor-target gene relationships and regulatory interactions. Supports distributed computation for large-scale datasets.

astropy

Core Python library for astronomy and astrophysics workflows that need Astropy APIs, including units/quantities, coordinates, FITS I/O, tables, time systems, WCS, and cosmology. Use when implementing or debugging astronomical data analysis code with Astropy.

autoskill

Observe the user

benchling-integration

Benchling Python SDK and REST API integration for registry entities, inventory, ELN entries, workflows, Benchling Apps, and Data Warehouse queries. Use when automating lab data with benchling-sdk or the v2 API.

bgpt-paper-search

Search scientific papers and retrieve structured experimental data extracted from full-text studies via the BGPT MCP server. Returns 25+ fields per paper including methods, results, sample sizes, quality scores, and conclusions. Use for literature reviews, evidence synthesis, and finding experimental details not available in abstracts alone.

bids

>

biopython

Comprehensive molecular biology toolkit. Use for sequence manipulation, file parsing (FASTA/GenBank/PDB), phylogenetics, and programmatic NCBI/PubMed access (Bio.Entrez). Best for batch processing, custom bioinformatics pipelines, BLAST automation. For quick lookups use gget; for multi-service integration use bioservices.

bioservices

Unified Python interface to 40+ bioinformatics services. Use when querying multiple databases (UniProt, KEGG, ChEMBL, Reactome) in a single workflow with consistent API. Best for cross-database analysis, ID mapping across services. For quick single-database lookups use gget; for sequence/file manipulation use biopython.

bulk-rnaseq

End-to-end bulk RNA-seq orchestrator — takes raw FASTQ reads through QC and trimming (FastQC, fastp/Trim Galore), alignment and quantification (STAR, Salmon, featureCounts), assembles a gene-level counts matrix, then hands off to differential expression (pydeseq2), pathway/GSEA enrichment (pathway-enrichment), and publication figures (scientific-visualization). Use whenever the user has bulk RNA-seq reads or quant output and wants a complete, reproducible differential-expression workflow — e.g.

cellxgene-census

Query the CZ CELLxGENE Census programmatically for versioned public single-cell and spatial transcriptomics data. Use when you need population-scale cell metadata, gene expression slices, Census summary counts, source H5AD URIs/downloads, embeddings, spatial Census data, or reference atlas comparisons across organisms, tissues, diseases, assays, and cell types. For analyzing your own local single-cell data use scanpy, anndata, or scvi-tools.

cirq

Google quantum computing framework. Use when targeting Google Quantum AI hardware, designing noise-aware circuits, or running quantum characterization experiments. Best for Google hardware, noise modeling, and low-level circuit design. For IBM hardware use qiskit; for quantum ML with autodiff use pennylane; for physics simulations use qutip.

citation-management

Comprehensive citation management for academic research. Search OpenAlex, PubMed, and Google Scholar for papers, extract accurate metadata, validate citations, and generate properly formatted BibTeX entries. This skill should be used when you need to find papers, verify citation information, convert DOIs to BibTeX, or ensure reference accuracy in scientific writing.

clinical-decision-support

Prepare and validate research-only clinical decision-support evaluation, evidence-profile, cohort, survival, biomarker/model, privacy, and governance artifacts. Use for aggregate or synthetic research documentation and traceability—not patient care or live clinical operation.

clinical-reports

Create safety-bounded draft structures and run local deterministic checks for clinical case, diagnostic, trial, safety, and aggregate research reports. Use only with synthetic, de-identified, or aggregate inputs and verified source-fact manifests; every output requires qualified review.

相关技能