Skip to content

takeuchiruiac-sys/fep-hypothesis-explorer.v1

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🧠 FEP Hypothesis Explorer v2

自由エネルギー原理(Free Energy Principle)に基づくニューロシンボリック仮説探索器

自由エネルギー最小化ループにより、観測データから仮説を自律的に生成・評価・選択するPythonフレームワークです。


概要

本システムは、Karl Fristonの自由エネルギー原理と**能動的推論(Active Inference)**を計算的に実装し、以下のサイクルを自律的に回します:

入力 → 構造化 → [信念更新 → 予測 → 驚き計算 → 行動選択 → 実行] × N → 検証 → 応答

主な特徴

  • 変分自由エネルギーを分布全体で正しく計算(KLダイバージェンス + 精度項)
  • Noisy-OR尤度モデルによる条件付き確率の厳密定義
  • 全計算を対数空間で実行(数値安定性の保証)
  • 5つの仮説探索戦略: アブダクション / 演繹的組合せ / 類推 / 変異 / LLMアブダクション
  • **期待自由エネルギー(EFE)**に基づく情報理論的行動選択
  • **Truth Maintenance System(TMS)**による信念の依存追跡と自動撤回
  • 評価フレームワーク内蔵(accuracy, 収束率, エントロピー削減等)

アーキテクチャ

┌──────────────────────────────────────────────────────┐
│  Input (natural language)                            │
│  ↓                                                   │
│  [InputParser] ─── LLM構造化 + well-formedness検証   │
│  ↓                                                   │
│  [FreeEnergyMinimizationLoop]                        │
│  │  perception (Bayesian belief update)              │
│  │  prediction → surprise                            │
│  │  EFE計算 → action selection                       │
│  │  ├─ explore (abduce/deduce/analogy/mutate/LLM)   │
│  │  ├─ gather info                                   │
│  │  ├─ update model                                  │
│  │  ├─ request clarification                         │
│  │  └─ generate response                             │
│  └─ loop until converged                             │
│  ↓                                                   │
│  [Verifier] ─── 確定論理層で検証                      │
│  ↓                                                   │
│  [Reconciler] ─── 矛盾解消                           │
│  ↓                                                   │
│  [ResponseGenerator] ─── 仮説に基づく応答構築         │
│  ↓                                                   │
│  Output (confidence + justification + trace)         │
└──────────────────────────────────────────────────────┘

ディレクトリ構成

fep-hypothesis-explorer.v1/
├── core/                  # 基盤型定義・ユーティリティ
│   ├── types.py           #   Scope, LogicalRule, Hypothesis, Prediction
│   ├── math_utils.py      #   logsumexp 等
│   └── llm_backend.py     #   LLMBackend Protocol + DefaultLLMBackend
├── logic/                 # 確定論理層
│   ├── axiom_store.py     #   公理ストア(規則の格納・索引・検索)
│   └── tms.py             #   Truth Maintenance System
├── inference/             # 推論コア
│   ├── generative_model.py  # 尤度・変分FE・ベイズ更新・驚き計算
│   ├── explorer.py          # 仮説探索器(5戦略)
│   └── action_selector.py   # 行動選択器(EFE計算)
├── loop/                  # メインループ
│   └── fep_loop.py        #   FreeEnergyMinimizationLoop
├── language/              # 言語層
│   ├── input_parser.py    #   自然言語 → 述語論理パーサー
│   └── response_gen.py    #   仮説ベース応答生成器
├── evaluation/            # 評価フレームワーク
│   └── evaluator.py       #   定量評価(accuracy, 収束率 等)
├── agi.py                 # NeuroSymbolicFEP_AGI 統合クラス
├── main.py                # エントリポイント(実行例 + 評価)
└── test_basic.py          # 基本テスト

セットアップ

必要環境

  • Python 3.11+
  • 外部ライブラリ依存なし(標準ライブラリのみ)

インストール・実行

git clone https://github.com/takeuchiruiac-sys/fep-hypothesis-explorer.v1.git
cd fep-hypothesis-explorer.v1
python main.py

テスト

python test_basic.py

使い方

基本的な推論

from agi import NeuroSymbolicFEP_AGI

agi = NeuroSymbolicFEP_AGI()

result = agi.think(
    user_input="支えを失った物体が上に動くことはありますか?",
    context={
        "satisfied_conditions": ["classical_regime"],
        "domain": "physics",
    },
)

print(f"Response: {result['response']}")
print(f"Confidence: {result['confidence']:.2%}")
print(f"Verification: {result['verification']}")

評価の実行

from evaluation.evaluator import Evaluator, EvaluationCase

evaluator = Evaluator(agi)

cases = [
    EvaluationCase(
        input_text="鉄球を水に入れたら沈みますか?",
        context={
            "satisfied_conditions": ["classical_regime", "fluid_is_water"],
            "domain": "physics",
        },
        expected_conclusion="sinks",
        expected_min_confidence=0.7,
        tags=["physics", "density"],
    ),
]

metrics = evaluator.evaluate(cases)
print(f"Accuracy: {metrics.accuracy:.2%}")
print(f"Convergence Rate: {metrics.convergence_rate:.2%}")

カスタム知識の追加

from core.types import LogicalRule, Scope

agi.axiom_store.add_rule(LogicalRule(
    rule_id="BIO_PHOTOSYNTHESIS",
    antecedent="plant_exposed_to_sunlight",
    consequent="plant_produces_glucose",
    confidence=0.95,
    scope=Scope("biology", preconditions=["has_chlorophyll"]),
    source=["Biology 101"],
))

LLMバックエンドの差し替え

from core.llm_backend import LLMBackend

class OpenAIBackend:
    def __init__(self, api_key: str):
        import openai
        self.client = openai.OpenAI(api_key=api_key)

    def generate(self, prompt: str, **kwargs) -> str:
        resp = self.client.chat.completions.create(
            model="gpt-4o",
            messages=[{"role": "user", "content": prompt}],
        )
        return resp.choices[0].message.content

    def embed(self, text: str) -> list[float]:
        resp = self.client.embeddings.create(
            model="text-embedding-3-small", input=text
        )
        return resp.data[0].embedding

agi = NeuroSymbolicFEP_AGI(llm=OpenAIBackend("sk-..."))

数学的基盤

変分自由エネルギー

$$F = \underbrace{\sum_i q(\theta_i) \left[\ln q(\theta_i) - \ln p(\theta_i)\right]}_{D_{KL}[q(\theta) | p(\theta)]} - \underbrace{\sum_i q(\theta_i) \sum_j \ln p(o_j | \theta_i)}_{\mathbb{E}_q[\ln p(o|\theta)]}$$

ベイズ更新(対数空間)

$$\ln q(\theta_i) = \ln p(\theta_i) + \sum_j \ln p(o_j | \theta_i) - \ln Z$$

尤度関数(Noisy-OR)

$$P(o | \theta) = 1 - \prod_r \left(1 - c_r\right)$$

期待自由エネルギー(EFE)

$$G(\pi) = -\underbrace{\left[H[q(\theta)] - \mathbb{E}_{q(o|\pi)}[H[q(\theta|o,\pi)]]\right]}_{\text{epistemic value (情報利得)}} + \underbrace{D_{KL}[q(o|\pi) | \tilde{p}(o)]}_{\text{pragmatic value}}$$

驚き

$$\text{surprise} = -\ln p(o) = -\ln \sum_i q(\theta_i), p(o | \theta_i)$$


設計改善点(v1 → v2)

# 改善箇所 旧版 v2
1 変分自由エネルギー 各仮説を独立に計算 分布全体で正しくKLを計算
2 尤度関数 rule.confidence をそのまま返す Noisy-OR条件付き確率
3 数値安定性 尤度の連乗 全て対数空間 + logsumexp
4 EFE ハードコード 情報利得を情報理論的に計算
5 LLM統合 スタブのみ 構造化抽出 + 検証パイプライン
6 仮説重複排除 なし frozenset による論理形式の重複検出
7 収束条件 驚き閾値のみ 驚き + ΔFEの二重条件
8 評価 なし accuracy, 収束率, エントロピー削減

調整可能パラメータ

パラメータ クラス デフォルト 説明
surprise_threshold GenerativeModel 2.0 驚きの閾値。小さくすると早期収束
fe_change_threshold FEPLoop 0.01 FE変化量の収束判定閾値
max_cycles FEPLoop 10 最大推論サイクル数
exploration_budget HypothesisExplorer 50 1サイクルあたりの探索予算
complexity_weight GenerativeModel 1.0 KL項の重み(大→オッカムの剃刀)
accuracy_weight GenerativeModel 1.0 精度項の重み
epistemic_weight ActionSelector 1.0 認識的価値の重み(大→探索的)
pragmatic_weight ActionSelector 1.0 実用的価値の重み(大→目標指向)

ロードマップ

  • LLMバックエンド実装(OpenAI / Anthropic)
  • 公理ストアの永続化(SQLite)
  • 非同期推論ループ(asyncio
  • 仮説pruning(上限数管理)
  • 推論トレースの可視化ダッシュボード
  • ベンチマークスイートの拡充
  • REST APIラッパー

ライセンス

MIT License(予定)


著者

Rui Takeuchi (@takeuchiruiac-sys)

About

自由エネルギー原理による仮説探索器

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages