Why is there difference between cmd line and .py file?

Robert rxjwg98 at gmail.com
Tue Jan 5 15:25:48 EST 2016


Hi,

I run below code, which is downloaded from link:

http://stackoverflow.com/questions/15513792/expectation-maximization-coin-toss-examples?rq=1



////////////
# represent the experiments
head_counts = np.array([5,9,8,4,7])
tail_counts = 10-head_counts
experiments = zip(head_counts,tail_counts)

# initialise the pA(heads) and pB(heads)
pA_heads = np.zeros(100); pA_heads[0] = 0.60
pB_heads = np.zeros(100); pB_heads[0] = 0.50

# E-M begins!
delta = 0.001  
j = 0 # iteration counter
improvement = float('inf')
while (improvement>delta):
    expectation_A = np.zeros((5,2), dtype=float) 
    expectation_B = np.zeros((5,2), dtype=float)
    for i in range(0,len(experiments)):
        e = experiments[i] # i'th experiment
        ll_A = get_mn_log_likelihood(e,np.array([pA_heads[j],1-pA_heads[j]])) # loglikelihood of e given coin A
        ll_B = get_mn_log_likelihood(e,np.array([pB_heads[j],1-pB_heads[j]])) # loglikelihood of e given coin B

        weightA = math.exp(ll_A) / ( math.exp(ll_A) + math.exp(ll_B) ) # corresponding weight of A proportional to likelihood of A 
        weightB = math.exp(ll_B) / ( math.exp(ll_A) + math.exp(ll_B) ) # corresponding weight of B proportional to likelihood of B                            

        expectation_A[i] = np.dot(weightA, e) 
        expectation_B[i] = np.dot(weightB, e)

    print "sum(expectation_A)[0]", sum(expectation_A)[0]
    pA_heads[j+1] = sum(expectation_A)[0] / sum(sum(expectation_A)); 
    pB_heads[j+1] = sum(expectation_B)[0] / sum(sum(expectation_B));
//////////
The print message is: 
sum(expectation_A)[0] 21.2974818963
sum(expectation_A)[0] 19.2093824201
sum(expectation_A)[0] 19.4102767983
sum(expectation_A)[0] 19.7538328728
sum(expectation_A)[0] 19.9753285438
sum(expectation_A)[0] 20.0879016403
sum(expectation_A)[0] 20.139820175
sum(expectation_A)[0] 20.1628374165



When I check below in detail in interactive mode (Canopy Python shell),
 
sum(expectation_A)[0]

it has error:
/////////////
sum(expectation_A)[0]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-145-d6f33dff0343> in <module>()
----> 1 sum(expectation_A)[0]

IndexError: invalid index to scalar variable. 
//////////////

I can see expectation_A content with:

In[146]:expectation_A
Out[146]: 
array([[ 0.52278641,  0.52278641],
       [ 8.55858656,  0.95095406],
       [ 6.75024946,  1.68756237],
       [ 0.1260128 ,  0.1890192 ],
       [ 4.20520218,  1.80222951]])

It looks like 
sum(expectation_A)[0]

can run in .py file, while it cannot be run in python shell.
Is it true?

Thanks,



More information about the Python-list mailing list