Created
February 18, 2024 20:32
ベイジアンネットワークの作成
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pgmpy.models import BayesianNetwork | |
from pgmpy.factors.discrete import TabularCPD | |
# ベイジアンネットワークのモデルを作成 | |
model = BayesianNetwork() | |
# ノードを追加 | |
model.add_nodes_from(['W', 'S', 'R', 'G']) | |
# エッジを追加 | |
model.add_edges_from([('W', 'S'), ('W', 'R'), ('S', 'G'), ('R', 'G')]) | |
# 各ノードの条件付き確率分布を定義(行に変数、列に条件) | |
cpd_w = TabularCPD(variable='W', variable_card=2, values=[[0.5], [0.5]]) #事前確率 | |
cpd_s = TabularCPD(variable='S', variable_card=2, values=[[0.9, 0.5], [0.1, 0.5]], evidence=['W'], evidence_card=[2]) #[[P(S=0|W=0), P(S=0|W=1)], [P(S=1|W=0), P(S=1|W=1)]] | |
cpd_r = TabularCPD(variable='R', variable_card=2, values=[[0.2, 0.8], [0.8, 0.2]], evidence=['W'], evidence_card=[2]) #[[P(R=0|W=0), P(R=0|W=1)], [P(R=1|W=0), P(R=1|W=1)]] | |
cpd_g = TabularCPD(variable='G', variable_card=2, values=[[0.99, 0.1, 0.1, 0.01], [0.01, 0.9, 0.9, 0.99]], evidence=['S', 'R'], evidence_card=[2, 2]) #[[P(G=0|S=0, R=0), P(G=0|S=0, R=1), P(G=0|S=1, R=0), P(G=0|S=1, R=1)], [P(G=1|S=0, R=0), P(G=1|S=0, R=1), P(G=1|S=1, R=0), P(G=1|S=1, R=1)]] | |
# モデルに条件付き確率分布を追加 | |
model.add_cpds(cpd_w, cpd_s, cpd_r, cpd_g) | |
# モデルの構造と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