如何将confusion_matrix和category_report写入txt

时间:2018-08-12 09:28:25

标签: python numpy scikit-learn

我试图将从函数获得的矩阵写入txt-sklearn.metrics.confusion_matrix 以及来自-category_report

的统计信息

我收到以下错误-  “预期的1D或2D数组,取而代之的是%dD数组”%X.ndim) ValueError:预期为1D或2D数组,取而代之的是0D数组

有人知道如何解决吗?

该代码附带两次尝试写入文件的尝试- (您可以在代码中看到“ Try 1”和“ Try 2”)

def main():

    train_images, train_labels, test_images, test_labels = importData.load_data(data_address = 'D:/Python Projects/MNIST_With_Moments/mnist_data')
    classifier = train_svm_model.train_model_RBF_kernel(num_train=5000, images=train_images, tag=train_labels, gamma_value=2,
                                                        num_iteretion=-1, c_value=50, log_transform=True, RAM_size=8000)
    prediction, labels = predict_svm_model.predict(clf=classifier, num_test=100, images=test_images, tag=test_labels)

    target_names = ['class 0', 'class 1', 'class 2', 'class 3', 'class 4', 'class 5', 'class 6', 'class 7', 'class 8','class 9']
    print()

    print("SVM with HuMoment only on MNIST data -\nClassification report for classifier %s:\n\n%s\n"
          % (classifier, classification_report(y_true=labels, y_pred=prediction, target_names=target_names, digits=3)))
    print("Confusion matrix: \neach row of the matrix represents the instances in a predicted class \n"
          "end each column represents the instances in an actual class. \n"
          "\n%s" % sklearn.metrics.confusion_matrix(labels, prediction))

    """
    try 1 -
    """
    np.savetxt("pred.txt","SVM with HuMoment only on MNIST data -\nClassification report for classifier %s:\n\n%s\n"
          % (classifier, classification_report(y_true=labels, y_pred=prediction, target_names=target_names, digits=3))
         +"Confusion matrix: \neach row of the matrix represents the instances in a predicted class \n"
          "end each column represents the instances in an actual class. \n"
          "\n%s" % sklearn.metrics.confusion_matrix(labels, prediction))

    """
    try 2 -
    """

    clf_rep = sklearn.metrics.precision_recall_fscore_support(labels, prediction)
    out_dict = {
        "precision": clf_rep[0].round(2)
        , "recall": clf_rep[1].round(2)
        , "f1-score": clf_rep[2].round(2)
        , "support": clf_rep[3]
    }
    out_df = pd.DataFrame(out_dict)
    avg_tot = (out_df.apply(lambda x: round(x.mean(), 2) if x.name!="support" else  round(x.sum(), 2)).to_frame().T)
    avg_tot.index = ["avg/total"]
    out_df = out_df.append(avg_tot)
    np.savetxt("pred.txt","SVM with HuMoment only on MNIST data -\nClassification report for classifier %s:\n\n%s\n"
          % (classifier,np.array(out_df)))

1 个答案:

答案 0 :(得分:0)

根据文档,classification_report返回String,而confusion_matrix返回Array,因此您应该执行以下操作:

import numpy as np
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix

y_true = [0, 1, 2, 2, 2]
y_pred = [0, 0, 2, 2, 1]
target_names = ['class 0', 'class 1', 'class 2']

cr = classification_report(y_true, y_pred, target_names=target_names)
cm = np.array2string(confusion_matrix(y_true, y_pred))
f = open('report.txt', 'w')
f.write('Title\n\nClassification Report\n\n{}\n\nConfusion Matrix\n\n{}\n'.format(cr, cm))
f.close()