-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
han_imdb.py
93 lines (73 loc) · 2.78 KB
/
han_imdb.py
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
import os.path as osp
from typing import Dict, List, Union
import torch
import torch.nn.functional as F
from torch import nn
import torch_geometric
import torch_geometric.transforms as T
from torch_geometric.datasets import IMDB
from torch_geometric.nn import HANConv
path = osp.join(osp.dirname(osp.realpath(__file__)), '../../data/IMDB')
metapaths = [[('movie', 'actor'), ('actor', 'movie')],
[('movie', 'director'), ('director', 'movie')]]
transform = T.AddMetaPaths(metapaths=metapaths, drop_orig_edge_types=True,
drop_unconnected_node_types=True)
dataset = IMDB(path, transform=transform)
data = dataset[0]
class HAN(nn.Module):
def __init__(self, in_channels: Union[int, Dict[str, int]],
out_channels: int, hidden_channels=128, heads=8):
super().__init__()
self.han_conv = HANConv(in_channels, hidden_channels, heads=heads,
dropout=0.6, metadata=data.metadata())
self.lin = nn.Linear(hidden_channels, out_channels)
def forward(self, x_dict, edge_index_dict):
out = self.han_conv(x_dict, edge_index_dict)
out = self.lin(out['movie'])
return out
model = HAN(in_channels=-1, out_channels=3)
if torch.cuda.is_available():
device = torch.device('cuda')
elif torch_geometric.is_xpu_available():
device = torch.device('xpu')
else:
device = torch.device('cpu')
data, model = data.to(device), model.to(device)
with torch.no_grad(): # Initialize lazy modules.
out = model(data.x_dict, data.edge_index_dict)
optimizer = torch.optim.Adam(model.parameters(), lr=0.005, weight_decay=0.001)
def train() -> float:
model.train()
optimizer.zero_grad()
out = model(data.x_dict, data.edge_index_dict)
mask = data['movie'].train_mask
loss = F.cross_entropy(out[mask], data['movie'].y[mask])
loss.backward()
optimizer.step()
return float(loss)
@torch.no_grad()
def test() -> List[float]:
model.eval()
pred = model(data.x_dict, data.edge_index_dict).argmax(dim=-1)
accs = []
for split in ['train_mask', 'val_mask', 'test_mask']:
mask = data['movie'][split]
acc = (pred[mask] == data['movie'].y[mask]).sum() / mask.sum()
accs.append(float(acc))
return accs
best_val_acc = 0
start_patience = patience = 100
for epoch in range(1, 200):
loss = train()
train_acc, val_acc, test_acc = test()
print(f'Epoch: {epoch:03d}, Loss: {loss:.4f}, Train: {train_acc:.4f}, '
f'Val: {val_acc:.4f}, Test: {test_acc:.4f}')
if best_val_acc <= val_acc:
patience = start_patience
best_val_acc = val_acc
else:
patience -= 1
if patience <= 0:
print('Stopping training as validation accuracy did not improve '
f'for {start_patience} epochs')
break