-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.py
180 lines (147 loc) · 8.54 KB
/
main.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
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
import argparse
import os
import random
import numpy as np
import torch
from data_generator import DataGenerator
from maml import meta_gradient_step
from models import GCN, GCN_Proto, GCN_Structure
##############
# Parameters #
##############
parser = argparse.ArgumentParser(description='graph transfer')
parser.add_argument("--datapath", default="../data/", type=str)
parser.add_argument("--graphpath", default="../data/graph/", type=str)
parser.add_argument('--logdir', type=str, default='../logs', help='directory for summaries and checkpoints.')
# data generate hyperparameters
parser.add_argument("--random_seed", default='1', type=int)
parser.add_argument("--batch_n", default=5, type=int)
parser.add_argument('--A_n', default=18872 + 1, type=int)
parser.add_argument('--P_n', default=12334 + 1, type=int)
parser.add_argument('--V_n', default=18, type=int)
parser.add_argument("--in_f_d", default=128, type=int)
parser.add_argument("--sample_g_n", default=100, type=int, help='number of graph for meta-training')
parser.add_argument("--test_sample_g_n", default=20, type=int, help='number of graph for meta-testing/validation')
# training hyperparameters
parser.add_argument('--meta_lr', type=float, default=0.001, help='meta learning rate')
parser.add_argument('--batch_train_n', type=int, default=10, help='shot number')
parser.add_argument('--model', type=str, default='gcn', help='gcn')
parser.add_argument('--metatrain_iterations', type=int, default=3000, help='meta training iterations')
parser.add_argument('--update_batch_size', type=int, default=100, help='how much samples used for training')
parser.add_argument('--inner_train_steps', type=int, default=5, help='inner_train_step')
parser.add_argument('--inner_lr', type=float, default=1e-3, help='inner learning rate')
parser.add_argument('--inner_lr_test', type=float, default=1e-3, help='inner learning rate of test')
parser.add_argument("--test_load_epoch", default=100, type=int)
parser.add_argument('--device', default=0, type=int)
parser.add_argument('--train', type=int, default=1, help='train or test')
# model hyperparameters
parser.add_argument('--graph_threshold', type=float, default=-1, help='threshold of graph construction')
parser.add_argument('--alpha', type=float, default=0.2, help='Alpha for the leaky_relu.')
parser.add_argument('--dropout', type=float, default=0.0, help='Dropout rate (1 - keep probability).')
parser.add_argument('--nclasses', type=int, default=4, help='number of classes')
parser.add_argument('--nb_heads', type=int, default=8, help='Number of head attentions.')
parser.add_argument('--proto', type=str, default='graph', help='mean or graph')
parser.add_argument('--ae_weight', type=float, default=1.0, help='the weight of autoencoder loss')
parser.add_argument('--structure_dim', type=int, default=8, help='structure dimension')
parser.add_argument('--nhops', type=int, default=2, help='number of hops of structure embedding')
parser.add_argument('--hop_concat_type', type=str, default='fc', help='fc or attention or mean')
parser.add_argument('--module_type', type=str, default='sigmoid', help='sigmoid')
parser.add_argument('--hidden', type=int, default=8, help='Number of hidden units.')
parser.add_argument('--weight_decay', type=float, default=0, help='Weight decay (L2 loss on parameters).')
parser.add_argument('--weight_metric', type=int, default=1, help='1: k-hop common neighbor num, 2: jacard index, 3: adar index, 4: pagerank')
args = parser.parse_args()
print(args)
assert torch.cuda.is_available()
device = torch.device('cuda:{}'.format(args.device))
torch.backends.cudnn.benchmark = True
random.seed(args.random_seed)
np.random.seed(args.random_seed)
flag = 1
exp_string = "metalr.{}_".format(args.meta_lr) + "model.{}_".format(args.model) + "ubs.{}_".format(args.update_batch_size) + "innerlr.{}_".format(
args.inner_lr) + "hidden.{}_".format(args.hidden) + "weightmetric.{}_".format(args.weight_metric)
exp_string += "nhops.{}_".format(args.nhops)
exp_string += "hopconcat.{}_".format(args.hop_concat_type) + "module.{}_".format(
args.module_type) + "sdim.{}_".format(args.structure_dim)
exp_string += "aeweight.{}_".format(args.ae_weight)
SAVE_EPOCH = 20
def gradient_step(model, optimiser, loss_fn, x, y, **kwargs):
"""Takes a single gradient step.
"""
model.train()
optimiser.zero_grad()
y_pred = model(x)
loss = loss_fn(y_pred, y)
loss.backward()
optimiser.step()
return loss, y_pred
def train(args, model, optimiser, proto_model=None, structure_model=None, metatrain_iterations=2000,
data_generator=None,
verbose=True, fit_function=gradient_step, fit_function_kwargs={}):
if verbose:
print('Begin training...')
for epoch in range(metatrain_iterations):
input_data = data_generator.next_batch()
loss, acc, _ = fit_function(args, model, optimiser, proto_model, structure_model, input_data,
**fit_function_kwargs)
print(epoch, loss.item(), acc.item())
if not os.path.exists(args.logdir + '/' + exp_string + '/'):
os.makedirs(args.logdir + '/' + exp_string + '/')
if epoch % SAVE_EPOCH == 0 and epoch != 0:
torch.save(model.state_dict(), args.logdir + '/' + exp_string + '/' + 'model_epoch_{}'.format(epoch))
if proto_model != None:
torch.save(proto_model.state_dict(),
args.logdir + '/' + exp_string + '/' + 'proto_model_epoch_{}'.format(epoch))
if structure_model != None:
torch.save(structure_model.state_dict(),
args.logdir + '/' + exp_string + '/' + 'structure_model_epoch_{}'.format(epoch))
if verbose:
print('Finished.')
def evaluate(args, model, optimiser, proto_model=None, structure_model=None, data_generator=None,
verbose=True, fit_function=gradient_step, fit_function_kwargs={}):
if verbose:
print('Begin evaluating...')
input_data = data_generator.test_batch()
loss, acc, ci = fit_function(args, model, optimiser, proto_model, structure_model, input_data,
**fit_function_kwargs)
# ipdb.set_trace()
print("testing results: loss is {}, acc is {}, ci is {}".format(loss.item(), acc.item(), ci.item()))
if verbose:
print('Finished.')
def main():
data_generator = DataGenerator(args)
meta_model = GCN(nfeat=args.in_f_d,
nhid=args.hidden,
nclass=args.nclasses,
dropout=args.dropout).to(device)
proto_model = GCN_Proto(args, nfeat=args.hidden, dropout=args.dropout).to(device)
structure_model = GCN_Structure(args, nfeat=args.hidden, nhid=args.structure_dim, dropout=args.dropout).to(
device)
if args.train:
meta_optimiser = torch.optim.Adam(
list(meta_model.parameters()) + list(proto_model.parameters()) + list(structure_model.parameters()),
lr=args.meta_lr, weight_decay=args.weight_decay)
train(args, meta_model, meta_optimiser, proto_model, structure_model,
metatrain_iterations=args.metatrain_iterations,
data_generator=data_generator, fit_function=meta_gradient_step,
fit_function_kwargs={'train': True, 'inner_train_steps': args.inner_train_steps,
'inner_lr': args.inner_lr, 'batch_n': args.batch_n, 'device': device})
else:
if args.test_load_epoch > 0:
meta_model.load_state_dict(
torch.load(args.logdir + '/' + exp_string + '/' + 'model_epoch_{}'.format(args.test_load_epoch)))
proto_model.load_state_dict(
torch.load(
args.logdir + '/' + exp_string + '/' + 'proto_model_epoch_{}'.format(args.test_load_epoch)))
structure_model.load_state_dict(
torch.load(
args.logdir + '/' + exp_string + '/' + 'structure_model_epoch_{}'.format(
args.test_load_epoch)))
meta_optimiser = torch.optim.Adam(list(meta_model.parameters()) + list(proto_model.parameters()),
lr=args.meta_lr, weight_decay=args.weight_decay)
evaluate(args, meta_model, meta_optimiser, proto_model, structure_model, data_generator=data_generator,
fit_function=meta_gradient_step,
fit_function_kwargs={'train': False, 'inner_train_steps': args.inner_train_steps,
'inner_lr': args.inner_lr_test, 'batch_n': args.test_sample_g_n,
'device': device})
if __name__ == '__main__':
main()