标签:EM,qq,format,self,2f,算法,jj,print From: https://www.cnblogs.com/lld76/p/16821436.html
# 1,求观测序列的概率
# 2,已知状态序列求观测序列
# 3,已知观测序列求模型参数
# 设状态值概率
# pA=0.6
# pB=0.5
class EM():
def __init__(self):
self.t = 0.6
self.q = 0.5
def E(self, i, j):
pA = (self.t ** i) * ((1 - self.t) ** j)
pB = (self.q ** i) * ((1 - self.q) ** j)
d = pA / (pA + pB)
b = pB / (pA + pB)
# print('选择A的概率:{:.2f},选择B的概率:{:.2f}'.format(d, b))
cd = d * i
ad = d * j
# print('硬币A,正面朝上次数的期望值:{:.1f} 反面:{:.1f}'.format(cd, ad))
cb = b * i
ab = b * j
# print('硬币B,正面朝上次数的期望值:{:.1f} 反面:{:.1f}'.format(cb, ab))
# print('-' * 50)
return cd, ad, cb, ab
def M(self):
qq = 0
tt = 0
jj = 0
cc = 0
td = [[5,5],[9,1],[8,2],[4,6],[7,3]]
for i,j in td:
a, b, c, d = self.E(i, j)
qq += a
tt += b
jj += c
cc += d
print(qq, tt)
print('A正面概率:{:.2f} 反面概率:{:.2f}'.format(qq/(qq+tt), tt/(qq+tt)))
print(jj, cc)
print('B正面概率:{:.2f} 反面概率:{:.2f}'.format(jj/(jj+cc), cc/(jj+cc)))
self.t = round(qq/(qq+tt), 3)
self.q = round(jj/(jj+cc), 3)
print('完')
def run(self):
self.s = None
self.p = None
while 1:
if (self.s == self.t) and (self.p == self.q):
break
else:
self.s = self.t
self.p = self.q
self.M()
EM().run()
def EM1(i, j):
t,q = 0.2,0.7
a = (t**i) * ((1-t)**j)
b = (q**i) * ((1-q)**j)
print('A:{:.2f} B:{:.2f}'.format(a, b))
c = a / (a + b)
d = b / (a + b)
print('使用A概率{:.2f},使用B概率{:.2f}'.format(c, d))
e = c * i
f = c * j
print('{:.2f} {:.2f}'.format(e, f))
print('-'*50)
# g = d * i
# h = d * j
# print(g, h)
t, q = c/10, e/10
# EM1(3, 2)
# EM1(2, 3)
# EM1(1, 4)
# EM1(3, 2)
# EM1(2, 3)