main.py 6.18 KB
Newer Older
1
import argparse
2

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3
4
import dgl

5
6
import torch as th
import torch.optim as optim
7
from model import CAREGNN
8
from sklearn.metrics import recall_score, roc_auc_score
9
from torch.nn.functional import softmax
10
11
from utils import EarlyStopping

12
13
14
15
16
17
18
19
20
21

def main(args):
    # Step 1: Prepare graph data and retrieve train/validation/test index ============================= #
    # Load dataset
    dataset = dgl.data.FraudDataset(args.dataset, train_size=0.4)
    graph = dataset[0]
    num_classes = dataset.num_classes

    # check cuda
    if args.gpu >= 0 and th.cuda.is_available():
22
        device = "cuda:{}".format(args.gpu)
23
    else:
24
        device = "cpu"
25
26

    # retrieve labels of ground truth
27
    labels = graph.ndata["label"].to(device)
28
29

    # Extract node features
30
    feat = graph.ndata["feature"].to(device)
31
32

    # retrieve masks for train/validation/test
33
34
35
    train_mask = graph.ndata["train_mask"]
    val_mask = graph.ndata["val_mask"]
    test_mask = graph.ndata["test_mask"]
36
37
38
39
40
41

    train_idx = th.nonzero(train_mask, as_tuple=False).squeeze(1).to(device)
    val_idx = th.nonzero(val_mask, as_tuple=False).squeeze(1).to(device)
    test_idx = th.nonzero(test_mask, as_tuple=False).squeeze(1).to(device)

    # Reinforcement learning module only for positive training nodes
42
43
44
    rl_idx = th.nonzero(
        train_mask.to(device) & labels.bool(), as_tuple=False
    ).squeeze(1)
45
46
47
48

    graph = graph.to(device)

    # Step 2: Create model =================================================================== #
49
50
51
52
53
54
55
56
57
    model = CAREGNN(
        in_dim=feat.shape[-1],
        num_classes=num_classes,
        hid_dim=args.hid_dim,
        num_layers=args.num_layers,
        activation=th.tanh,
        step_size=args.step_size,
        edges=graph.canonical_etypes,
    )
58
59
60
61
62
63

    model = model.to(device)

    # Step 3: Create training components ===================================================== #
    _, cnt = th.unique(labels, return_counts=True)
    loss_fn = th.nn.CrossEntropyLoss(weight=1 / cnt)
64
65
66
    optimizer = optim.Adam(
        model.parameters(), lr=args.lr, weight_decay=args.weight_decay
    )
67
68
69
70
71
72
73
74
75
76
    if args.early_stop:
        stopper = EarlyStopping(patience=100)

    # Step 4: training epochs =============================================================== #
    for epoch in range(args.max_epoch):
        # Training and validation using a full graph
        model.train()
        logits_gnn, logits_sim = model(graph, feat)

        # compute loss
77
78
79
80
81
82
83
84
85
86
87
88
        tr_loss = loss_fn(
            logits_gnn[train_idx], labels[train_idx]
        ) + args.sim_weight * loss_fn(logits_sim[train_idx], labels[train_idx])

        tr_recall = recall_score(
            labels[train_idx].cpu(),
            logits_gnn.data[train_idx].argmax(dim=1).cpu(),
        )
        tr_auc = roc_auc_score(
            labels[train_idx].cpu(),
            softmax(logits_gnn, dim=1).data[train_idx][:, 1].cpu(),
        )
89
90

        # validation
91
92
93
94
95
96
97
98
99
100
        val_loss = loss_fn(
            logits_gnn[val_idx], labels[val_idx]
        ) + args.sim_weight * loss_fn(logits_sim[val_idx], labels[val_idx])
        val_recall = recall_score(
            labels[val_idx].cpu(), logits_gnn.data[val_idx].argmax(dim=1).cpu()
        )
        val_auc = roc_auc_score(
            labels[val_idx].cpu(),
            softmax(logits_gnn, dim=1).data[val_idx][:, 1].cpu(),
        )
101
102
103
104
105
106
107

        # backward
        optimizer.zero_grad()
        tr_loss.backward()
        optimizer.step()

        # Print out performance
108
109
110
111
112
113
114
115
116
117
118
        print(
            "Epoch {}, Train: Recall: {:.4f} AUC: {:.4f} Loss: {:.4f} | Val: Recall: {:.4f} AUC: {:.4f} Loss: {:.4f}".format(
                epoch,
                tr_recall,
                tr_auc,
                tr_loss.item(),
                val_recall,
                val_auc,
                val_loss.item(),
            )
        )
119
120
121
122
123
124
125
126
127
128
129

        # Adjust p value with reinforcement learning module
        model.RLModule(graph, epoch, rl_idx)

        if args.early_stop:
            if stopper.step(val_auc, model):
                break

    # Test after all epoch
    model.eval()
    if args.early_stop:
130
        model.load_state_dict(th.load("es_checkpoint.pt"))
131
132
133
134
135

    # forward
    logits_gnn, logits_sim = model.forward(graph, feat)

    # compute loss
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
    test_loss = loss_fn(
        logits_gnn[test_idx], labels[test_idx]
    ) + args.sim_weight * loss_fn(logits_sim[test_idx], labels[test_idx])
    test_recall = recall_score(
        labels[test_idx].cpu(), logits_gnn[test_idx].argmax(dim=1).cpu()
    )
    test_auc = roc_auc_score(
        labels[test_idx].cpu(),
        softmax(logits_gnn, dim=1).data[test_idx][:, 1].cpu(),
    )

    print(
        "Test Recall: {:.4f} AUC: {:.4f} Loss: {:.4f}".format(
            test_recall, test_auc, test_loss.item()
        )
    )


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="GCN-based Anti-Spam Model")
    parser.add_argument(
        "--dataset",
        type=str,
        default="amazon",
        help="DGL dataset for this model (yelp, or amazon)",
    )
    parser.add_argument(
        "--gpu", type=int, default=-1, help="GPU index. Default: -1, using CPU."
    )
    parser.add_argument(
        "--hid_dim", type=int, default=64, help="Hidden layer dimension"
    )
    parser.add_argument(
        "--num_layers", type=int, default=1, help="Number of layers"
    )
    parser.add_argument(
        "--max_epoch",
        type=int,
        default=30,
        help="The max number of epochs. Default: 30",
    )
    parser.add_argument(
        "--lr", type=float, default=0.01, help="Learning rate. Default: 0.01"
    )
    parser.add_argument(
        "--weight_decay",
        type=float,
        default=0.001,
        help="Weight decay. Default: 0.001",
    )
    parser.add_argument(
        "--step_size",
        type=float,
        default=0.02,
        help="RL action step size (lambda 2). Default: 0.02",
    )
    parser.add_argument(
        "--sim_weight",
        type=float,
        default=2,
        help="Similarity loss weight (lambda 1). Default: 2",
    )
    parser.add_argument(
        "--early-stop",
        action="store_true",
        default=False,
        help="indicates whether to use early stop",
    )
204
205
206
207
208

    args = parser.parse_args()
    print(args)
    th.manual_seed(717)
    main(args)