hypogenic-hypothesis-generation について
HypoGeniCは、ラベル付き表形式データからLLMで仮説を生成・検証する研究者向けPythonスキルです。データ駆動型、文献統合型、両者の併用に対応し、仮説を使って新しいサンプルを推論できます。
主な機能
- 01ラベル付きデータから仮説を生成
- 02検証結果に基づく仮説の反復改良
- 03研究論文の知見を統合
- 04仮説による新規サンプルの分類
- 05複数仮説を組み合わせた推論
活用シーン
- 01ラベル付き観察データのパターン探索
- 02検証データによる複数の説明の比較
- 03文献を用いたデータ駆動型仮説の拡張
- 04生成した仮説群によるサンプル分類
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ jaechang-hits/ sciagent-skills --skill hypogenic-hypothesis-generationインストール後、Claude Code で/hypogenic-hypothesis-generationを入力して読み込まれたか確認します。
詳細
HypoGeniC による仮説生成
概要
HypoGeniC は、LLM を使用して、表形式データセットにおける科学的仮説の生成と検証を自動化します。ラベル付きデータ(例:欺瞞検出、AI 生成コンテンツの識別)を入力すると、検証可能な仮説を生成し、検証時の性能を基に反復的に改善したうえで、新しいサンプルを分類する推論を実行します。データのみを用いる手法(HypoGeniC)、文献を取り入れる手法(HypoRefine)、両者を機構的に統合する手法の3つをサポートしています。
使用する場面
- 既存の理論を使わずに、ラベル付き観察データセットから検証可能な仮説を生成する場合
- 実証データで複数の競合する仮説を体系的に検証する場合
- 研究論文から得た知見と、データ駆動型のパターン発見を組み合わせる場合
- 欺瞞検出、コンテンツ分析、メンタルヘルス指標などの分野で、仮説の着想を加速する場合
- LLM ベースの仮説生成手法を、少数ショットのベースラインと比較評価する場合
- 手動による仮説定式化のフレームワークには、hypothesis-generation knowhow を使用してください
- 仮説の解釈可能性を必要としない汎用的な ML 分類には、scikit-learn-machine-learning を使用してください
前提条件
- Python パッケージ:
hypogenic - 任意:LLM 応答のキャッシュには Redis サーバー(ポート 6832)、PDF 文献の処理には GROBID
- API キー:環境変数に設定された OpenAI、Anthropic、または互換性のある LLM API キー
- データ:HypoGeniC 形式のラベル付き JSON データセット(「主要な概念」を参照)
pip install hypogenic
# Optional: clone example datasets
git clone https://github.com/ChicagoHAI/HypoGeniC-datasets.git ./data
git clone https://github.com/ChicagoHAI/Hypothesis-agent-datasets.git ./data_lit
クイックスタート
from hypogenic import BaseTask
import re
# Custom label extractor (must match dataset label format)
def extract_label(text: str) -> str:
match = re.search(r'final answer:\s+(.*)', text, re.IGNORECASE)
return match.group(1).strip() if match else text.strip()
# 1. Load task from config
task = BaseTask(
config_path="./data/your_task/config.yaml",
extract_label=extract_label
)
# 2. Generate hypotheses (data-driven)
task.generate_hypotheses(
method="hypogenic",
num_hypotheses=20,
output_path="./output/hypotheses.json"
)
# 3. Run inference on test set
results = task.inference(
hypothesis_bank="./output/hypotheses.json",
test_data="./data/your_task/your_task_test.json"
)
print(f"Accuracy: {results['accuracy']:.3f}")
ワークフロー
ステップ 1:データセットを準備する
テキスト特徴量とラベルを含む train/val/test の JSON ファイルを作成します。
import json
# Dataset: each key maps to a list of equal length
dataset = {
"headline_1": [
"What Up, Comet? You Just Got *PROBED*",
"Scientists Made a Breakthrough in Quantum Computing"
],
"headline_2": [
"Scientists Were Holding Their Breath Today. Here's Why.",
"New Quantum Computer Achieves Milestone"
],
"label": [
"Headline 2 has more clicks than Headline 1",
"Headline 1 has more clicks than Headline 2"
]
}
# All lists must have equal length; labels must match extract_label output
for split in ["train", "val", "test"]:
with open(f"my_task_{split}.json", "w") as f:
json.dump(dataset, f, indent=2)
print(f"Created dataset with {len(dataset['label'])} samples")
ステップ 2:タスク設定を作成する
データセットのパスとプロンプトテンプレートを定義する config.yaml を作成します。
# config.yaml structure (write as YAML file)
config = """
task_name: my_task
train_data_path: ./my_task_train.json
val_data_path: ./my_task_val.json
test_data_path: ./my_task_test.json
prompt_templates:
observations: |
Feature 1: ${text_features_1}
Feature 2: ${text_features_2}
Observation: ${label}
batched_generation:
system: "You are a research scientist generating hypotheses."
user: "Generate ${num_hypotheses} testable hypotheses from these observations."
inference:
system: "You are evaluating a hypothesis against data."
user: "Hypothesis: ${hypothesis}\\nSample: ${sample_text}\\nFinal answer: ${label}"
is_relevant:
system: "Check hypothesis relevance."
user: "Is this hypothesis relevant? ${hypothesis}"
"""
with open("config.yaml", "w") as f:
f.write(config)
print("Configuration written to config.yaml")
ステップ 3:ラベル抽出を実装する
ラベル形式に合ったカスタムの extract_label 関数を定義します。
import re
def extract_label(llm_output: str) -> str:
"""Parse LLM output to extract predicted label.
Must return labels matching the 'label' field values in the dataset.
Default: searches for 'final answer: <label>' pattern.
"""
match = re.search(r'final answer:\s+(.*)', llm_output, re.IGNORECASE)
if match:
return match.group(1).strip()
# Domain-specific fallback
if "Final prediction:" in llm_output:
return llm_output.split("Final prediction:")[-1].strip()
return llm_output.strip()
# Test against expected labels
assert extract_label("Final answer: Headline 1") == "Headline 1"
print("Label extractor validated")
ステップ 4:仮説を生成する(HypoGeniC)
反復的な改善を行いながら、データ駆動型の仮説生成を実行します。
from hypogenic import BaseTask
task = BaseTask(
config_path="./config.yaml",
extract_label=extract_label
)
# Generate hypotheses: initializes from data subset, iteratively refines
task.generate_hypotheses(
method="hypogenic", # Data-driven generation
num_hypotheses=20, # Target number of hypotheses
output_path="./output/hypotheses.json"
)
# CLI equivalent:
# hypogenic_generation --config config.yaml --method hypogenic --num_hypotheses 20
print("Hypothesis bank saved to ./output/hypotheses.json")
ステップ 5:推論を実行する
生成した仮説をテストセットで検証します。
results = task.inference(
hypothesis_bank="./output/hypotheses.json",
test_data="./my_task_test.json"
)
print(f"Test accuracy: {results['accuracy']:.3f}")
print(f"Predictions: {results['predictions'][:5]}")
# CLI equivalent:
# hypogenic_inference --config config.yaml --hypotheses output/hypotheses.json
ステップ 6:文献を取り入れた生成(HypoRefine)
文献から得た知見をデータ駆動型の仮説と組み合わせます。
# Requires GROBID setup and preprocessed PDFs
# bash ./modules/setup_grobid.sh # first time
# bash ./modules/run_grobid.sh # start GROBID service
# python pdf_preprocess.py --task_name my_task
task.generate_hypotheses(
method="hyporefine",
num_hypotheses=15,
literature_path="./literature/my_task/",
output_path="./output/"
)
# Generates 3 hypothesis banks:
# - HypoRefine (integrated literature+data)
# - Literature-only hypotheses
# - Literature union HypoRefine
print("HypoRefine generation complete: 3 hypothesis banks created")
ステップ 7:複数仮説による推論
複数の仮説を同時に検証し、アンサンブル分類を行います。
from examples.multi_hyp_inference import run_multi_hypothesis_inference
results = run_multi_hypothesis_inference(
config_path="./config.yaml",
hypothesis_bank="./output/hypotheses.json",
test_data="./my_task_test.json"
)
print(f"Multi-hypothesis accuracy: {results['accuracy']:.3f}")
主要なパラメーター
| パラメーター | デフォルト | 範囲/選択肢 | 効果 |
|---|---|---|---|
method | "hypogenic" | "hypogenic", "hyporefine", "union" | 生成戦略 |
num_hypotheses | 20 | 5-50 | 生成する仮説の数 |
batch_size | 5 | 3-10 | 生成バッチあたりのサンプル数 |
max_iterations | 10 | 1-50 | 改善の反復回数 |
temperature | 0.7 | 0.0-1.0 | LLM のサンプリング温度 |
confidence_threshold | 0.7 | 0.5-0.95 | 推論時の信頼度しきい値 |
num_papers | 10 | 5-30 | HypoRefine の文献抽出に使用する論文数 |
inference_method | "voting" | "voting", "weighted", "ensemble" | 複数の仮説による予測の統合方法 |
主要な概念
データセット形式
HypoGeniC では、並列リストを含む JSON ファイルが必要です。
{
"text_features_1": ["sample_1_feat1", "sample_2_feat1"],
"text_features_2": ["sample_1_feat2", "sample_2_feat2"],
"label": ["class_A", "class_B"]
}
- すべてのリストの長さは同じである必要があります
- 特徴量のキーはカスタマイズできます(
review_text、post_contentなど) - ラベルは
extract_label()の出力形式と完全に一致する必要があります - 3つの分割が必要です:
<TASK>_train.json、<TASK>_val.json、<TASK>_test.json
3つの生成手法
| 手法 | 入力 | プロセス | 最適な用途 |
|---|---|---|---|
| HypoGeniC | データのみ | サブセットから初期化し、検証データを用いて反復的に改善 | 探索的研究、文献のない新しいデータセット |
| HypoRefine | データ + PDF | 文献の知見を抽出し、データのパターンと統合して両方を改善 | 既存の理論の拡張または検証 |
| Union | 文献 + HypoGeniC | 機構的に組み合わせ、重複を除去 | 仮説の多様性と網羅性を最大化 |
設定テンプレート
最小限必要な config.yaml の構造:
task_name: my_task
train_data_path: ./my_task_train.json
val_data_path: ./my_task_val.json
test_data_path: ./my_task_test.json
model:
name: "gpt-4" # or claude-3, gpt-3.5-turbo
api_key_env: "OPENAI_API_KEY"
temperature: 0.7
generation:
method: "hypogenic"
num_hypotheses: 20
batch_size: 5
max_iterations: 10
cache:
enabled: true # Redis on localhost:6832
host: "localhost"
port: 6832
prompt_templates:
observations: |
Feature 1: ${text_features_1}
Observation: ${label}
batched_generation:
system: "Generate testable hypotheses."
user: "Generate ${num_hypotheses} hypotheses."
inference:
system: "Evaluate hypothesis against sample."
user: "Hypothesis: ${hypothesis}\nSample: ${sample_text}"
is_relevant:
system: "Check relevance."
user: "Is ${hypothesis} relevant?"
よくあるレシピ
レシピ:ゼロからカスタムタスクを作成する
使用するタイミング:ドメイン固有のデータを使って、新しい分類タスクを作成する場合。
import json
from hypogenic import BaseTask
# 1. Prepare data splits
for split_name, data in [("train", train_data), ("val", val_data), ("test", test_data)]:
with open(f"my_task_{split_name}.json", "w") as f:
json.dump(data, f)
# 2. Define domain-specific label extractor
def my_extractor(text):
if "positive" in text.lower():
return "positive"
elif "negative" in text.lower():
return "negative"
return text.strip()
# 3. Create task and run full pipeline
task = BaseTask(config_path="./my_task/config.yaml", extract_label=my_extractor)
task.generate_hypotheses(method="hypogenic", num_hypotheses=15, output_path="./output/")
results = task.inference(hypothesis_bank="./output/hypotheses.json")
print(f"Custom task accuracy: {results['accuracy']:.3f}")
レシピ:文献処理のセットアップ
使用するタイミング:HypoRefine の前に、PDF を構造化テキストへ変換するために GROBID をセットアップする場合。
# 1. Setup GROBID (first time only)
bash ./modules/setup_grobid.sh
# 2. Place PDFs in literature directory
mkdir -p literature/my_task/raw/
cp papers/*.pdf literature/my_task/raw/
# 3. Start GROBID and process
bash ./modules/run_grobid.sh
cd examples && python pdf_preprocess.py --task_name my_task
# Output: structured text files in literature/my_task/processed/
レシピ:最大限の網羅性を実現するユニオン手法
使用するタイミング:文献由来の仮説とデータ駆動型の仮説を組み合わせ、包括的に網羅する場合。
# Generate literature hypotheses first (via HypoRefine)
task.generate_hypotheses(
method="hyporefine",
num_hypotheses=15,
literature_path="./literature/my_task/",
output_path="./output/"
)
# Union combines and deduplicates both banks
# CLI alternative:
# hypogenic_generation --config config.yaml --method union \
# --literature_hypotheses output/lit_hypotheses.json
# Compare all three approaches
for bank in ["hypogenic", "hyporefine", "union"]:
r = task.inference(hypothesis_bank=f"./output/{bank}_hypotheses.json")
print(f"{bank}: accuracy={r['accuracy']:.3f}")
期待される出力
hypotheses.json-- 順位付けされた、検証可能な仮説のバンク(通常10~20件)- サンプルごとの予測と全体の精度を含む推論結果
- HypoRefine の場合:3種類の仮説バンク(文献のみ、統合、ユニオン)
- 報告された改善:少数ショットのベースラインを約9%上回り、文献のみのアプローチを約16%上回る
- 仮説ペアの多様性80~84%(重複しない知見)
トラブルシューティング
| 問題 | 原因 | 解決策 |
|---|---|---|
ModuleNotFoundError: hypogenic | パッケージがインストールされていません | pip install hypogenic |
| 汎用的、または検証できない仮説 | プロンプトテンプレートが曖昧すぎます | batched_generation プロンプトにドメイン固有のコンテキストを追加します |
| 推論精度が低い | 学習例が少ない、またはラベルの抽出に問題があります | 学習データを増やします。extract_label がデータセットのラベルと一致していることを確認します |
| GROBID による PDF 処理が失敗する | GROBID サービスが起動していません | bash ./modules/run_grobid.sh を実行し、PDF が有効な論文であることを確認します |
| ラベル抽出の不一致 | extract_label の出力がデータセットのラベルと異なります | 両方の形式を出力して一致させます。assert extract_label(sample) == expected でテストします |
| Redis 接続エラー | Redis が起動していないか、ポートが間違っています | Redis をポート6832で起動するか、cache.enabled: false を設定します |
| API のレート制限エラー | LLM 呼び出しの同時実行が多すぎます | batch_size を減らし、Redis キャッシュを有効にして重複した呼び出しを避けます |
| 仮説バンクが空 | 必須のプロンプトテンプレートが設定にありません | 次の4つのテンプレートをすべて含めます:observations、batched_generation、inference、is_relevant |
同梱リソース
このエントリーだけで完結しています。元の references/config_template.yaml(151行)は、必須の YAML 構造、モデル/キャッシュ/生成パラメーター、プロンプトテンプレートのパターンを残して、「主要概念」の「設定テンプレート」サブセクションに統合されています。テンプレートから省略した項目:評価指標ブロック、ログ設定、タスク固有の特徴量/ラベルのメタデータ説明。これらは標準的な YAML パターンであり、必要に応じてユーザーが追加できます。
関連スキル
- hypothesis-generation -- 仮説を手作業で構築するためのフレームワークと科学的方法に関するノウハウ
- scikit-learn-machine-learning -- 仮説の解釈可能性が不要な場合の、分類のための従来型機械学習
- pubmed-database -- HypoRefine の入力に使う論文を見つけるための文献検索
参考文献
- Zhou, Y., Liu, H., Srivastava, T., Mei, H., & Tan, C. (2024). 「Hypothesis Generation with Large Language Models」. EMNLP Workshop NLP for Science. https://aclanthology.org/2024.nlp4science-1.10/
- Liu, H., Zhou, Y., Li, M., Yuan, C., & Tan, C. (2024). 「Literature Meets Data: A Synergistic Approach to Hypothesis Generation」. arXiv:2410.17309. https://arxiv.org/abs/2410.17309
- Liu, H., Huang, S., Hu, J., Zhou, Y., & Tan, C. (2025). 「HypoBench: Towards Systematic and Principled Benchmarking for Hypothesis Generation」. arXiv:2504.11524. https://arxiv.org/abs/2504.11524
- GitHub リポジトリ:https://github.com/ChicagoHAI/hypothesis-generation
- PyPI パッケージ:https://pypi.org/project/hypogenic/