【问题标题】:Save classification report & confusion matrix of for loop into csv file将for循环的分类报告和混淆矩阵保存到csv文件中
【发布时间】:2022-09-28 15:32:50
【问题描述】:

我的 CSV 文件中需要有 10 个结果,但它只显示一个。我查看了一些发布的问题,它说可能是我之前的迭代被覆盖了。

我应该如何编辑我的代码以在我的 CSV 文件中获得 10 次重复?

for x in range (10):
    from sklearn.metrics import classification_report
    report = classification_report(Y_test, Y_pred, output_dict=True)
    CR = pd.DataFrame(report).transpose()
    CR.to_csv(\'LR_CR.csv\')

    from sklearn.metrics import confusion_matrix
    matrix = confusion_matrix(Y_test, Y_pred)
    CM = pd.DataFrame(matrix).transpose()
    CM.to_csv(\'LR_CM.csv\')


Output
              precision    recall  f1-score    support
0              0.421053  0.444444  0.432432  18.000000
1              0.777778  0.760870  0.769231  46.000000
accuracy       0.671875  0.671875  0.671875   0.671875
macro avg      0.599415  0.602657  0.600832  64.000000
weighted avg   0.677449  0.671875  0.674506  64.000000

    0   1
0   8  14
1  10  32    

             precision    recall  f1-score  support
0              0.625000  0.277778  0.384615    18.00
1              0.767857  0.934783  0.843137    46.00
accuracy       0.750000  0.750000  0.750000     0.75
macro avg      0.696429  0.606280  0.613876    64.00
weighted avg   0.727679  0.750000  0.714178    64.00

    0   1
0   5   3
1  13  43

    标签: python-3.x for-loop export-to-csv


    【解决方案1】:

    这里发生的是您在循环的每次迭代中都覆盖了您的 CSV 文件。 如果您想拥有 10 个单独的 CSV 文件,则需要以不同的方式命名每个文件,这可以通过使用 f-strings 来实现

    for i in range(10):
        pd.to_csv(f'some_name_{i}.csv')
    

    或者,如果您需要单个 CSV 文件中的所有结果,则只需附加到现有文件

    df.to_csv('existing.csv', mode='a', index=False, header=False)```
    

    【讨论】:

      猜你喜欢
      • 2020-08-21
      • 2019-07-26
      • 2019-05-26
      • 2020-04-11
      • 2021-07-29
      • 2021-07-29
      • 2022-10-20
      • 1970-01-01
      • 2015-08-25
      相关资源
      最近更新 更多