|
| 1 | +# Copyright 2020 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +"""Trains a GNN.""" |
| 15 | +import time |
| 16 | + |
| 17 | +from absl import app |
| 18 | +from absl import flags |
| 19 | +import tensorflow as tf |
| 20 | + |
| 21 | +from utils import load_dataset, build_model, cal_acc # pylint: disable=g-multiple-import |
| 22 | + |
| 23 | +flags.DEFINE_enum('dataset', 'cora', ['cora'], |
| 24 | + 'The input dataset. Avaliable dataset now: cora') |
| 25 | +flags.DEFINE_enum('model', 'gcn', ['gcn'], |
| 26 | + 'GNN model. Available model now: gcn') |
| 27 | +flags.DEFINE_float('dropout_rate', 0.5, 'Dropout probability') |
| 28 | +flags.DEFINE_integer('gpu', '-1', 'Gpu id, -1 means cpu only') |
| 29 | +flags.DEFINE_float('lr', 1e-2, 'Initial learning rate') |
| 30 | +flags.DEFINE_integer('epochs', 200, 'Number of training epochs') |
| 31 | +flags.DEFINE_integer('num_layers', 2, 'Number of gnn layers') |
| 32 | +flags.DEFINE_list('hidden_dim', [32], 'Dimension of gnn hidden layers') |
| 33 | +flags.DEFINE_enum('optimizer', 'adam', ['adam', 'sgd'], |
| 34 | + 'Optimizer for training') |
| 35 | +flags.DEFINE_float('weight_decay', 5e-4, 'Weight for L2 regularization') |
| 36 | +flags.DEFINE_string('save_dir', 'models/cora/gcn', |
| 37 | + 'Directory stores trained model') |
| 38 | + |
| 39 | +FLAGS = flags.FLAGS |
| 40 | + |
| 41 | + |
| 42 | +def train(model, adj, features, labels, idx_train, idx_val, idx_test): |
| 43 | + """Train gnn model.""" |
| 44 | + loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) |
| 45 | + best_val_acc = 0.0 |
| 46 | + |
| 47 | + if FLAGS.optimizer == 'adam': |
| 48 | + optimizer = tf.keras.optimizers.Adam(learning_rate=FLAGS.lr) |
| 49 | + elif FLAGS.optimizer == 'sgd': |
| 50 | + optimizer = tf.keras.optimizers.SGD(learning_rate=FLAGS.lr) |
| 51 | + |
| 52 | + inputs = (features, adj) |
| 53 | + for epoch in range(FLAGS.epochs): |
| 54 | + epoch_start_time = time.time() |
| 55 | + |
| 56 | + with tf.GradientTape() as tape: |
| 57 | + output = model(inputs) |
| 58 | + train_loss = loss_fn(labels[idx_train], output[idx_train]) |
| 59 | + # L2 regularization |
| 60 | + for weight in model.trainable_weights: |
| 61 | + train_loss += FLAGS.weight_decay * tf.nn.l2_loss(weight) |
| 62 | + |
| 63 | + gradients = tape.gradient(train_loss, model.trainable_variables) |
| 64 | + optimizer.apply_gradients(zip(gradients, model.trainable_variables)) |
| 65 | + |
| 66 | + train_acc = cal_acc(labels[idx_train], output[idx_train]) |
| 67 | + |
| 68 | + # Evaluate |
| 69 | + output = model(inputs, training=False) |
| 70 | + val_loss = loss_fn(labels[idx_val], output[idx_val]) |
| 71 | + val_acc = cal_acc(labels[idx_val], output[idx_val]) |
| 72 | + |
| 73 | + if val_acc > best_val_acc: |
| 74 | + best_val_acc = val_acc |
| 75 | + model.save(FLAGS.save_dir) |
| 76 | + |
| 77 | + print('[%03d/%03d] %.2f sec(s) Train Acc: %.3f Loss: %.6f | Val Acc: %.3f loss: %.6f' % \ |
| 78 | + (epoch + 1, FLAGS.epochs, time.time()-epoch_start_time, \ |
| 79 | + train_acc, train_loss, val_acc, val_loss)) |
| 80 | + |
| 81 | + print('Start Predicting...') |
| 82 | + model = tf.keras.models.load_model(FLAGS.save_dir) |
| 83 | + output = model(inputs, training=False) |
| 84 | + test_acc = cal_acc(labels[idx_test], output[idx_test]) |
| 85 | + print('***Test Accuracy: %.3f***' % test_acc) |
| 86 | + |
| 87 | + |
| 88 | +def main(_): |
| 89 | + |
| 90 | + if FLAGS.gpu == -1: |
| 91 | + device = '/cpu:0' |
| 92 | + else: |
| 93 | + device = '/gpu:{}'.format(FLAGS.gpu) |
| 94 | + |
| 95 | + with tf.device(device): |
| 96 | + tf.random.set_seed(1234) |
| 97 | + # Load the dataset and process features and adj matrix |
| 98 | + print('Loading {} dataset...'.format(FLAGS.dataset)) |
| 99 | + adj, features, labels, idx_train, idx_val, idx_test = load_dataset( |
| 100 | + FLAGS.dataset) |
| 101 | + num_classes = max(labels) + 1 |
| 102 | + print('Build model...') |
| 103 | + model = build_model(FLAGS.model, FLAGS.num_layers, FLAGS.hidden_dim, |
| 104 | + num_classes, FLAGS.dropout_rate) |
| 105 | + print('Start Training...') |
| 106 | + train(model, adj, features, labels, idx_train, idx_val, idx_test) |
| 107 | + |
| 108 | + |
| 109 | +if __name__ == '__main__': |
| 110 | + app.run(main) |
0 commit comments