"tutorials/vscode:/vscode.git/clone" did not exist on "3e43d7b8d203df1f2e2e2f0b5c029dfebeec549b"
eval_function.py 5.61 KB
Newer Older
1
import numpy as np
2
import torch
3
4
from sklearn import metrics
from sklearn.linear_model import LogisticRegression
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
5
from sklearn.model_selection import GridSearchCV, ShuffleSplit, train_test_split
6
from sklearn.multiclass import OneVsRestClassifier
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
7
from sklearn.preprocessing import normalize, OneHotEncoder
8
9
10
11


def fit_logistic_regression(X, y, data_random_seed=1, repeat=1):
    # transform targets to one-hot vector
12
    one_hot_encoder = OneHotEncoder(categories="auto", sparse=False)
13
14
15
16

    y = one_hot_encoder.fit_transform(y.reshape(-1, 1)).astype(np.bool)

    # normalize x
17
    X = normalize(X, norm="l2")
18
19
20
21
22
23
24

    # set random state, this will ensure the dataset will be split exactly the same throughout training
    rng = np.random.RandomState(data_random_seed)

    accuracies = []
    for _ in range(repeat):
        # different random split after each repeat
25
26
27
        X_train, X_test, y_train, y_test = train_test_split(
            X, y, test_size=0.8, random_state=rng
        )
28
29

        # grid search with one-vs-rest classifiers
30
        logreg = LogisticRegression(solver="liblinear")
31
32
        c = 2.0 ** np.arange(-10, 11)
        cv = ShuffleSplit(n_splits=5, test_size=0.5)
33
34
35
36
37
38
39
        clf = GridSearchCV(
            estimator=OneVsRestClassifier(logreg),
            param_grid=dict(estimator__C=c),
            n_jobs=5,
            cv=cv,
            verbose=0,
        )
40
41
42
43
        clf.fit(X_train, y_train)

        y_pred = clf.predict_proba(X_test)
        y_pred = np.argmax(y_pred, axis=1)
44
45
46
        y_pred = one_hot_encoder.transform(y_pred.reshape(-1, 1)).astype(
            np.bool
        )
47
48
49
50
51
52

        test_acc = metrics.accuracy_score(y_test, y_pred)
        accuracies.append(test_acc)
    return accuracies


53
54
55
def fit_logistic_regression_preset_splits(
    X, y, train_mask, val_mask, test_mask
):
56
    # transform targets to one-hot vector
57
    one_hot_encoder = OneHotEncoder(categories="auto", sparse=False)
58
59
60
    y = one_hot_encoder.fit_transform(y.reshape(-1, 1)).astype(np.bool)

    # normalize x
61
    X = normalize(X, norm="l2")
62
63
64
65

    accuracies = []
    for split_id in range(train_mask.shape[1]):
        # get train/val/test masks
66
67
68
69
        tmp_train_mask, tmp_val_mask = (
            train_mask[:, split_id],
            val_mask[:, split_id],
        )
70
71
72
73
74
75
76
77
78

        # make custom cv
        X_train, y_train = X[tmp_train_mask], y[tmp_train_mask]
        X_val, y_val = X[tmp_val_mask], y[tmp_val_mask]
        X_test, y_test = X[test_mask], y[test_mask]

        # grid search with one-vs-rest classifiers
        best_test_acc, best_acc = 0, 0
        for c in 2.0 ** np.arange(-10, 11):
79
80
81
            clf = OneVsRestClassifier(
                LogisticRegression(solver="liblinear", C=c)
            )
82
83
84
85
            clf.fit(X_train, y_train)

            y_pred = clf.predict_proba(X_val)
            y_pred = np.argmax(y_pred, axis=1)
86
87
88
            y_pred = one_hot_encoder.transform(y_pred.reshape(-1, 1)).astype(
                np.bool
            )
89
90
91
92
93
            val_acc = metrics.accuracy_score(y_val, y_pred)
            if val_acc > best_acc:
                best_acc = val_acc
                y_pred = clf.predict_proba(X_test)
                y_pred = np.argmax(y_pred, axis=1)
94
95
96
                y_pred = one_hot_encoder.transform(
                    y_pred.reshape(-1, 1)
                ).astype(np.bool)
97
98
99
100
101
102
                best_test_acc = metrics.accuracy_score(y_test, y_pred)

        accuracies.append(best_test_acc)
    return accuracies


103
104
105
def fit_ppi_linear(
    num_classes, train_data, val_data, test_data, device, repeat=1
):
106
    r"""
107
108
109
    Trains a linear layer on top of the representations. This function is specific to the PPI dataset,
    which has multiple labels.
    """
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135

    def train(classifier, train_data, optimizer):
        classifier.train()

        x, label = train_data
        x, label = x.to(device), label.to(device)
        for step in range(100):
            # forward
            optimizer.zero_grad()
            pred_logits = classifier(x)

            # loss and backprop
            loss = criterion(pred_logits, label)
            loss.backward()
            optimizer.step()

    def test(classifier, data):
        classifier.eval()
        x, label = data
        label = label.cpu().numpy().squeeze()

        # feed to network and classifier
        with torch.no_grad():
            pred_logits = classifier(x.to(device))
            pred_class = (pred_logits > 0).float().cpu().numpy()

136
137
138
139
140
        return (
            metrics.f1_score(label, pred_class, average="micro")
            if pred_class.sum() > 0
            else 0
        )
141
142
143
144
145

    num_feats = train_data[0].size(1)
    criterion = torch.nn.BCEWithLogitsLoss()

    # normalization
146
147
148
    mean, std = train_data[0].mean(0, keepdim=True), train_data[0].std(
        0, unbiased=False, keepdim=True
    )
149
150
151
152
153
154
155
156
157
158
159
    train_data[0] = (train_data[0] - mean) / std
    val_data[0] = (val_data[0] - mean) / std
    test_data[0] = (test_data[0] - mean) / std

    best_val_f1 = []
    test_f1 = []
    for _ in range(repeat):
        tmp_best_val_f1 = 0
        tmp_test_f1 = 0
        for weight_decay in 2.0 ** np.arange(-10, 11, 2):
            classifier = torch.nn.Linear(num_feats, num_classes).to(device)
160
161
162
163
164
            optimizer = torch.optim.AdamW(
                params=classifier.parameters(),
                lr=0.01,
                weight_decay=weight_decay,
            )
165
166
167
168
169
170
171
172
173
174

            train(classifier, train_data, optimizer)
            val_f1 = test(classifier, val_data)
            if val_f1 > tmp_best_val_f1:
                tmp_best_val_f1 = val_f1
                tmp_test_f1 = test(classifier, test_data)
        best_val_f1.append(tmp_best_val_f1)
        test_f1.append(tmp_test_f1)

    return [best_val_f1], [test_f1]