1

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]])
2
  • Why is results a list? Shouldn't it be a float? Commented Mar 30, 2018 at 22:57
  • Just set results = 0 and your code will run fine. However, you should really consider the answers below as they are more pythonic. Commented Mar 30, 2018 at 23:08

4 Answers 4

3

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)

Sign up to request clarification or add additional context in comments.

Comments

2

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)])

Comments

1

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

results = 0

Comments

0

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.