-
Notifications
You must be signed in to change notification settings - Fork 3
/
train.py
187 lines (152 loc) · 6.38 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
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
181
182
183
184
185
186
187
from __future__ import division
from __future__ import print_function
import time
import tensorflow as tf
from sklearn import metrics
from utils import *
from models import GCN
import random
import os
import sys
if len(sys.argv) != 2:
sys.exit("Use: python train.py <dataset>")
dataset = sys.argv[1]
# Set random seed
seed = random.randint(1, 200)
tf.set_random_seed(seed)
# Settings, default not using GPU
os.environ["CUDA_VISIBLE_DEVICES"] = ""
flags = tf.app.flags
FLAGS = flags.FLAGS
# 'cora', 'citeseer', 'pubmed'
flags.DEFINE_string('dataset', dataset, 'Dataset string.')
# 'gcn', 'gcn_cheby', 'dense'
flags.DEFINE_string('model', 'gcn', 'Model string.')
flags.DEFINE_float('learning_rate', 0.02, 'Initial learning rate.')
flags.DEFINE_integer('epochs', 200, 'Number of epochs to train.')
flags.DEFINE_integer('hidden1', 200, 'Number of units in hidden layer 1.')
flags.DEFINE_float('dropout', 0.5, 'Dropout rate (1 - keep probability).')
flags.DEFINE_float('weight_decay', 0,
'Weight for L2 loss on embedding matrix.') # 5e-4
flags.DEFINE_integer('early_stopping', 10,
'Tolerance for early stopping (# of epochs).')
flags.DEFINE_integer('max_degree', 3, 'Maximum Chebyshev polynomial degree.')
# Load data
adj, features, y_train, y_val, y_test, train_mask, val_mask, test_mask, train_size, test_size = load_corpus(
FLAGS.dataset)
# print(adj)
features = sp.identity(features.shape[0]) # featureless
print(adj.shape)
print(features.shape)
# Some preprocessing
features = preprocess_features(features)
if FLAGS.model == 'gcn':
support = [preprocess_adj(adj)]
num_supports = 1 # list size 1, different from Kipf
else:
raise ValueError('Invalid argument for model: ' + str(FLAGS.model))
# Define placeholders
placeholders = {
'support': [tf.sparse_placeholder(tf.float32) for _ in range(num_supports)],
'features': tf.sparse_placeholder(tf.float32, shape=tf.constant(features[2], dtype=tf.int64)),
'labels': tf.placeholder(tf.float32, shape=(None, y_train.shape[1])),
'labels_mask': tf.placeholder(tf.int32),
'dropout': tf.placeholder_with_default(0., shape=()),
# helper variable for sparse dropout
'num_features_nonzero': tf.placeholder(tf.int32),
}
# Create model
print(features[2][1]) # dim, note there is sparse_to_tuple in preprocess_features
model = GCN(placeholders, input_dim=features[2][1], logging=True)
# Initialize session
session_conf = tf.ConfigProto(gpu_options=tf.GPUOptions(allow_growth=True))
sess = tf.Session(config=session_conf)
# Define model evaluation function
def evaluate(features, support, labels, mask, placeholders):
t_test = time.time()
feed_dict_val = construct_feed_dict(
features, support, labels, mask, placeholders)
outs_val = sess.run([model.loss, model.accuracy, model.pred, model.labels], feed_dict=feed_dict_val)
return outs_val[0], outs_val[1], outs_val[2], outs_val[3], (time.time() - t_test)
# Init variables, models.py call layers.py then call init.py
sess.run(tf.global_variables_initializer())
cost_val = []
# Train model
for epoch in range(FLAGS.epochs):
t = time.time()
# Construct feed dictionary, same input for every epoch as we input full batch
feed_dict = construct_feed_dict(
features, support, y_train, train_mask, placeholders)
feed_dict.update({placeholders['dropout']: FLAGS.dropout}) # update dropout for train, different from test 0
# to inductive
# Training step
outs = sess.run([model.opt_op, model.loss, model.accuracy,
model.layers[0].embedding], feed_dict=feed_dict)
# Validation
cost, acc, pred, labels, duration = evaluate(
features, support, y_val, val_mask, placeholders)
cost_val.append(cost)
print("Epoch:", '%04d' % (epoch + 1), "train_loss=", "{:.5f}".format(outs[1]),
"train_acc=", "{:.5f}".format(
outs[2]), "val_loss=", "{:.5f}".format(cost),
"val_acc=", "{:.5f}".format(acc), "time=", "{:.5f}".format(time.time() - t))
if epoch > FLAGS.early_stopping and cost_val[-1] > np.mean(cost_val[-(FLAGS.early_stopping+1):-1]):
print("Early stopping...")
break
print("Optimization Finished!")
# Testing
test_cost, test_acc, pred, labels, test_duration = evaluate(
features, support, y_test, test_mask, placeholders)
print("Test set results:", "cost=", "{:.5f}".format(test_cost),
"accuracy=", "{:.5f}".format(test_acc), "time=", "{:.5f}".format(test_duration))
test_pred = []
test_labels = []
print(len(test_mask))
for i in range(len(test_mask)):
if test_mask[i]:
test_pred.append(pred[i])
test_labels.append(labels[i])
print("Test Precision, Recall and F1-Score...")
print(metrics.classification_report(test_labels, test_pred, digits=4))
print("Macro average Test Precision, Recall and F1-Score...")
print(metrics.precision_recall_fscore_support(test_labels, test_pred, average='macro'))
print("Micro average Test Precision, Recall and F1-Score...")
print(metrics.precision_recall_fscore_support(test_labels, test_pred, average='micro'))
# doc and word embeddings
print('embeddings:')
word_embeddings = outs[3][train_size: adj.shape[0] - test_size]
train_doc_embeddings = outs[3][:train_size] # include val docs
test_doc_embeddings = outs[3][adj.shape[0] - test_size:]
print(len(word_embeddings), len(train_doc_embeddings),
len(test_doc_embeddings))
## print(word_embeddings)
f = open('data/corpus/' + dataset + '_vocab.txt', 'r')
words = f.readlines()
f.close()
vocab_size = len(words)
word_vectors = []
for i in range(vocab_size):
word = words[i].strip()
word_vector = word_embeddings[i]
word_vector_str = ' '.join([str(x) for x in word_vector])
word_vectors.append(word + ' ' + word_vector_str)
word_embeddings_str = '\n'.join(word_vectors)
f = open('data/' + dataset + '_word_vectors.txt', 'w')
f.write(word_embeddings_str)
f.close()
doc_vectors = []
doc_id = 0
for i in range(train_size):
doc_vector = train_doc_embeddings[i]
doc_vector_str = ' '.join([str(x) for x in doc_vector])
doc_vectors.append('doc_' + str(doc_id) + ' ' + doc_vector_str)
doc_id += 1
for i in range(test_size):
doc_vector = test_doc_embeddings[i]
doc_vector_str = ' '.join([str(x) for x in doc_vector])
doc_vectors.append('doc_' + str(doc_id) + ' ' + doc_vector_str)
doc_id += 1
doc_embeddings_str = '\n'.join(doc_vectors)
f = open('data/' + dataset + '_doc_vectors.txt', 'w')
f.write(doc_embeddings_str)
f.close()