Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: how to save a confusion matrix

What i try to do, is saving a confusion matrix, in some kind of text file (probably HTML looks the best). I need to take the data from a csv file, add it into arrays, and then create the confusion matrix. Code:

import csv
import pandas as pd

data = csv.reader(open('results_date.csv', 'r'), delimiter=";", quotechar='|')
next(data)

true_data = []
pred_data = []

for row in data:
    if len(row) >= 2:
        true_data.append(row[0])
        pred_data.append(row[1])

true_data = [s.strip().split('_')[0] for s in true_data]
pred_data = [s.strip().split('=')[0] for s in pred_data]

y_true = pd.Series(true_data, name="Actual")
y_pred = pd.Series(pred_data, name="Predicted")
df_confusion = pd.crosstab(y_true, y_pred)
print (df_confusion)

The confusion matrix looks like this:

Predicted  class1  class2  class3  class4  classX
Actual
class1          5       6       0       4       5
class2          1       0       4       8       0
class3          5       3       2       0       1
class4          4       2       5       2       0
classX          0       5       2       1       7

And i want to output it into some file, under the same form (my guess is that it would look better as a HTML or CSV file, but anything would do - please, not crazy formats that you need special programs for).

like image 929
David Botezatu Avatar asked Mar 29 '26 23:03

David Botezatu


2 Answers

df_confusion.to_csv('your_output_file_name.csv')
df_confusion.to_html('your_output_file_name.html')

check the documentation for full details and parameters:

http://pandas.pydata.org/pandas-docs/version/0.20.3/generated/pandas.DataFrame.to_csv.html

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_html.html

also, a search would have answered it very fast, please do that in future.

like image 194
Zulfiqaar Avatar answered Apr 02 '26 11:04

Zulfiqaar


You can simply do: df_confusion.to_csv('File_name.csv')

like image 43
quest Avatar answered Apr 02 '26 11:04

quest



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!