NameError: 名称 ‘plot_confusion_matrix’ 未定义

我在尝试使用VGG16创建一个分类模型,但在项目结束时遇到了获取混淆矩阵的错误。以下是代码,

导入的包和模块如下:

import osimport kerasimport numpy as npimport tensorflow as tffrom keras.models import Modelimport matplotlib.pyplot as pltfrom keras.optimizers import Adamfrom keras.applications import MobileNetfrom sklearn.metrics import confusion_matrixfrom keras.layers.core import Dense, Activationfrom keras.metrics import categorical_crossentropyfrom sklearn.model_selection import train_test_splitfrom keras.preprocessing.image import ImageDataGeneratorfrom keras.applications.mobilenet import preprocess_inputfrom tensorflow.keras.preprocessing import image_dataset_from_directory

注意: 为了简短,我跳过了数据集的链接

下面定义VGG16:

vgg16_model = keras.applications.vgg16.VGG16()vgg16_model.summary()

现在,定义模型:

model = Sequential()for layer in vgg16_model.layers:  model.add(layer)for layer in model.layers:  layer.trainable = Falsemodel.add(Dense(2, activation='softmax'))

编译模型:

model.compile(Adam(lr=.0001), loss='categorical_crossentropy', metrics=['accuracy'])

训练模型:

model.fit_generator(train_batches, steps_per_epoch=4, validation_data=valid_batches, validation_steps=4, epochs=10, verbose=2)

现在获取混淆矩阵:

test_imgs, test_labels = next(test_batches)plots(test_imgs, titles=test_labels)test_labels = test_labels[:,0] predictions = model.predict_generator(test_batches, steps=1, verbose=0)cm = confusion_matrix(test_labels, np.round(predictions[:,0]))

下面我遇到了一个错误,请关注下面的代码,

cm_plot_labels = ['diseaseAffectedEggplant','freshEggplant']plot_confusion_matrix(cm, cm_plot_labels, title="Confusion Matrix")   // 在这一行,我遇到了错误

错误信息如下,

---------------------------------------------------------------------------NameError                                 Traceback (most recent call last)<ipython-input-28-43b96d543746> in <module>()      1 cm_plot_labels = ['diseaseAffectedEggplant','freshEggplant']----> 2 plot_confusion_matrix(cm, cm_plot_labels, title="Confusion Matrix")NameError: name 'plot_confusion_matrix' is not defined

回答:

您需要从sklearn.metrics模块中导入plot_confusion_matrix

from sklearn.metrics import plot_confusion_matrix

请查看文档


函数plot_confusion_matrix在1.0版本中已被废弃,并在1.2版本中被移除。请使用类方法中的一个:ConfusionMatrixDisplay.from_predictionsConfusionMatrixDisplay.from_estimator

请查看文档

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注