0

在我的 ML 模型中(请参考下面的代码),我想做以下事情:

  1. 导出classification_report和混淆矩阵cm作为.xlsx文件(两个单独的 Excel 文件表)

  2. 导出classification_report和混淆矩阵cm_plot 作为一个.pdf文件(都在同一页面上)

我的尝试:

#libraries
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from xgboost import XGBClassifier
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix

#import data
data = 'https://gist.githubusercontent.com/curran/a08a1080b88344b0c8a7/raw/0e7a9b0a5d22642a06d3d5b9bcbad9890c8ee534/iris.csv'
df=pd.read_csv(data, delimiter=",")
target = 'species'

X = df.loc[:,df.columns!= target] 
y = df.loc[:,df.columns== target]

# split into train and test sets

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=139806)

# train classifier and predict on test set 
model = XGBClassifier()
model.fit(X_train,y_train)
y_pred = model.predict(X_test)
reports = classification_report(y_test,y_pred)
cm =confusion_matrix(y_test, y_pred)
#################################################################################
# desire output 1: Export "reports" and "cm_plot" as .xlsx file 
outputdata = r'C:\Users\myname\Desktop\Demo\outfiles.xlsx'
writer = pd.ExcelWriter(output_data, engine='xlsxwriter')
reports.to_excel(writer,sheet_name='class_report')
cm.to_excel(writer,sheet_name ='confusionMatrix')

# desire output 2: Export "reports" and "cm_plot" as .pdf file (same page)
reports.to_pdf('reports.pdf')
cm_plot = sns.heatmap(cm, annot=True)
plt.show()

cm_plot.to_pdf('reports.pdf')

所需的输出(用于 pdf)应如下所示:

在此处输入图像描述

提前致谢

4

0 回答 0