forked from BUPT-GAMMA/GammaGL
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chebnet_trainer.py
142 lines (118 loc) · 5.11 KB
/
chebnet_trainer.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
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
136
137
138
139
140
141
142
# !/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@File : chebnet_trainer.py
@Time : 2022/5/14 11:05:55
@Author : Zhang Zhongjian
"""
import os
# os.environ['CUDA_VISIBLE_DEVICES']='0'
# os.environ['TL_BACKEND'] = 'paddle'
import sys
sys.path.insert(0, os.path.abspath('../../')) # adds path2gammagl to execute in command line.
import argparse
import tensorlayerx as tlx
from gammagl.datasets import Planetoid
from gammagl.models import ChebNetModel
from gammagl.utils import mask_to_index
from tensorlayerx.model import TrainOneStep, WithLoss
if tlx.BACKEND == 'torch': # when the backend is torch and you want to use GPU
try:
tlx.set_device(device='GPU', id=0)
except:
print("GPU is not available")
class SemiSpvzLoss(WithLoss):
def __init__(self, net, loss_fn):
super(SemiSpvzLoss, self).__init__(backbone=net, loss_fn=loss_fn)
def forward(self, data, y):
logits = self.backbone_network(data['x'], data['edge_index'], data['edge_weight'], data['num_nodes'])
train_logits = tlx.gather(logits, data['train_idx'])
train_y = tlx.gather(data['y'], data['train_idx'])
loss = self._loss_fn(train_logits, train_y)
return loss
def calculate_acc(logits, y, metrics):
"""
Args:
logits: node logits
y: node labels
metrics: tensorlayerx.metrics
Returns:
rst
"""
metrics.update(logits, y)
rst = metrics.result()
metrics.reset()
return rst
def main(args):
# 1. load dataset
if str.lower(args.dataset) not in ['cora', 'pubmed', 'citeseer']:
raise ValueError('Unknown dataset: {}'.format(args.dataset))
dataset = Planetoid(args.dataset_path, args.dataset)
graph = dataset[0]
edge_index = graph.edge_index
edge_weight = tlx.ones((edge_index.shape[1],))
# for mindspore, it should be passed into node indices
train_idx = mask_to_index(graph.train_mask)
test_idx = mask_to_index(graph.test_mask)
val_idx = mask_to_index(graph.val_mask)
net = ChebNetModel(feature_dim=dataset.num_node_features,
hidden_dim=args.hidden_dim,
out_dim=graph.num_nodes,
k=args.k,
drop_rate=args.drop_rate,
name="ChebNet")
optimizer = tlx.optimizers.Adam(lr=args.lr, weight_decay=args.l2_coef)
metrics = tlx.metrics.Accuracy()
train_weights = net.trainable_weights
loss_func = SemiSpvzLoss(net, tlx.losses.softmax_cross_entropy_with_logits)
train_one_step = TrainOneStep(loss_func, optimizer, train_weights)
data = {
"x": graph.x,
"y": graph.y,
"edge_index": edge_index,
"edge_weight": edge_weight,
"train_idx": train_idx,
"test_idx": test_idx,
"val_idx": val_idx,
"num_nodes": graph.num_nodes,
}
best_val_acc = 0
for epoch in range(args.n_epoch):
net.set_train()
train_loss = train_one_step(data, data['y'])
net.set_eval()
logits = net(data['x'], data['edge_index'], data['edge_weight'], data['num_nodes'])
val_logits = tlx.gather(logits, data['val_idx'])
val_y = tlx.gather(data['y'], data['val_idx'])
val_acc = calculate_acc(val_logits, val_y, metrics)
print("Epoch [{:0>3d}] ".format(epoch + 1) \
+ " train loss: {:.4f}".format(train_loss.item()) \
+ " val acc: {:.4f}".format(val_acc))
# save best model on evaluation set
if val_acc > best_val_acc:
best_val_acc = val_acc
net.save_weights(args.best_model_path + "ChebNet_" + args.dataset + ".npz", format='npz_dict')
net.load_weights(args.best_model_path + "ChebNet_" + args.dataset + ".npz", format='npz_dict')
if tlx.BACKEND == 'torch':
net.to(data['x'].device)
net.set_eval()
logits = net(data['x'], data['edge_index'], data['edge_weight'], data['num_nodes'])
test_logits = tlx.gather(logits, data['test_idx'])
test_y = tlx.gather(data['y'], data['test_idx'])
test_acc = calculate_acc(test_logits, test_y, metrics)
print("Test acc: {:.4f}".format(test_acc))
if __name__ == '__main__':
# parameters setting
parser = argparse.ArgumentParser()
parser.add_argument("--k", type=int, default=2, help="the k of every chebconv")
parser.add_argument("--lr", type=float, default=0.01, help="learnin rate")
parser.add_argument("--n_epoch", type=int, default=200, help="number of epoch")
parser.add_argument("--hidden_dim", type=int, default=64, help="dimention of hidden layers")
parser.add_argument("--drop_rate", type=float, default=0.5, help="drop_rate")
parser.add_argument("--l2_coef", type=float, default=5e-4, help="l2 loss coeficient")
parser.add_argument('--dataset', type=str, default='cora', help='dataset')
parser.add_argument("--dataset_path", type=str, default=r'../', help="path to save dataset")
parser.add_argument("--best_model_path", type=str, default=r'./', help="path to save best model")
parser.add_argument("--self_loops", type=int, default=1, help="number of graph self-loop")
args = parser.parse_args()
main(args)