Stomach_Cancer_Pytorch/.trae/documents/修改 ModifiedResNet 以使用 ResNet50 並將分類輸出改為 3.md

3.7 KiB
Raw Permalink Blame History

變更目標

  • 在整體流程中加入兩項功能:

    1. 產生「模型預測類別分佈」的統計直方圖Bar Chart並保存為圖片
    2. 將模型對每張圖的預測類別(含信心值)以 CSV 格式逐圖存檔

介面與插入點

  • 主流程:main.py 目前在 110 行呼叫 Crop_Result(...) 完成資料前處理後,交由 experiments/experiment.py:62 內的 processing_main() 進行模型訓練與測試

  • 最適合記錄預測與產生統計圖的插入點:experiments/Training/Xception_Identification_Test.py

    • 測試評估:Evaluate_Model(...)(第 317360 行)遍歷 Test_Dataloader,可取得 images, labels, File_Name, File_Classes 與模型輸出

    • 逐批結果彙整:Evaluate_Per_Class_Metrics(...)(第 362434 行),可加入總結圖表的產出

具體修改

1. 逐圖分類記錄CSV

  • Evaluate_Model(...) 內:

    • with torch.no_grad() 迴圈中保留 File_Name,取得模型 outputs,計算 softmax 機率與 argmax 類別

    • 收集為清單:rows.append({file_path, true_label_idx, pred_label_idx, prob_per_class...})

    • 迴圈結束後寫出 CSV../Result/Prediction_Logs/Label_Result/<date>/<experiment_name>/fold-<k>/predictions.csv

    • 欄位:file_path, true_label, pred_label, conf_class_0, conf_class_1, conf_class_2

2. 預測分佈統計直方圖

  • Evaluate_Model(...) 完成 CSV 後:

    • 根據 pred_label_idx 計數,生成 Bar Chartx 軸為 Training_Labelsy 軸為數量)

    • 圖檔輸出:../Result/Prediction_Logs/Bar_Chat/<date>/<experiment_name>/fold-<k>/prediction_histogram.png

  • 可選:新增「各類別信心值分佈」直方圖(每類一張),路徑:..Result/conf_Hist/<date>/<experiment_name>/fold-<k>/conf_hist_class_<name>.png

3. 設定保存路徑

  • 使用現有 Save_Result_File_Config 結構,不需修改常數:

    • 在程式中以相對路徑 ../Result/Prediction_Logs/... 建立目錄(透過 Process_File.JudgeRoot_MakeDir

    • 目錄結構:../Result/Prediction_Logs/<date>/<experiment_name>/fold-<k>/

4. 程式設計細節

  • 新增工具函式(置於 Xception_Identification_Test.py 底部或 Training_Tools/Tools.py

    • save_predictions_csv(rows, save_dir):負責寫出 CSV

    • plot_prediction_histogram(pred_indices, class_names, save_path):使用 matplotlib 畫 Bar Chart

  • 修改 Evaluate_Model(...)

    • 保留 File_Name;將 outputstorch.softmax(outputs, dim=1) 取得機率

    • 記錄 predicted_idxprobabilities.tolist()

    • 呼叫新增工具函式保存 CSV 與直方圖

5. 主程式連動(可選)

  • main.py

    • 保持現狀,不需改動;所有記錄與圖表由 Evaluate_Model(...) 執行時自動生成

    • 若需在訓練完成後總覽全部折次結果,可於 experiments/experiment.py:151 之後新增彙總函式,合併多折 predictions.csv 生成總分佈圖

6. 輸出成果

  • 檔案:

    • ../Result/Prediction_Logs/Label_Result/<date>/<experiment_name>/fold-<k>/predictions.csv

    • ../Result/Prediction_Logs/Bar_Chat/<date>/<experiment_name>/fold-<k>/prediction_histogram.png

    • (可選)../Result/Prediction_Logs/Bar_Chat/<date>/<experiment_name>/fold-<k>/prediction_histogram.png

驗證與回溯

  • 驗證:執行既有流程,檢查 Prediction_Logs 目錄是否產生 CSV 與直方圖

  • 影響範圍小:僅在測試評估階段新增 I/O對訓練流程無副作用

  • 回溯:如需停用,移除或關閉保存函式即可

風險與注意事項

  • 測試資料量大時 CSV 會較長;可分折保存或分批 Flush

  • 若需記錄 Top-3可同時保存 topk_indicestopk_probs,目前先保存 Top-1 + 全類機率