Communitygithub.com

timesfm-forecasting

Googleによるゼロショット時系列予測

timesfm-forecasting とは?

TimesFM Forecasting スキルは、Google Research が開発した事前学習済みデコーダーベースの基盤モデル「TimesFM」をエージェントが安全にローカル推論できるようにラップしたものです。このスキルは、任意の単変量時系列をゼロショットで予測し、調整された分位点予測区間を返すため、モデルの学習が不要です。主な特徴として、モデル読み込み前にRAM、GPUメモリ、ディスク容量を検証する必須のプリフライトシステムチェッカーが含まれており、エージェントがユーザーマシンをクラッシュさせることを防ぎます。推奨モデルはTimesFM 2.5(200Mパラメータ、約800MBのディスク容量、CPUで約1.5GBのRAMを消費)で、最大16,384ポイントのコンテキストをサポートします。このスキルは、セールス、需要、センサー、価格、天気などの単変量時系列の予測、バッチ予測、確率的な予測区間の取得に最適であり、classicalな統計モデルや時系列分類、多変量解析には適していません。エクソジェナス変数(XReg)のサポート、分位点区間を使った異常検知、statsmodelsやmatplotlibなどの他のスキルとの連携機能も提供します。

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

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

TimesFM Forecasting

概要

TimesFM(時系列基盤モデル)は、Google Research が開発した時系列予測のための事前学習済みデコーダーベース基盤モデルです。ゼロショットで動作します。つまり、任意の単変量時系列を入力として与えるだけで、調整された分位点予測区間を伴う点予測を返し、学習は一切不要です。

このスキルは、エージェントにとって安全で使いやすいローカル推論のために TimesFM をラップしたものです。モデルが読み込まれる前に、RAM、GPUメモリ、ディスク容量を検証する必須のプリフライトシステムチェッカーが含まれており、エージェントがユーザーのマシンをクラッシュさせることを防ぎます。

重要な数値: TimesFM 2.5 は 200M パラメータ(ディスク上で約 800 MB、CPU 上の RAM で約 1.5 GB、GPU 上の VRAM で約 1 GB)を使用します。アーカイブされた v1/v2 の 500M パラメータモデルには約 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(推奨)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 のインストール

# 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("インストール 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)),  # 任意の 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% 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/ を参照してください。

# 必要: 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 との連携

古典的なモデル(ARIMA、SARIMAX)の比較ベースラインとして statsmodels を使用:

# 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 との連携

予測の前に時系列の EDA を実行して、傾向、季節性、定常性を理解します。

📚 利用可能なスクリプト

scripts/check_system.py

必須のプリフライトチェッカー。 初回モデル読み込み前に実行します。

python scripts/check_system.py

出力例:

=== TimesFM システム要件チェック ===

[RAM]       合計: 32.0 GB | 利用可能: 24.3 GB  ✅ PASS
[GPU]       NVIDIA RTX 4090 | VRAM: 24.0 GB      ✅ PASS
[ディスク]  空き: 142.5 GB                        ✅ PASS
[Python]    3.12.1                                 ✅ PASS
[timesfm]   インストール済み (2.5.0)                ✅ PASS
[torch]     インストール済み (2.4.1+cu121)          ✅ PASS

判定: ✅ システムは 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 RAM 未満のマシンで v1/v2 を使用する → 代わりに TimesFM 2.5(200M パラメータ)を使用してください。
  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 を使用する → 予測がゼロでクランプされます。温度、リターンなどには False を設定してください。

モデルバージョン

timeline
    accTitle: TimesFM バージョン履歴
    accDescr: TimesFM モデルリリースのタイムライン。パラメータ数と主な改善点を示します。

    section 2024
        TimesFM 1.0 : 200M パラメータ, 2K コンテキスト, JAX のみ
        TimesFM 2.0 : 500M パラメータ, 2K コンテキスト, PyTorch + JAX
    section 2025
        TimesFM 2.5 : 200M パラメータ, 16K コンテキスト, 分位点ヘッド, 周波数インジケータなし
バージョンパラメータ数コンテキスト分位点ヘッド周波数フラグ状態
2.5200M16,384ありなし推奨
2.0500M2,048ありありアーカイブ
1.0200M2,048なしあり非推奨

完全なリファレンス: references/model_versions.md を参照して、バージョン間の移行、チェックポイントのダウンロード URL、および非推奨の詳細を確認してください。

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.

関連スキル