自由エネルギー原理(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.pypython test_basic.pyfrom 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"],
))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-..."))| # | 改善箇所 | 旧版 | 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)