[SOLVED] Trying to create predict() function that accepts a list of prediction probabilities and a threshold value and computes final predictions

Issue

I am trying to write a function predict() that accepts as input a list of prediction probabilities and a threshold value, and computes the final predictions to be output by the model. If a prediction probability value is less than or equal to the threshold value, then the prediction is the negative case (i.e. 0). If a prediction probability value is greater than the threshold value, then the prediction is the positive case (i.e. 1).

When I pass the prediction probabilities (predict_prob) and threshold value (thresh) to the function, I get

TypeError: 'type' object is not subscriptable

I tried to change my predict_prob list to tuples which I thought was subscriptable, but I still get the same error. My code is below. Can someone assist?

# Create predict() function that accepts a list of prediction probabilities and a threshold value
def predict(predict_prob,thresh):
    pred = []  
    for i in range(len(predict_prob)):
        if list[i] >= thresh: 
            pred.append(1) 
        else:
            pred.append(0)
    return pred

predict_prob = [0.886,0.375,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,0.917,0.64,0.388,0.116,0.72]

thresh = 0.5

preds = predict(predict_prob, thresh)

Solution

list is a reserved word for python and that’s where the error comes from. You probably wanted to refer to predict_prob instead as in the corrected example below

# Create predict() function that accepts a list of prediction probabilities and a threshold value
def predict(predict_prob,thresh):
    pred = []  
    for i in range(len(predict_prob)):
        if predict_prob[i] >= thresh: 
            pred.append(1) 
        else:
            pred.append(0)
    return pred

predict_prob = [0.886,0.375,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,0.917,0.64,0.388,0.116,0.72]

thresh = 0.5

preds = predict(predict_prob, thresh)

One faster way to do that is using numpy arrays since it will be the following

import numpy as np
def predict(predict_prob, thresh):
   bool_res = np.array(predict_prob)>thresh
   return 1*bool_res

Answered By – DaSim

Answer Checked By – Jay B. (BugsFixing Admin)

Leave a Reply

Your email address will not be published.