Edamame
Edamame

Reputation: 25366

Python: sum over arrays element by element

I have some probability output of 5 models, and I sum of the probabilities element by element like below:

probs = [None] * 5

for i in range(0,5):
  probs[i] = models[i].predict_proba(X)

probs[0] + probs[1] + probs[2] + probs[3] + probs[4]

This works fine.

I then tried to simplified the above code a bit by doing below:

probs = [None] * 5
results = [None]

for i in range(0,5):
  probs[i] = models[i].predict_proba(X)
  results += probs[i]

results

But got the following error:

TypeError unsupported operand type(s) for +: 'NoneType' and 'float' 
TypeErrorTraceback (most recent call last)
<ipython-input-20-8d4d443a7428> in <module>()
      4 for i in range(0,5):
      5   probs[i] = models[i].predict_proba(X)
----> 6   results += probs[i]
      7 
      8 results

TypeError: unsupported operand type(s) for +: 'NoneType' and 'float'

How could I fix such error? Thanks.

Note: 

probs[i] is of format:

array([[  9.99877759e-01,   1.22241455e-04],
       [  9.99694005e-01,   3.05994629e-04],
       [  9.47546608e-01,   5.24533925e-02],
       [  1.83994998e-01,   8.16005002e-01],
       [  9.66928729e-01,   3.30712706e-02],
       [  9.99487283e-01,   5.12717255e-04],
       [  2.85824823e-03,   9.97141752e-01],
       [  9.97979081e-01,   2.02091861e-03],
       [  9.99744813e-01,   2.55186665e-04]])

Upvotes: 1

Views: 103

Answers (4)

Bill
Bill

Reputation: 11658

This should solve the problem:

probs = [None] * 5
results = np.zeros(data.shape)

for i in range(0,5):
  probs[i] = models[i].predict_proba(X)
  results += probs[i]

results

Where, data.shape should be the expected shape of the result from models[i].predict_proba(X).

Upvotes: 0

StackOverPine
StackOverPine

Reputation: 11

You defined result as a list, but it should be a float type. Try this:

results = 0

Upvotes: 1

JACK ZHANG
JACK ZHANG

Reputation: 610

You assigned [None] as your result at the beginning, and then try to add it immediately in the first iteration of the for loop, and that causes the error message.

Instead, you can try use list comprehension since using Python:

result = sum([models[i].predict_proba(X) for i in range(5)])

Upvotes: 2

user3483203
user3483203

Reputation: 51165

Your issue is that you are trying to add a float to None. You can simplify your code greatly using a list comprehension:

probs = [models[i].predict_proba(X) for i in range(5)]

And then to get the sum, just sum(probs)

Upvotes: 3

Related Questions