main.py 6.53 KB
Newer Older
1
2
3
4
5
import argparse
import pickle as pkl

import numpy as np
import torch
KounianhuaDu's avatar
KounianhuaDu committed
6
7
8
9
import torch.nn as nn
import torch.optim as optim
from data_loader import load_data
from TAHIN import TAHIN
10
11
12
13
14
15
16
17
18
from utils import (
    evaluate_acc,
    evaluate_auc,
    evaluate_f1_score,
    evaluate_logloss,
)

import dgl

KounianhuaDu's avatar
KounianhuaDu committed
19
20

def main(args):
21
    # step 1: Check device
KounianhuaDu's avatar
KounianhuaDu committed
22
    if args.gpu >= 0 and torch.cuda.is_available():
23
        device = "cuda:{}".format(args.gpu)
KounianhuaDu's avatar
KounianhuaDu committed
24
    else:
25
26
27
28
29
30
31
32
33
34
35
36
        device = "cpu"

    # step 2: Load data
    (
        g,
        train_loader,
        eval_loader,
        test_loader,
        meta_paths,
        user_key,
        item_key,
    ) = load_data(args.dataset, args.batch, args.num_workers, args.path)
KounianhuaDu's avatar
KounianhuaDu committed
37
    g = g.to(device)
38
    print("Data loaded.")
KounianhuaDu's avatar
KounianhuaDu committed
39

40
    # step 3: Create model and training components
KounianhuaDu's avatar
KounianhuaDu committed
41
42
    model = TAHIN(
        g, meta_paths, args.in_size, args.out_size, args.num_heads, args.dropout
43
    )
KounianhuaDu's avatar
KounianhuaDu committed
44
45
46
    model = model.to(device)
    criterion = nn.BCELoss()
    optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.wd)
47
    print("Model created.")
KounianhuaDu's avatar
KounianhuaDu committed
48

49
50
    # step 4: Training
    print("Start training.")
KounianhuaDu's avatar
KounianhuaDu committed
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
    best_acc = 0.0
    kill_cnt = 0
    for epoch in range(args.epochs):
        # Training and validation using a full graph
        model.train()
        train_loss = []
        for step, batch in enumerate(train_loader):
            user, item, label = [_.to(device) for _ in batch]
            logits = model.forward(g, user_key, item_key, user, item)

            # compute loss
            tr_loss = criterion(logits, label)
            train_loss.append(tr_loss)

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

70
        train_loss = torch.stack(train_loss).sum().cpu().item()
KounianhuaDu's avatar
KounianhuaDu committed
71
72
73
74
75
76
77
78
79
80
81

        model.eval()
        with torch.no_grad():
            validate_loss = []
            validate_acc = []
            for step, batch in enumerate(eval_loader):
                user, item, label = [_.to(device) for _ in batch]
                logits = model.forward(g, user_key, item_key, user, item)

                # compute loss
                val_loss = criterion(logits, label)
82
83
84
                val_acc = evaluate_acc(
                    logits.detach().cpu().numpy(), label.detach().cpu().numpy()
                )
KounianhuaDu's avatar
KounianhuaDu committed
85
86
                validate_loss.append(val_loss)
                validate_acc.append(val_acc)
87
88

            validate_loss = torch.stack(validate_loss).sum().cpu().item()
KounianhuaDu's avatar
KounianhuaDu committed
89
            validate_acc = np.mean(validate_acc)
90
91

            # validate
KounianhuaDu's avatar
KounianhuaDu committed
92
93
94
            if validate_acc > best_acc:
                best_acc = validate_acc
                best_epoch = epoch
95
                torch.save(model.state_dict(), "TAHIN" + "_" + args.dataset)
KounianhuaDu's avatar
KounianhuaDu committed
96
97
98
99
100
                kill_cnt = 0
                print("saving model...")
            else:
                kill_cnt += 1
                if kill_cnt > args.early_stop:
101
                    print("early stop.")
KounianhuaDu's avatar
KounianhuaDu committed
102
103
104
                    print("best epoch:{}".format(best_epoch))
                    break

105
106
107
108
109
            print(
                "In epoch {}, Train Loss: {:.4f}, Valid Loss: {:.5}\n, Valid ACC: {:.5}".format(
                    epoch, train_loss, validate_loss, validate_acc
                )
            )
KounianhuaDu's avatar
KounianhuaDu committed
110

111
    # test use the best model
KounianhuaDu's avatar
KounianhuaDu committed
112
113
    model.eval()
    with torch.no_grad():
114
        model.load_state_dict(torch.load("TAHIN" + "_" + args.dataset))
KounianhuaDu's avatar
KounianhuaDu committed
115
116
117
118
119
120
121
122
123
124
125
        test_loss = []
        test_acc = []
        test_auc = []
        test_f1 = []
        test_logloss = []
        for step, batch in enumerate(test_loader):
            user, item, label = [_.to(device) for _ in batch]
            logits = model.forward(g, user_key, item_key, user, item)

            # compute loss
            loss = criterion(logits, label)
126
127
128
129
130
131
132
133
134
135
136
137
138
            acc = evaluate_acc(
                logits.detach().cpu().numpy(), label.detach().cpu().numpy()
            )
            auc = evaluate_auc(
                logits.detach().cpu().numpy(), label.detach().cpu().numpy()
            )
            f1 = evaluate_f1_score(
                logits.detach().cpu().numpy(), label.detach().cpu().numpy()
            )
            log_loss = evaluate_logloss(
                logits.detach().cpu().numpy(), label.detach().cpu().numpy()
            )

KounianhuaDu's avatar
KounianhuaDu committed
139
140
141
142
143
            test_loss.append(loss)
            test_acc.append(acc)
            test_auc.append(auc)
            test_f1.append(f1)
            test_logloss.append(log_loss)
144
145

        test_loss = torch.stack(test_loss).sum().cpu().item()
KounianhuaDu's avatar
KounianhuaDu committed
146
147
148
149
        test_acc = np.mean(test_acc)
        test_auc = np.mean(test_auc)
        test_f1 = np.mean(test_f1)
        test_logloss = np.mean(test_logloss)
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
204
205
206
207
208
209
210
211
212
213
214
        print(
            "Test Loss: {:.5}\n, Test ACC: {:.5}\n, AUC: {:.5}\n, F1: {:.5}\n, Logloss: {:.5}\n".format(
                test_loss, test_acc, test_auc, test_f1, test_logloss
            )
        )


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

    parser.add_argument(
        "--dataset",
        default="movielens",
        help="Dataset to use, default: movielens",
    )
    parser.add_argument(
        "--path", default="./data", help="Path to save the data"
    )
    parser.add_argument("--model", default="TAHIN", help="Model Name")

    parser.add_argument("--batch", default=128, 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(
        "--epochs", type=int, default=500, help="Maximum number of epochs"
    )
    parser.add_argument(
        "--wd", type=float, default=0, help="L2 Regularization for Optimizer"
    )
    parser.add_argument("--lr", type=float, default=0.001, help="Learning Rate")
    parser.add_argument(
        "--num_workers",
        type=int,
        default=10,
        help="Number of processes to construct batches",
    )
    parser.add_argument(
        "--early_stop", default=15, type=int, help="Patience for early stop."
    )

    parser.add_argument(
        "--in_size",
        default=128,
        type=int,
        help="Initial dimension size for entities.",
    )
    parser.add_argument(
        "--out_size",
        default=128,
        type=int,
        help="Output dimension size for entities.",
    )

    parser.add_argument(
        "--num_heads", default=1, type=int, help="Number of attention heads"
    )
    parser.add_argument("--dropout", default=0.1, type=float, help="Dropout.")

KounianhuaDu's avatar
KounianhuaDu committed
215
216
217
218
219
    args = parser.parse_args()

    print(args)

    main(args)