如何获取一个混淆矩阵,其中绘制了修改后的输出大小和输出为python中的.svg图像



我想绘制一个混淆矩阵,因为我有两个矩阵,即y_test_和y_pred。我希望输出图像为" .svg"。正如我必须将图像放在项目报告中,我希望它的尺寸可修改。我希望能够按照我的纸张来修改图像大小。

我已经尝试了" sklearn.metrics"的" Confusion_Matrix"功能。但是输出图像比我需要的太小。此外,图像以" .png"格式。我使用的代码在下面给出。

from sklearn.metrics import confusion_matrix
def plot_confusion_matrix(y_true, y_pred, classes, normalize=False, title=None, cmap=plt.cm.Blues):
    if not title:
        if normalize:
            title = 'Normalized confusion matrix'
        else:
            title = 'Confusion matrix, without normalization'
    cm = confusion_matrix(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)
    ax.set(xticks=np.arange(cm.shape[1]), yticks=np.arange(cm.shape[0]), xticklabels=classes, yticklabels=classes, title=title, 
           ylabel='True label',
           xlabel='Predicted label')
    plt.setp(ax.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor")
    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_confusion_matrix(y_test_, y_pred, classes=class_names, title='Confusion matrix, without normalization')
plot_confusion_matrix(y_test_, y_pred, classes=class_names, normalize=True, title='Normalized confusion matrix')
plt.show()

此代码生成的图像尚不清楚地放在纸上,而不是以" .svg"形式。建议我该怎么做。

对于清除输出

您尚未提供完整的代码,但我认为,如果您使用的是Seaborn,则可以使用sns.set()如下

import matplotlib.pyplot as plt
import seaborn as sn
sn.set()
%matplotlib inline

在调用plt.show()

之前将文件保存为.svg使用
plt.savefig("test.svg", format="svg")

plt.savefig("test.svg")

最新更新