main.py 10.6 KB
Newer Older
KounianhuaDu's avatar
KounianhuaDu committed
1
import argparse
2
3
4
from time import time

import numpy as np
KounianhuaDu's avatar
KounianhuaDu committed
5
import torch as th
6
7
8
import torch.optim as optim
from data_loader import Data
from models import CompGCN_ConvE
KounianhuaDu's avatar
KounianhuaDu committed
9
10
11
from utils import in_out_norm


12
13
# predict the tail for (head, rel, -1) or head for (-1, rel, tail)
def predict(model, graph, device, data_iter, split="valid", mode="tail"):
KounianhuaDu's avatar
KounianhuaDu committed
14
15
16
    model.eval()
    with th.no_grad():
        results = {}
17
18
        train_iter = iter(data_iter["{}_{}".format(split, mode)])

KounianhuaDu's avatar
KounianhuaDu committed
19
20
        for step, batch in enumerate(train_iter):
            triple, label = batch[0].to(device), batch[1].to(device)
21
22
23
24
25
26
            sub, rel, obj, label = (
                triple[:, 0],
                triple[:, 1],
                triple[:, 2],
                label,
            )
KounianhuaDu's avatar
KounianhuaDu committed
27
            pred = model(graph, sub, rel)
28
            b_range = th.arange(pred.size()[0], device=device)
KounianhuaDu's avatar
KounianhuaDu committed
29
            target_pred = pred[b_range, obj]
30
            pred = th.where(label.bool(), -th.ones_like(pred) * 10000000, pred)
KounianhuaDu's avatar
KounianhuaDu committed
31
32
            pred[b_range, obj] = target_pred

33
34
35
36
37
38
39
40
41
            # compute metrics
            ranks = (
                1
                + th.argsort(
                    th.argsort(pred, dim=1, descending=True),
                    dim=1,
                    descending=False,
                )[b_range, obj]
            )
KounianhuaDu's avatar
KounianhuaDu committed
42
            ranks = ranks.float()
43
44
45
46
47
48
49
50
51
52
            results["count"] = th.numel(ranks) + results.get("count", 0.0)
            results["mr"] = th.sum(ranks).item() + results.get("mr", 0.0)
            results["mrr"] = th.sum(1.0 / ranks).item() + results.get(
                "mrr", 0.0
            )
            for k in [1, 3, 10]:
                results["hits@{}".format(k)] = th.numel(
                    ranks[ranks <= (k)]
                ) + results.get("hits@{}".format(k), 0.0)

KounianhuaDu's avatar
KounianhuaDu committed
53
54
    return results

55
56
57
58
59
60

# evaluation function, evaluate the head and tail prediction and then combine the results
def evaluate(model, graph, device, data_iter, split="valid"):
    # predict for head and tail
    left_results = predict(model, graph, device, data_iter, split, mode="tail")
    right_results = predict(model, graph, device, data_iter, split, mode="head")
KounianhuaDu's avatar
KounianhuaDu committed
61
    results = {}
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
    count = float(left_results["count"])

    # combine the head and tail prediction results
    # Metrics: MRR, MR, and Hit@k
    results["left_mr"] = round(left_results["mr"] / count, 5)
    results["left_mrr"] = round(left_results["mrr"] / count, 5)
    results["right_mr"] = round(right_results["mr"] / count, 5)
    results["right_mrr"] = round(right_results["mrr"] / count, 5)
    results["mr"] = round(
        (left_results["mr"] + right_results["mr"]) / (2 * count), 5
    )
    results["mrr"] = round(
        (left_results["mrr"] + right_results["mrr"]) / (2 * count), 5
    )
    for k in [1, 3, 10]:
        results["left_hits@{}".format(k)] = round(
            left_results["hits@{}".format(k)] / count, 5
        )
        results["right_hits@{}".format(k)] = round(
            right_results["hits@{}".format(k)] / count, 5
        )
        results["hits@{}".format(k)] = round(
            (
                left_results["hits@{}".format(k)]
                + right_results["hits@{}".format(k)]
            )
            / (2 * count),
            5,
        )
    return results

KounianhuaDu's avatar
KounianhuaDu committed
93
94
95
96
97

def main(args):
    # Step 1: Prepare graph data and retrieve train/validation/test index ============================= #
    # check cuda
    if args.gpu >= 0 and th.cuda.is_available():
98
        device = "cuda:{}".format(args.gpu)
KounianhuaDu's avatar
KounianhuaDu committed
99
    else:
100
101
102
103
104
105
106
        device = "cpu"

    # construct graph, split in/out edges and prepare train/validation/test data_loader
    data = Data(
        args.dataset, args.lbl_smooth, args.num_workers, args.batch_size
    )
    data_iter = data.data_iter  # train/validation/test data_loader
KounianhuaDu's avatar
KounianhuaDu committed
107
    graph = data.g.to(device)
108
    num_rel = th.max(graph.edata["etype"]).item() + 1
KounianhuaDu's avatar
KounianhuaDu committed
109

110
    # Compute in/out edge norms and store in edata
KounianhuaDu's avatar
KounianhuaDu committed
111
112
113
    graph = in_out_norm(graph)

    # Step 2: Create model =================================================================== #
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
    compgcn_model = CompGCN_ConvE(
        num_bases=args.num_bases,
        num_rel=num_rel,
        num_ent=graph.num_nodes(),
        in_dim=args.init_dim,
        layer_size=args.layer_size,
        comp_fn=args.opn,
        batchnorm=True,
        dropout=args.dropout,
        layer_dropout=args.layer_dropout,
        num_filt=args.num_filt,
        hid_drop=args.hid_drop,
        feat_drop=args.feat_drop,
        ker_sz=args.ker_sz,
        k_w=args.k_w,
        k_h=args.k_h,
    )
KounianhuaDu's avatar
KounianhuaDu committed
131
132
133
134
    compgcn_model = compgcn_model.to(device)

    # Step 3: Create training components ===================================================== #
    loss_fn = th.nn.BCELoss()
135
136
137
138
    optimizer = optim.Adam(
        compgcn_model.parameters(), lr=args.lr, weight_decay=args.l2
    )

KounianhuaDu's avatar
KounianhuaDu committed
139
140
141
142
143
144
    # Step 4: training epoches =============================================================== #
    best_mrr = 0.0
    kill_cnt = 0
    for epoch in range(args.max_epochs):
        # Training and validation using a full graph
        compgcn_model.train()
145
        train_loss = []
KounianhuaDu's avatar
KounianhuaDu committed
146
        t0 = time()
147
        for step, batch in enumerate(data_iter["train"]):
KounianhuaDu's avatar
KounianhuaDu committed
148
            triple, label = batch[0].to(device), batch[1].to(device)
149
150
151
152
153
154
            sub, rel, obj, label = (
                triple[:, 0],
                triple[:, 1],
                triple[:, 2],
                label,
            )
KounianhuaDu's avatar
KounianhuaDu committed
155
            logits = compgcn_model(graph, sub, rel)
156

KounianhuaDu's avatar
KounianhuaDu committed
157
158
            # compute loss
            tr_loss = loss_fn(logits, label)
nxznm's avatar
nxznm committed
159
            train_loss.append(tr_loss.item())
KounianhuaDu's avatar
KounianhuaDu committed
160
161
162
163
164
165
166
167

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

        train_loss = np.sum(train_loss)

168
169
170
171
        t1 = time()
        val_results = evaluate(
            compgcn_model, graph, device, data_iter, split="valid"
        )
KounianhuaDu's avatar
KounianhuaDu committed
172
173
        t2 = time()

174
175
176
177
178
179
        # validate
        if val_results["mrr"] > best_mrr:
            best_mrr = val_results["mrr"]
            th.save(
                compgcn_model.state_dict(), "comp_link" + "_" + args.dataset
            )
KounianhuaDu's avatar
KounianhuaDu committed
180
181
182
183
            kill_cnt = 0
            print("saving model...")
        else:
            kill_cnt += 1
nxznm's avatar
nxznm committed
184
            if kill_cnt > 100:
185
                print("early stop.")
KounianhuaDu's avatar
KounianhuaDu committed
186
                break
187
        print(
188
            "In epoch {}, Train Loss: {:.4f}, Valid MRR: {:.5}, Train time: {}, Valid time: {}".format(
189
190
191
192
193
                epoch, train_loss, val_results["mrr"], t1 - t0, t2 - t1
            )
        )

    # test use the best model
KounianhuaDu's avatar
KounianhuaDu committed
194
    compgcn_model.eval()
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
    compgcn_model.load_state_dict(th.load("comp_link" + "_" + args.dataset))
    test_results = evaluate(
        compgcn_model, graph, device, data_iter, split="test"
    )
    print(
        "Test MRR: {:.5}\n, MR: {:.10}\n, H@10: {:.5}\n, H@3: {:.5}\n, H@1: {:.5}\n".format(
            test_results["mrr"],
            test_results["mr"],
            test_results["hits@10"],
            test_results["hits@3"],
            test_results["hits@1"],
        )
    )


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Parser For Arguments",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )

    parser.add_argument(
        "--data",
        dest="dataset",
        default="FB15k-237",
        help="Dataset to use, default: FB15k-237",
    )
    parser.add_argument(
        "--model", dest="model", default="compgcn", help="Model Name"
    )
    parser.add_argument(
        "--score_func",
        dest="score_func",
        default="conve",
        help="Score Function for Link prediction",
    )
    parser.add_argument(
        "--opn",
        dest="opn",
        default="ccorr",
        help="Composition Operation to be used in CompGCN",
    )

    parser.add_argument(
        "--batch", dest="batch_size", default=1024, type=int, help="Batch size"
    )
    parser.add_argument(
        "--gpu",
        type=int,
        default="0",
        help="Set GPU Ids : Eg: For CPU = -1, For Single GPU = 0",
    )
    parser.add_argument(
        "--epoch",
        dest="max_epochs",
        type=int,
        default=500,
        help="Number of epochs",
    )
    parser.add_argument(
        "--l2", type=float, default=0.0, help="L2 Regularization for Optimizer"
    )
    parser.add_argument(
        "--lr", type=float, default=0.001, help="Starting Learning Rate"
    )
    parser.add_argument(
        "--lbl_smooth",
        dest="lbl_smooth",
        type=float,
        default=0.1,
        help="Label Smoothing",
    )
    parser.add_argument(
        "--num_workers",
        type=int,
        default=10,
        help="Number of processes to construct batches",
    )
    parser.add_argument(
        "--seed",
        dest="seed",
        default=41504,
        type=int,
        help="Seed for randomization",
    )

    parser.add_argument(
        "--num_bases",
        dest="num_bases",
        default=-1,
        type=int,
        help="Number of basis relation vectors to use",
    )
    parser.add_argument(
        "--init_dim",
        dest="init_dim",
        default=100,
        type=int,
        help="Initial dimension size for entities and relations",
    )
    parser.add_argument(
        "--layer_size",
        nargs="?",
        default="[200]",
        help="List of output size for each compGCN layer",
    )
    parser.add_argument(
        "--gcn_drop",
        dest="dropout",
        default=0.1,
        type=float,
        help="Dropout to use in GCN Layer",
    )
    parser.add_argument(
        "--layer_dropout",
        nargs="?",
        default="[0.3]",
        help="List of dropout value after each compGCN layer",
    )
KounianhuaDu's avatar
KounianhuaDu committed
314
315

    # ConvE specific hyperparameters
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
    parser.add_argument(
        "--hid_drop",
        dest="hid_drop",
        default=0.3,
        type=float,
        help="ConvE: Hidden dropout",
    )
    parser.add_argument(
        "--feat_drop",
        dest="feat_drop",
        default=0.3,
        type=float,
        help="ConvE: Feature Dropout",
    )
    parser.add_argument(
        "--k_w", dest="k_w", default=10, type=int, help="ConvE: k_w"
    )
    parser.add_argument(
        "--k_h", dest="k_h", default=20, type=int, help="ConvE: k_h"
    )
    parser.add_argument(
        "--num_filt",
        dest="num_filt",
        default=200,
        type=int,
        help="ConvE: Number of filters in convolution",
    )
    parser.add_argument(
        "--ker_sz",
        dest="ker_sz",
        default=7,
        type=int,
        help="ConvE: Kernel size to use",
    )
KounianhuaDu's avatar
KounianhuaDu committed
350
351

    args = parser.parse_args()
352

KounianhuaDu's avatar
KounianhuaDu committed
353
354
355
356
357
358
359
360
361
    np.random.seed(args.seed)
    th.manual_seed(args.seed)

    print(args)

    args.layer_size = eval(args.layer_size)
    args.layer_dropout = eval(args.layer_dropout)

    main(args)