user8050075
user8050075

Reputation:

How can I write confusion_matrix and classification_report to txt

I am trying to write to the txt the matrix obtained from the function - sklearn.metrics.confusion_matrix and the statistic from - classification_report

I get the following error - "Expected 1D or 2D array, got %dD array instead" % X.ndim) ValueError: Expected 1D or 2D array, got 0D array instead

Does anyone know how to solve this?

The code is attached with 2 attempts to write to the file - (you can see "Try 1" and "Try 2" in the code)

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)))

Upvotes: 0

Views: 2752

Answers (1)

Yohanes Gultom
Yohanes Gultom

Reputation: 3842

Based on the doc, classification_report returns String while confusion_matrix returns Array, so you should do something like this instead:

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()

Upvotes: 1

Related Questions