首页 > 解决方案 > 如何导出/打印每个观察的分类器详细输出?

问题描述

我使用了 2 个分类器来预测学习者的二进制最终结果(成功或失败):

clfs = [
        GradientBoostingClassifier(n_estimators=100, max_depth=2,random_state=0),
        XGBClassifier(n_estimators=100, max_depth=2,random_state=0)
    ]

下面报告了精度、召回率、f1-score、支持和准确性的最终总体测量值——但我只是想知道如何打印出每个观察结果的 CSV 文件,无论它是否被正确预测(是/否)以及分配的学习者 ID

for clf in clfs:
print('Result of: ',clf)
train_and_cross_validation(clf)

print(rs.score(X_test,y_test))
y_pred = rs.predict(X_test)
report = classification_report(y_test, y_pred)
print(report)
print(confusion_matrix(y_test, y_pred))

标签: pythonmachine-learningclassificationprediction

解决方案


不要打印变量,而是将它们添加到 pandas 数据框,然后将该数据框输出到 .csv 文件。

import pandas as pd

#Create an empty dataframe
df2 = pd.DataFrame({"Report":[0], 
"Confusion_Matrix":[0],
"Report":[0],
"RS_Value":[0],
"CLF":[0]})

for clf in clfs:
    print('Result of: ',clf)
    train_and_cross_validation(clf)

    rs_value = (rs.score(X_test,y_test))
    y_pred = rs.predict(X_test)
    report = classification_report(y_test, y_pred)
    print(report)
    confusion_m = (confusion_matrix(y_test, y_pred))

#Creates a new line for the dataframe from the data we just calculated
    df2 = pd.DataFrame({"Report":[report], 
    "Confusion_Matrix":[confusion_m],
    "RS_Value":[rs_value],
    "CLF":[clf]})

#adds that line onto the original dataframe
    df1 = df1.append(df2)

完成所有循环后,将结果输出到 .csv 文件

df1.to_csv('output.csv')

推荐阅读