[Kaggle] *Representing and Estimating Bayesian network
If you are using virtualenv or other native package management, you may need to run these commands:
pip install pandas matplotlib graphviz
To render the generated DOT source code, you also need to install Graphviz download page.
Link: https://graphviz.readthedocs.io/en/stable/examples.html
很有意思的一个库,画圈圈,画线线。
# Make division default to floating-point, saving confusion
from __future__ import division
from __future__ import print_function
# Necessary libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as pl
from random import random
# combinatorics
from itertools import product, combinations
# ordered dictionaries are useful for keeping ordered sets of varibles
from collections import OrderedDict as odict
#visualise our graph
from graphviz import Digraph # <-- interesting
# Put the graphs where we can see them
%matplotlib inline
# easier debugging display
pd.set_option('display.multi_sparse', False)
from pprint import pprint
| X | Y | Z | p(Z | X,Y) |
|---|---|---|---|
| 0 | 0 | 0 | 0 |
| 0 | 0 | 1 | 1 |
| 0 | 1 | 0 | 1/3 |
| 0 | 1 | 1 | 2/3 |
| 1 | 0 | 0 | 1/3 |
| 1 | 0 | 1 | 2/3 |
| 1 | 1 | 0 | 2/5 |
| 1 | 1 | 1 | 3/5 |
example_prob_table = odict([ ((0, 0,), [0.0, 1]), ((0, 1,), [1/3, 2/3]), ((1, 0,), [1/3, 2/3]), ((1, 1,), [2/5, 3/5]), ])
def p_cond(prob_table, this_val, *parents):
"""
argument
`prob_table`, a dictionary of conditional probabilities,
`this_val` (e.g., 1) the value of the variable we wish to find the probability for
`parents` (e.g. Y=1, Z=1) the parent values that we wish to set.
You must use a consistent order for the parents.
Returns p(X=this_val|parents(X)=parents)
"""
prob_array = np.asarray(prob_table[parents])
if this_val<prob_array.size:
return prob_array[this_val]
elif this_val == prob_array.size:
return 1.0 - prob_array.sum()
else:
return 0.0
print('p(Z=1|X=1,Y=1)={}'.format( p_cond(example_prob_table, 1, 1, 1) ))
example_prob_table = odict([ ((0, 0,), [0.0, 1]), ((0, 1,), [1/3, 2/3]), ((1, 0,), [1/3, 2/3]), ((1, 1,), [2/5, 3/5]),])

浙公网安备 33010602011771号