MaxPowers
MaxPowers

Reputation: 5486

Error while computing probabilities of an array list

one can assign a probability to each element of an array by simply deviding the value of each element by the sum of all array elements. I am trying to do this with python for a long list of numpy arrays. My Code:

def calc_probs(self, array_list):

    for array in array_list:
        buffer=array.astype("float")
        s=sum(buffer)
        for e in np.nditer(buffer, op_flags=["readwrite"]):
            e/=s
        self.probs.append(buffer)

This code should be working. In fact it IS working when typing it into the interactive mode of IPython. The results are then just what I want them to be. But if I save the code to a file und run, I always get the following ValueError:

ValueError: non-broadcastable output operand with shape () doesn't match the broadcast shape (10)

I do not understand why this error occures, especially when running from a file. Could anyone please explain it to me and help to solve the problem? Thanks a lot!

Upvotes: 2

Views: 1456

Answers (1)

ecatmur
ecatmur

Reputation: 157354

sum is __builtin__.sum, which doesn't know how to sum a NumPy array so just returns the array unchanged. The error is happening because you are trying to divide the singular matrix e by the 10x10 matrix s.

You want s = np.sum(buffer).

This whole code could be simplified to:

self.probs.append(array / np.sum(array))

Upvotes: 3

Related Questions