Search code examples
python-3.xfunctionreturn-value

return mutliple variables from a function to be used elsewhere in Python program


I am trying to extract a specific variable from a def in Python. The def has the format as follows:

def print_prediction(file_name):
    prediction_feature = extract_features(file_name)
    prediction_feature = prediction_feature.reshape(1, num_rows, num_columns, num_channels)
    model_path = os.path.join("ModelPath")
    model = load_model(filepath)

    predicted_vector = np.argmax(model.predict(prediction_feature), axis=-1)
    predicted_class = le.inverse_transform(predicted_vector)
    print("The predicted class is:", predicted_class[0])

    predicted_proba_vector = model.predict(prediction_feature)
    predicted_proba = predicted_proba_vector[0]
    for i in range(len(predicted_proba)):
        category = le.inverse_transform(np.array([i]))
        print(category[0], "\t\t : ", format(predicted_proba[i], '.15f'))
    print('\n')

    return (predicted_proba_vector, category)

The skeleton of the overall code is as follows:

imports

def

for index, row in metadata.iterrows():
    file_path = os.path.join(os.path.abspath(fulldatasetpath)+'/'+str(row["file_name"]))
    print_prediction(file_path)
    prob1 = predicted_proba_vector[0]
    cat1 = format(predicted_proba[1], '.15f'

    predictions.append([file_path, prob1])
    time.sleep(.1)

Can you tell me how I can go about getting the return values from the def.


Solution

  • To assign the return values from print_prediction to variables just change the 2nd line inside your for loop to:

    predicted_proba_vector, category = print_prediction(file_path)
    

    The full loop should then look like:

    for index, row in metadata.iterrows():
        file_path = os.path.join(os.path.abspath(fulldatasetpath)+'/'+str(row["file_name"]))
        predicted_proba_vector, category = print_prediction(file_path)
        prob1 = predicted_proba_vector[0]
        cat1 = format(predicted_proba[1], '.15f')
    
        predictions.append([file_path, prob1])
        time.sleep(.1)