Skip to content

Instantly share code, notes, and snippets.

@smzn
Created February 19, 2024 00:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smzn/ae444db377445e579d30986a3267f30f to your computer and use it in GitHub Desktop.
Save smzn/ae444db377445e579d30986a3267f30f to your computer and use it in GitHub Desktop.
ベイジアンネットワークのモデルを作成
from pgmpy.models import BayesianNetwork
from pgmpy.factors.discrete import TabularCPD
# ベイジアンネットワークのモデルを作成
model = BayesianNetwork()
# ノードを追加
model.add_nodes_from(['B', 'E', 'A', 'P', 'S'])
# エッジを追加
model.add_edges_from([('B', 'A'), ('E', 'A'), ('A', 'P'), ('A', 'S')])
# 各ノードの条件付き確率分布を定義
cpd_b = TabularCPD(variable='B', variable_card=2, values=[[0.99], [0.01]]) # Bの事前確率
cpd_e = TabularCPD(variable='E', variable_card=2, values=[[0.98], [0.02]]) # Eの事前確率
cpd_a = TabularCPD(variable='A', variable_card=2,
values=[[0.92, 0.74, 0.06, 0.05], # P(A|B, E)
[0.08, 0.26, 0.94, 0.95]],
evidence=['B', 'E'], evidence_card=[2, 2])
cpd_p = TabularCPD(variable='P', variable_card=2, values=[[0.5, 0.5], [0.5, 0.5]], evidence=['A'], evidence_card=[2]) # Pの条件付き確率(今回は未設定)
cpd_s = TabularCPD(variable='S', variable_card=2, values=[[0.9, 0.3], [0.1, 0.7]], evidence=['A'], evidence_card=[2]) # Sの条件付き確率
# モデルに条件付き確率分布を追加
model.add_cpds(cpd_b, cpd_e, cpd_a, cpd_p, cpd_s)
# モデルの構造とCPDsが有効であるかをチェック
assert model.check_model()
# ベイジアンネットワークの概要を出力
print(model)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment