Python 绩效评价模型不';行不通

Python 绩效评价模型不';行不通,python,jupyter-notebook,tensorflow2.0,Python,Jupyter Notebook,Tensorflow2.0,我试图通过调用模型的evaluate方法在测试集上评估模型的性能 import tensorflow as tf import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Flatten, Con

我试图通过调用模型的evaluate方法在测试集上评估模型的性能

import tensorflow as tf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline 
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten, Conv2D, MaxPooling2D
from tensorflow.keras.preprocessing import image
在导入LIB之后 我上传了数据集

mnist_data = tf.keras.datasets.mnist
(train_images, train_labels), (test_images, test_labels) = mnist_data.load_data()
现在,问题真的来自这一部分,我不知道为什么

test_loss, test_accuracy = evaluate_model(model, scaled_test_images, test_labels)

print(f"Test loss: {test_loss}")
print(f"Test accuracy: {test_accuracy}")
我得到了这个错误:

10000/1 [=================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================5s 499us/sample - loss: 0.0256 - acc: 0.9840 - mae: 4.3630
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-16-0cceed9839ec> in <module>
      1 # Run your function to evaluate the model
      2 
----> 3 test_loss, test_accuracy = evaluate_model(model, scaled_test_images, test_labels)
      4 
      5 print(f"Test loss: {test_loss}")

<ipython-input-15-2804922fd7ac> in evaluate_model(model, scaled_test_images, test_labels)
      9     Your function should return a tuple (test_loss, test_accuracy).
     10     """
---> 11     (test_loss, test_accuracy) = model.evaluate(scaled_test_images, test_labels)
     12     return (test_loss, test_accuracy)

ValueError: too many values to unpack (expected 2)

您必须删除其中一个度量标准
acc
mae
,原因是它相互冲突

model.compile(
    optimizer = opt,
    loss = 'sparse_categorical_crossentropy', 
    metrics = ['acc'] # this or metrics = ['mae']
)
使用评估功能将返回
损失
acc
mae
,具体取决于您设置的值

#using accuracy
(test_loss, test_accuracy) = model.evaluate(scaled_test_images, test_labels)

在您的情况下,我建议使用“acc”,因为这是一个分类问题,所以它是准确的,但是,它取决于您使用它的目的


您还可以使用函数
tf.keras.metrics.mean_absolute_error(x_有效,结果)
计算
平均绝对误差
,在编译模型时,您是否指定了任何指标
model.evaluate()
只有在
model.compile()
@MrSoLoDoLo def compile\u model(model):opt=tf.keras.optimizers.Adam(learning\u rate=0.005)acc=tf.keras.metrics.sparsecategoricacacity()mae=tf.keras.metrics.meanAbsoluduteError()model.compile中指定了多个输出,才会返回它们(optimizer=opt,loss='sparse\u categorical\u crossentropy',metrics=['acc','mae'])这就是问题所在。
model.evaluate()
默认情况下只返回
损耗
。由于您在
模型中指定了另外两个度量值
acc
mae
。compile()
,它将返回一个包含3个输出的列表。因此,请尝试通过
测试损耗、测试精度、测试mae=评估模型(模型、缩放的测试图像、测试标签)解包
查看您拥有多少度量的简单方法是通过
打印(model.metrics\u names)
。然后您可以相应地解压元组。@MrSoLoDoLo仍然无法工作,我将编辑代码,以便您可以修改ITI@kha。如果这解决了您的问题,请接受并对答案进行评分
num_test_images = scaled_test_images.shape[0]

random_inx = np.random.choice(num_test_images, 4)
random_test_images = scaled_test_images[random_inx, ...]
random_test_labels = test_labels[random_inx, ...]

predictions = model.predict(random_test_images)

fig, axes = plt.subplots(4, 2, figsize=(16, 12))
fig.subplots_adjust(hspace=0.4, wspace=-0.2)

for i, (prediction, image, label) in enumerate(zip(predictions, random_test_images, random_test_labels)):
    axes[i, 0].imshow(np.squeeze(image))
    axes[i, 0].get_xaxis().set_visible(False)
    axes[i, 0].get_yaxis().set_visible(False)
    axes[i, 0].text(10., -1.5, f'Digit {label}')
    axes[i, 1].bar(np.arange(len(prediction)), prediction)
    axes[i, 1].set_xticks(np.arange(len(prediction)))
    axes[i, 1].set_title(f"Categorical distribution. Model prediction: {np.argmax(prediction)}")
    
plt.show()
model.compile(
    optimizer = opt,
    loss = 'sparse_categorical_crossentropy', 
    metrics = ['acc'] # this or metrics = ['mae']
)
#using accuracy
(test_loss, test_accuracy) = model.evaluate(scaled_test_images, test_labels)
#using mae
(test_loss, test_mae) = model.evaluate(scaled_test_images, test_labels)