【问题标题】:return mutliple variables from a function to be used elsewhere in Python program从函数返回多个变量以在 Python 程序的其他地方使用
【发布时间】:2021-10-26 23:27:03
【问题描述】:

我正在尝试从 Python 中的 def 中提取特定变量。 def 的格式如下:

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)

整体代码的骨架如下:

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)

您能告诉我如何从def 获取return 值吗?

【问题讨论】:

  • 你是问如何获取函数的返回值?
  • 首先是一个函数,而不是一个def。但你是什么意思?要从函数中获取值,您需要运行它并将结果分配给一个/多个变量。
  • predicted_proba_vector, category = print_prediction(file_name) 类似的东西会给变量赋值
  • 是的,乔,假设您希望变量在退出函数后名称相同,这是正确的(在您的情况下,“文件名”除外,应为“文件路径”)
  • 是的,只需将 file_name 更改为您的变量 file_path

标签: python-3.x function return-value


【解决方案1】:

要将print_prediction 的返回值分配给变量,只需将for 循环中的第二行更改为:

predicted_proba_vector, category = print_prediction(file_path)

完整的循环应该如下所示:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 2012-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多