I put in the following python code and can't figure out why I am getting an error. The loop runs fine, but the 'preds' keeps getting the error and points to the loop being the issue.
def predict(pred_prob,threshold):
pred = []
for i in range(len(pred_prob)):
if list[i] >= threshold:
pred.append(1)
else:
pred.append(0)
return pred
probs = [0.174,0.817,0.574,0.319,0.812,0.314,0.098,0.741,0.847,
0.202,0.31,0.073,0.179,]
thresh = 0.55
preds = predict(probs, thresh)
Why do I keep getting the following error "'type' object is not subscriptable"?
CodePudding user response:
You have tried to index list
, which is a Python type, not an actual list. In your problem, your actual list is called pred_prob
, so your predict function should rather be:
def predict(pred_prob, threshold):
pred = []
for i in range(len(pred_prob)):
if pred_prob[i] >= threshold:
pred.append(1)
else:
pred.append(0)
return pred
By the way, a more Pythonistic way of generating this result would be to use a comprehension, for example:
preds = [int(p >= thresh) for p in probs]
CodePudding user response:
On line 4, list
is a python type. You can't "get elements" from a type, because it is not iterable. I think you want to put pred_prob[i]
instead of list[i]