如何在循环中运行python程序10次并绘制每次的结果

时间:2018-12-02 19:37:34

标签: python python-3.x

我正在尝试运行此代码。我们将EM运行10个循环,并在每个循环中绘制结果。您想观察下面每个EM循环的进度。

X = np.linspace(-5,5,num=20)
X0 = X*np.random.rand(len(X))+10 # Create data cluster 1
X1 = X*np.random.rand(len(X))-10 # Create data cluster 2
X2 = X*np.random.rand(len(X)) # Create data cluster 3
X_tot = np.stack((X0,X1,X2)).flatten() # Combine the clusters to get the   random datapoints from above
class GMD:
def __init__(self,X,iterations):
    self.iterations = iterations
    self.X = X
    self.mu = None
    self.pi = None
    self.var = None

def run(self):

    self.mu = [-8,8,5]
    self.pi = [1/3,1/3,1/3]
    self.var = [5,3,1]


    for iter in range(self.iterations):
        r = np.zeros((len(X_tot),3))  

        for c,g,p in zip(range(3),[norm(loc=self.mu[0],scale=self.var[0]),
                                   norm(loc=self.mu[1],scale=self.var[1]),
                                   norm(loc=self.mu[2],scale=self.var[2])],self.pi):
                                       r[:,c] = p*g.pdf(X_tot)


        for i in range(len(r)):
            r[i] = r[i]/(np.sum(pi)*np.sum(r,axis=1)[i])

        """Plot the data"""
        fig = plt.figure(figsize=(10,10))
        ax0 = fig.add_subplot(111)
        for i in range(len(r)):
            ax0.scatter(self.X[i],0,c=np.array([r[i][0],r[i][1],r[i][2]]),s=100) 
        """Plot the gaussians"""
        for g,c in zip([norm(loc=self.mu[0],scale=self.var[0]).pdf(np.linspace(-20,20,num=60)),
                        norm(loc=self.mu[1],scale=self.var[1]).pdf(np.linspace(-20,20,num=60)),
                        norm(loc=self.mu[2],scale=self.var[2]).pdf(np.linspace(-20,20,num=60))],['r','g','b']):
            ax0.plot(np.linspace(-20,20,num=60),g,c=c)




            var_c.append((1/m_c[c])*np.dot(((np.array(r[:,c]).reshape(60,1))*(self.X.reshape(len(self.X),1)-self.mu[c])).T,(self.X.reshape(len(self.X),1)-self.mu[c])))
        plt.show()

GMD = GMD(X_tot,10)
GMD.run()

但是运行此代码后,它会在输出中显示以下错误 this message showing when I am going to run this code

2 个答案:

答案 0 :(得分:0)

您可以制作另一个文件并导入您的班级,然后执行以下操作:

<div class="background">
    <div class="foreground1">This is some text</div>
    <div class="foreground2">This is some text</div>
</div>

答案 1 :(得分:0)

我无法回答克劳斯的回答,但正如他指出的那样,您可能在一次调用pi值时错过了自我:

for i in range(len(r)):
    r[i] = r[i]/(np.sum(pi)*np.sum(r,axis=1)[i]) # Here the pi should be self.pi