假设我们对坦克总数有[500, 1000, 1500, 2000, 3000]五种可能的估计,先验估计为均匀分布,之后我们观察到战场上坦克编号出现有[4, 180, 75, 1007, 1003, 1500]
尝试估计这五种可能的后验概率分布如下:
500: 0.0
1000: 0.0
1500: 0.837
2000: 0.149
3000: 0.013
python 代码如下:
This file contains 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 collections import Counter | |
class Tank(): | |
def __init__(self,value): | |
self.tab = dict(Counter(value)) | |
def Values(self): | |
return self.tab.keys() | |
def Mult(self, x, factor): | |
self.tab[x] = self.tab.get(x, 0) * factor | |
def Likelihood(self, data, hypo): | |
if hypo < data: | |
return 0 | |
else: | |
return 1.0/hypo | |
def Normalize(self, fraction=1.0): | |
total = sum(self.tab.itervalues()) | |
factor = float(fraction) / total | |
for x in self.tab: | |
self.tab[x] *= factor | |
return sum(self.tab) | |
def Update(self, data): | |
for hypo in self.Values(): | |
like = self.Likelihood(data, hypo) | |
self.Mult(hypo, like) | |
return self.Normalize() | |
def Print(self): | |
for val, prob in sorted(self.tab.iteritems()): | |
print val, prob | |
def main(): | |
suite = Tank([500, 1000, 1500, 2000, 3000]) | |
for roll in [4, 180, 75, 1007, 1003, 1500]: | |
suite.Update(roll) | |
print 'After more obs' | |
suite.Print() | |
if __name__ == '__main__': | |
main() |
没有评论:
发表评论