渲染混淆矩阵
Rendering a confusion matrix
我正在使用 jupyterlab
,专门渲染混淆矩阵。但是,在渲染矩阵时,似乎有什么不对劲,因为图形没有完全渲染。
我已经安装了sklearn包,但还是一样的问题。我尝试了不同的替代方案,但仍然渲染了一个剪断的混淆矩阵。
下面是我知道会呈现正确混淆矩阵的代码示例。
from sklearn.metrics import classification_report, confusion_matrix
import itertools
import matplotlib.pyplot as plt
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("Normalized confusion matrix")
else:
print('Confusion matrix, without normalization')
print(cm)
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, format(cm[i, j], fmt),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
# Compute confusion matrix
cnf_matrix = confusion_matrix(y_test, yhat, labels=[2,4])
np.set_printoptions(precision=2)
print (classification_report(y_test, yhat))
# Plot non-normalized confusion matrix
plt.figure()
plot_confusion_matrix(cnf_matrix, classes=['Benign(2)','Malignant(4)'],normalize= False, title='Confusion matrix')
从上面的代码中,我得到了这个混淆矩阵:
然而,我希望有一个非剪断的混淆矩阵,例如:
致谢:@Calvin Duy Canh Tran
2019-08-05 更新:
为了不怀疑上面使用的代码,我使用了额外的参考:相反,我尝试了混淆矩阵文档示例之一的代码 scikit-learn
。 link 就是这个 https://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html
在运行上述代码之前,我安装了对应的模块:
pip install -q scikit-plot
不幸的是,输出继续呈现截断的矩阵(见图):
正确的输出应该是这个(忽略方向):
不要将混淆矩阵作为输入参数传递给绘图函数。您需要传递 y_test, y_pred
并且混淆矩阵将在内部计算。
绘制它使用这个:
def plot_confusion_matrix(y_true, y_pred, classes,
normalize=False,
title=None,
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
if not title:
if normalize:
title = 'Normalized confusion matrix'
else:
title = 'Confusion matrix, without normalization'
# Compute confusion matrix
cm = confusion_matrix(y_true, y_pred)
# Only use the labels that appear in the data
classes = classes[unique_labels(y_true, y_pred)]
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("Normalized confusion matrix")
else:
print('Confusion matrix, without normalization')
print(cm)
fig, ax = plt.subplots()
im = ax.imshow(cm, interpolation='nearest', cmap=cmap)
ax.figure.colorbar(im, ax=ax)
# We want to show all ticks...
ax.set(xticks=np.arange(cm.shape[1]),
yticks=np.arange(cm.shape[0]),
# ... and label them with the respective list entries
xticklabels=classes, yticklabels=classes,
title=title,
ylabel='True label',
xlabel='Predicted label')
# Rotate the tick labels and set their alignment.
plt.setp(ax.get_xticklabels(), rotation=45, ha="right",
rotation_mode="anchor")
# Loop over data dimensions and create text annotations.
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.
for i in range(cm.shape[0]):
for j in range(cm.shape[1]):
ax.text(j, i, format(cm[i, j], fmt),
ha="center", va="center",
color="white" if cm[i, j] > thresh else "black")
fig.tight_layout()
return ax
# Plot non-normalized confusion matrix
plot_confusion_matrix(y_test, y_pred, classes=['Benign(2)','Malignant(4)'],normalize= False, title='Confusion matrix')
而不是
plot_confusion_matrix(cnf_matrix, classes=['Benign(2)','Malignant(4)'],normalize= False, title='Confusion matrix')
参考:https://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html
matplotlib 版本 3.1.1 和 scikit-plot 之间似乎存在冲突。参考这个 GitHub issue,它显示了类似的问题。
将 matplotlib 降级到版本 3.1.0 可以立即解决。
我正在使用 jupyterlab
,专门渲染混淆矩阵。但是,在渲染矩阵时,似乎有什么不对劲,因为图形没有完全渲染。
我已经安装了sklearn包,但还是一样的问题。我尝试了不同的替代方案,但仍然渲染了一个剪断的混淆矩阵。
下面是我知道会呈现正确混淆矩阵的代码示例。
from sklearn.metrics import classification_report, confusion_matrix
import itertools
import matplotlib.pyplot as plt
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("Normalized confusion matrix")
else:
print('Confusion matrix, without normalization')
print(cm)
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, format(cm[i, j], fmt),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
# Compute confusion matrix
cnf_matrix = confusion_matrix(y_test, yhat, labels=[2,4])
np.set_printoptions(precision=2)
print (classification_report(y_test, yhat))
# Plot non-normalized confusion matrix
plt.figure()
plot_confusion_matrix(cnf_matrix, classes=['Benign(2)','Malignant(4)'],normalize= False, title='Confusion matrix')
从上面的代码中,我得到了这个混淆矩阵:
然而,我希望有一个非剪断的混淆矩阵,例如:
致谢:@Calvin Duy Canh Tran
2019-08-05 更新:
为了不怀疑上面使用的代码,我使用了额外的参考:相反,我尝试了混淆矩阵文档示例之一的代码 scikit-learn
。 link 就是这个 https://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html
在运行上述代码之前,我安装了对应的模块:
pip install -q scikit-plot
不幸的是,输出继续呈现截断的矩阵(见图):
正确的输出应该是这个(忽略方向):
不要将混淆矩阵作为输入参数传递给绘图函数。您需要传递 y_test, y_pred
并且混淆矩阵将在内部计算。
绘制它使用这个:
def plot_confusion_matrix(y_true, y_pred, classes,
normalize=False,
title=None,
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
if not title:
if normalize:
title = 'Normalized confusion matrix'
else:
title = 'Confusion matrix, without normalization'
# Compute confusion matrix
cm = confusion_matrix(y_true, y_pred)
# Only use the labels that appear in the data
classes = classes[unique_labels(y_true, y_pred)]
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("Normalized confusion matrix")
else:
print('Confusion matrix, without normalization')
print(cm)
fig, ax = plt.subplots()
im = ax.imshow(cm, interpolation='nearest', cmap=cmap)
ax.figure.colorbar(im, ax=ax)
# We want to show all ticks...
ax.set(xticks=np.arange(cm.shape[1]),
yticks=np.arange(cm.shape[0]),
# ... and label them with the respective list entries
xticklabels=classes, yticklabels=classes,
title=title,
ylabel='True label',
xlabel='Predicted label')
# Rotate the tick labels and set their alignment.
plt.setp(ax.get_xticklabels(), rotation=45, ha="right",
rotation_mode="anchor")
# Loop over data dimensions and create text annotations.
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.
for i in range(cm.shape[0]):
for j in range(cm.shape[1]):
ax.text(j, i, format(cm[i, j], fmt),
ha="center", va="center",
color="white" if cm[i, j] > thresh else "black")
fig.tight_layout()
return ax
# Plot non-normalized confusion matrix
plot_confusion_matrix(y_test, y_pred, classes=['Benign(2)','Malignant(4)'],normalize= False, title='Confusion matrix')
而不是
plot_confusion_matrix(cnf_matrix, classes=['Benign(2)','Malignant(4)'],normalize= False, title='Confusion matrix')
参考:https://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html
matplotlib 版本 3.1.1 和 scikit-plot 之间似乎存在冲突。参考这个 GitHub issue,它显示了类似的问题。
将 matplotlib 降级到版本 3.1.0 可以立即解决。