File size: 3,887 Bytes
52dd1ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# src/training/train_resnet_pt_svm.py

import os
import argparse
import json

import numpy as np
from sklearn.svm import LinearSVC
from sklearn.metrics import accuracy_score
import joblib


def load_features(features_dir: str):
    x_train_path = os.path.join(features_dir, "X_train_resnet18.npy")
    y_train_path = os.path.join(features_dir, "y_train.npy")
    x_test_path = os.path.join(features_dir, "X_test_resnet18.npy")
    y_test_path = os.path.join(features_dir, "y_test.npy")

    assert os.path.exists(x_train_path), f"Missing: {x_train_path}"
    assert os.path.exists(y_train_path), f"Missing: {y_train_path}"
    assert os.path.exists(x_test_path), f"Missing: {x_test_path}"
    assert os.path.exists(y_test_path), f"Missing: {y_test_path}"

    X_train = np.load(x_train_path)
    y_train = np.load(y_train_path)
    X_test = np.load(x_test_path)
    y_test = np.load(y_test_path)

    return X_train, y_train, X_test, y_test


def main(

    features_dir: str = "data/resnet18_features",

    ckpt_path: str = "checkpoints/resnet_pt_svm_head.joblib",

    labels_path: str = "configs/labels.json",

):
    os.makedirs(os.path.dirname(ckpt_path), exist_ok=True)

    print(f"[+] Loading ResNet18 features from {features_dir} ...")
    X_train, y_train, X_test, y_test = load_features(features_dir)

    print(f"    X_train shape: {X_train.shape}, y_train shape: {y_train.shape}")
    print(f"    X_test shape : {X_test.shape}, y_test shape : {y_test.shape}")

    num_features = X_train.shape[1]
    print(f"[+] Feature dimension: {num_features}")

    # Labels mapping for logging / sanity
    if os.path.exists(labels_path):
        with open(labels_path, "r") as f:
            labels = json.load(f)
        num_classes = len(labels)
        print(f"[+] Loaded labels from {labels_path}, num_classes={num_classes}")
    else:
        print(f"[!] Warning: {labels_path} not found. Inference will need this later.")
        labels = None

    print("[+] Training Linear SVM on ResNet18 features ...")
    svm = LinearSVC(
        C=1.0,
        penalty="l2",
        loss="squared_hinge",
        max_iter=5000,  # give it some room
    )

    svm.fit(X_train, y_train)

    print("[+] Evaluating ...")
    y_pred_train = svm.predict(X_train)
    y_pred_test = svm.predict(X_test)

    train_acc = accuracy_score(y_train, y_pred_train)
    test_acc = accuracy_score(y_test, y_pred_test)

    print(f"    Train accuracy: {train_acc:.4f}")
    print(f"    Test accuracy : {test_acc:.4f}")

    print(f"[+] Saving ResNet PT + SVM head to {ckpt_path} ...")
    payload = {
        "model": svm,
        "backbone": "resnet18_imagenet",
        "feature_dim": int(num_features),
        "labels_path": labels_path,
        "train_acc": float(train_acc),
        "test_acc": float(test_acc),
    }
    joblib.dump(payload, ckpt_path)

    print("[+] Done training ResNet PT + SVM.")


def parse_args():
    parser = argparse.ArgumentParser(
        description="Train Linear SVM head on ResNet18 (pretrained) features."
    )
    parser.add_argument(
        "--features-dir",
        type=str,
        default="data/resnet18_features",
        help="Directory containing X_train_resnet18.npy etc.",
    )
    parser.add_argument(
        "--ckpt-path",
        type=str,
        default="checkpoints/resnet_pt_svm_head.joblib",
        help="Where to save SVM head checkpoint.",
    )
    parser.add_argument(
        "--labels-path",
        type=str,
        default="configs/labels.json",
        help="Path to labels mapping JSON.",
    )

    return parser.parse_args()


if __name__ == "__main__":
    args = parse_args()
    main(
        features_dir=args.features_dir,
        ckpt_path=args.ckpt_path,
        labels_path=args.labels_path,
    )