Keras 混淆矩阵看起来不正确

Keras Confusion Matrix does not look right

我是 运行 乳腺癌数据集上的 Keras 模型。我用它获得了大约 96% 的准确率,但混淆矩阵完全消失了。以下是图表:

这是我的混淆矩阵:

矩阵说我没有真阴性,它们实际上是假阴性,而我认为情况恰恰相反。我注意到的另一件事是,当真实值的数量相加并除以测试集的长度时,结果并不反映从模型计算的分数。这是完整的代码:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

from tensorflow import keras
from tensorflow.math import confusion_matrix
from keras import Sequential
from keras.layers import Dense

breast = load_breast_cancer()
X = breast.data
y = breast.target

#Split data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)

#Scale data
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.fit_transform(X_test)

#Create and fit keras model
model = Sequential()
model.add(Dense(8, activation='relu', input_shape=[X.shape[1]]))
model.add(Dense(4, activation='relu'))
model.add(Dense(1, activation='sigmoid'))

model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

history = model.fit(X_train, y_train, validation_data=(X_test, y_test), batch_size=16, epochs=50, verbose=1)
history = pd.DataFrame(history.history)

#Display loss visualization
history.loc[:,['loss','val_loss']].plot();

history.loc[:,['accuracy','val_accuracy']].plot();

#Create confusion matrix
y_pred = model.predict(X_test)
conf_matrix = confusion_matrix(y_test,y_pred)
cm = sns.heatmap(conf_matrix, annot=True, cmap='gray', annot_kws={'size':30})
cm_labels = ['Positive','Negative']
cm.set_xlabel('True')
cm.set_xticklabels(cm_labels)
cm.set_ylabel('Predicted')
cm.set_yticklabels(cm_labels);

我是不是做错了什么?我错过了什么吗?

检查 sklearn.metrics.confusion_matrix official documentation 中的混淆矩阵值。这些值是这样组织的:

  • TN: 左上角
  • FP:右上角
  • FN:左下角
  • TP:右下角

您从当前的混淆矩阵中得到 53 个真阴性和 90 个假阴性。