Python 实现贝叶斯架构
coding准备:需要python载入thinkbayes.py,Github:https://github.com/AllenDowney/ThinkBayes/blob/master/code/thinkbayes.py
贝叶斯架构
主体coding:
class Cookie(Pmf):
```python
def __init__(self,hypos) ###给每个hypo都赋予相同的先验概率
Pmf.__init__(self)
for hypo in hypos:
self.Set(hypo,1)
self.Normalize()
def Update(self,data): ###更新观测,改变相应概率
for hypo in self.Values():
like = self.Likelihood(data,hypo)
self.Mult(hypo,like)
self.Normalize()
mixes={
'Bow1':dict(vanilla=0.75, chocolate=0.25),
'Bow2':dict(vanilla=0.5, chocolate=0.5),
} ###用dict描述概率背景
def Likelihood(self,data,hypo): ###计算似然度
mix = self.mixes[hypo] ## Bow1 or Bow2?
like = mix[data] ## vanilla or chocolate?
return like
hypos = ['Bow1','Bow2']
pmf = Cookie(hypos)
pmf.Update('vanilla')
for hypo, prob in pmf.Items():
print(hypo,prob)
> Bow1 0.6
Bow2 0.4
这个框架的一个好处是它可以推广到多个元素的情况:
dataset = ['vanilla','vanilla']
for data in dataset:
pmf.Update(data)
for hypo, prob in pmf.Items():
print(hypo,prob)
> Bow1 0.692
Bow2 0.308
这个code为我们提供了解决很多贝叶斯问题的一个框架
Morty Hall Problem:
from thinkbayes import Pmf
pmf = Pmf()
class monty(Pmf):
def __init__(self,hypos