一张图解释EM算法

文章:http://www.nature.com/nbt/journal/v26/n8/full/nbt1406.html

图:


代码:

#!/usr/bin/env python
import numpy as np

class Coin:
    def __init__(self):
        self.data = []
        self.label = []
        self.thetaA = 0.0
        self.thetaB = 0.0

    def CreateDataSet(self):
        self.thetaA = np.random.random()
        self.thetaB = np.random.random()
        for t in range(50):
            theta = self.thetaA
            label = 'A'
            if np.random.random() >= 0.5:
                theta = self.thetaB
                label = 'B'
            samples = []
            # 1:head; 0:tail
            for i in range(10):
                if np.random.random() >= theta: samples.append(0)
                else: samples.append(1)
            self.data.append(samples)
            self.label.append(label)

    def Expect(self, thetas):
        thetaA, thetaB = thetas
        expection = []
        for t in range(len(self.label)):
            numH = sum(self.data[t])
            numT = len(self.data[t]) - numH
            pA = (thetaA ** numH) * ((1-thetaA) ** numT)
            pB = (thetaB ** numH) * ((1-thetaB) ** numT)
            pA /= (pA + pB); pB = 1 - pA
            expection.append([pA, pB])
        return expection

    def Maximum(self, expection):
        numAH = 0.0; numAT = 0.0
        numBH = 0.0; numBT = 0.0
        for t in range(len(self.label)):
            numH = sum(self.data[t])
            numT = len(self.data[t]) - numH
            pA, pB = expection[t]
            numAH += pA * numH
            numAT += pA * numT
            numBH += pB * numH
            numBT += pB * numT
        newThetas = []
        newThetas.append(numAH / (numAH + numAT))
        newThetas.append(numBH / (numBH + numBT))
        return newThetas

    def Train(self, iters):
        self.CreateDataSet()
        thetas = np.array([self.thetaA - 0.1, self.thetaB + 0.1])
        print '-' * 20
        print 'initial thetas:[', thetas[0], thetas[1], ']'
        for i in range(iters):
            expection = self.Expect(thetas.tolist())
            newThetas = np.array(self.Maximum(expection))
            if max(np.abs(newThetas - thetas)) < 0.00001: break
            thetas = newThetas
            # print ' ' * 5, '[', thetas[0], thetas[1], ']'
        print 'train thetas:[', thetas[0], thetas[1], ']'
        print 'original thetas:[', self.thetaA, self.thetaB, ']'

if __name__ == '__main__':
    coin = Coin()
    coin.CreateDataSet()
    coin.Train(50)


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值