File size: 1,318 Bytes
1cd0545
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import os
import csv
from typing import Dict, Any


class CSVLogger:
    """
    Ghi log quá trình huấn luyện ra file CSV.
    Dùng để vẽ biểu đồ Loss, Accuracy, Learning Rate trong báo cáo.
    """

    def __init__(self, log_path: str) -> None:
        self.log_path = log_path
        os.makedirs(os.path.dirname(log_path), exist_ok=True)

        self.fieldnames = [
            "epoch",
            "phase",
            "learning_rate",
            "train_loss",
            "train_accuracy",
            "val_loss",
            "val_accuracy",
            "embedding_norm",
            "gradient_norm",
            "train_batches",
            "val_batches",
            "epoch_time_sec",
            "device",
            "gpu_memory_mb",
            "checkpoint_saved"
        ]

        if not os.path.exists(self.log_path):
            with open(self.log_path, "w", newline="", encoding="utf-8") as f:
                writer = csv.DictWriter(f, fieldnames=self.fieldnames)
                writer.writeheader()

    def log(self, row: Dict[str, Any]) -> None:
        """Ghi một dòng kết quả vào file CSV."""
        with open(self.log_path, "a", newline="", encoding="utf-8") as f:
            writer = csv.DictWriter(f, fieldnames=self.fieldnames)
            writer.writerow(row)