【发布时间】: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