Communitygithub.com

timesfm-forecasting

使用 Google TimesFM 進行零樣本時間序列預測

timesfm-forecasting 是什麼?

此技能封裝了 Google Research 的 TimesFM(時間序列基礎模型),一個僅解碼器的預訓練基礎模型,專為零樣本時間序列預測而設計。開發者可以輸入任何單變量時間序列,立即獲得點預測和校準的分位數預測區間,無需進行模型訓練。此技能支援 TimesFM 2.5(2 億參數),可在 CPU 和 GPU(CUDA/MPS)上運作,並包含一個強制性的前置系統檢查,用於驗證 RAM、VRAM 和磁碟空間,以防止使用者的機器崩潰。此技能還支援批次預測、協變數(外在變數),並透過分位數預測區間提供異常檢測功能。它旨在成為一個對 AI 代理安全且友善的介面,透過 `scripts/check_system.py` 強制執行系統需求檢查,並在安裝和執行模型之前提供清晰的指引。

相容平台~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 開發的一個預訓練的僅解碼器基礎模型,專為時間序列預測而設計。它可以做到零樣本 — 輸入任何單變量時間序列,它就會返回點預測以及校準過的分位數預測區間,完全不需要訓練。

此技能封裝了 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["⚠️ 警告: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 維陣列
])
# point.shape == (1, 24)        — 中位數預測
# quantiles.shape == (1, 24, 10) — 第 10 到第 90 個百分位區間

從 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],  # 第 20 個百分位
        "upper_80": quantiles[i, :, 8],  # 第 80 個百分位
    })
    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隨時間變化的數值價格、溫度、促銷支出
dynamic_categorical隨時間變化的類別假期標誌、星期幾
static_numerical每個序列的固定數值商店規模、帳戶年齡
static_categorical每個序列的固定類別商店類型、地區、產品類別

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]  # 第 10 個百分位
upper_90 = q[0, :, 9]  # 第 90 個百分位

# 檢測異常:落在 90% 信賴區間之外的值
actual = test_values  # 您的保留資料
anomalies = (actual < lower_90) | (actual > upper_90)

# 嚴重程度等級
is_warning = (actual < q[0, :, 2]) | (actual > q[0, :, 8])  # 落在 80% 信賴區間之外
is_critical = anomalies  # 落在 90% 信賴區間之外
嚴重程度條件解釋
正常落在 80% 信賴區間內預期行為
警告落在 80% 信賴區間外不常見但可能發生
嚴重落在 90% 信賴區間外統計上罕見 (< 10% 機率)

請參閱 examples/anomaly-detection/ 取得包含視覺化的完整範例。

# 需要安裝:uv pip install timesfm[xreg]
point, quantiles = model.forecast_with_covariates(
    inputs=inputs,
    dynamic_numerical_covariates={"temperature": temp_arrays},
    dynamic_categorical_covariates={"day_of_week": dow_arrays},
    static_categorical_covariates={"region": region_labels},
    xreg_mode="xreg + timesfm",  # 或 "timesfm + xreg"
)

輸出、配置、工作流程與調校

🔗 與其他技能的整合

與 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. 在 RAM 小於 32 GB 的機器上使用 v1/v2 → 請改用 TimesFM 2.5(2 億參數)。
  5. 未設定 fix_quantile_crossing=True → 分位數可能不是單調遞增的(q10 > q50)。
  6. 在小 GPU 上設定過大的 per_core_batch_size → 造成 CUDA 記憶體不足。請從小數值開始,再逐漸增加。
  7. 傳入 2 維陣列 → TimesFM 期望一個1 維陣列的列表,而不是一個 2 維矩陣。
  8. 忘記設定 torch.set_float32_matmul_precision("high") → 在 Ampere 及以上架構的 GPU 上推理速度變慢。
  9. 未處理輸出中的 NaN → 在序列非常短的邊緣情況下可能發生。請務必檢查 np.isnan(point).any()。
  10. 對可能為負值的序列使用 infer_is_positive=True → 會將預測值限制在 0 以上。對於溫度、回報率等序列,請設為 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.

相關技能