-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtrain.py
137 lines (108 loc) · 4.32 KB
/
train.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
from __future__ import print_function
from keras.layers import Input, Dropout
from keras.models import Model
from keras.optimizers import Adam
from keras.regularizers import l2
from graph import GraphConvolution
from input_adj import InputAdj
from utils import *
import pickle as pkl
import os
import sys
import time
import argparse
np.random.seed()
ap = argparse.ArgumentParser()
ap.add_argument("-d", "--dataset", type=str, default="aifb",
help="Dataset string ('aifb', 'mutag', 'bgs', 'am')")
ap.add_argument("-e", "--epochs", type=int, default=50,
help="Number training epochs")
ap.add_argument("-hd", "--hidden", type=int, default=16,
help="Number hidden units")
ap.add_argument("-do", "--dropout", type=float, default=0.,
help="Dropout rate")
ap.add_argument("-b", "--bases", type=int, default=-1,
help="Number of bases used (-1: all)")
ap.add_argument("-lr", "--learnrate", type=float, default=0.01,
help="Learning rate")
ap.add_argument("-l2", "--l2norm", type=float, default=0.,
help="L2 normalization of input weights")
fp = ap.add_mutually_exclusive_group(required=False)
fp.add_argument('--validation', dest='validation', action='store_true')
fp.add_argument('--testing', dest='validation', action='store_false')
ap.set_defaults(validation=True)
args = vars(ap.parse_args())
print(args)
# Define parameters
DATASET = args['dataset']
NB_EPOCH = args['epochs']
VALIDATION = args['validation']
LR = args['learnrate']
L2 = args['l2norm']
HIDDEN = args['hidden']
BASES = args['bases']
DO = args['dropout']
dirname = os.path.dirname(os.path.realpath(sys.argv[0]))
with open(dirname + '/' + DATASET + '.pickle', 'rb') as f:
data = pkl.load(f)
A = data['A']
y = data['y']
train_idx = data['train_idx']
test_idx = data['test_idx']
# Get dataset splits
y_train, y_val, y_test, idx_train, idx_val, idx_test = get_splits(y, train_idx,
test_idx,
VALIDATION)
train_mask = sample_mask(idx_train, y.shape[0])
num_nodes = A[0].shape[0]
support = len(A)
# Define empty dummy feature matrix (input is ignored as we set featureless=True)
# In case features are available, define them here and set featureless=False.
X = sp.csr_matrix(A[0].shape)
# Normalize adjacency matrices individually
for i in range(len(A)):
d = np.array(A[i].sum(1)).flatten()
d_inv = 1. / d
d_inv[np.isinf(d_inv)] = 0.
D_inv = sp.diags(d_inv)
A[i] = D_inv.dot(A[i]).tocsr()
A_in = [InputAdj(sparse=True) for _ in range(support)]
X_in = Input(shape=(X.shape[1],), sparse=True)
# Define model architecture
H = GraphConvolution(HIDDEN, support, num_bases=BASES, featureless=True,
activation='relu',
W_regularizer=l2(L2))([X_in] + A_in)
H = Dropout(DO)(H)
Y = GraphConvolution(y_train.shape[1], support, num_bases=BASES,
activation='softmax')([H] + A_in)
# Compile model
model = Model(input=[X_in] + A_in, output=Y)
model.compile(loss='categorical_crossentropy', optimizer=Adam(lr=LR))
preds = None
# Fit
for epoch in range(1, NB_EPOCH + 1):
# Log wall-clock time
t = time.time()
# Single training iteration
model.fit([X] + A, y_train, sample_weight=train_mask,
batch_size=num_nodes, nb_epoch=1, shuffle=False, verbose=0)
if epoch % 1 == 0:
# Predict on full dataset
preds = model.predict([X] + A, batch_size=num_nodes)
# Train / validation scores
train_val_loss, train_val_acc = evaluate_preds(preds, [y_train, y_val],
[idx_train, idx_val])
print("Epoch: {:04d}".format(epoch),
"train_loss= {:.4f}".format(train_val_loss[0]),
"train_acc= {:.4f}".format(train_val_acc[0]),
"val_loss= {:.4f}".format(train_val_loss[1]),
"val_acc= {:.4f}".format(train_val_acc[1]),
"time= {:.4f}".format(time.time() - t))
else:
print("Epoch: {:04d}".format(epoch),
"time= {:.4f}".format(time.time() - t))
# Testing
test_loss, test_acc = evaluate_preds(preds, [y_test], [idx_test])
print("Test set results:",
"loss= {:.4f}".format(test_loss[0]),
"accuracy= {:.4f}".format(test_acc[0]))