Skip to content Skip to sidebar Skip to footer

How To Iterate Over A Numpy Matrix?

I have an matrix X = [[0. 0. 0. ... 0. 0. 0.] [0. 0. 0. ... 0. 0. 0.] [0. 0. 0. ... 0. 0. 0.] ...

Solution 1:

As a addition to @Eshwar S R's answer, this calculation can be done without a loop.

Is the output of the following code what you want?

loglike = np.sum(np.multiply(X_test, np.log(posprob)) + np.multiply((1-X_test), np.log(1-posprob)), axis=1)

Solution 2:

i is already a numpy array. No need to index it again as X[i]. Try this:

loglike = []
for i in X_test:
    p = np.sum(np.multiply(i, np.log(posprob)) + np.multiply((1-i), np.log(1-posprob)))
    loglike.append(p)
print(loglike)

Post a Comment for "How To Iterate Over A Numpy Matrix?"