|
| 1 | +# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved |
| 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 | +# http://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 | +#-*- coding: utf-8 -*- |
| 15 | +import pgl |
| 16 | +from pgl import data_loader |
| 17 | +from pgl.utils.logger import log |
| 18 | +import paddle.fluid as fluid |
| 19 | +import numpy as np |
| 20 | +import time |
| 21 | +import argparse |
| 22 | +from pgl.utils.log_writer import LogWriter # vdl |
| 23 | +from model import DeeperGCN |
| 24 | + |
| 25 | +def load(name): |
| 26 | + if name == 'cora': |
| 27 | + dataset = data_loader.CoraDataset() |
| 28 | + elif name == "pubmed": |
| 29 | + dataset = data_loader.CitationDataset("pubmed", symmetry_edges=False) |
| 30 | + elif name == "citeseer": |
| 31 | + dataset = data_loader.CitationDataset("citeseer", symmetry_edges=False) |
| 32 | + else: |
| 33 | + raise ValueError(name + " dataset doesn't exists") |
| 34 | + return dataset |
| 35 | + |
| 36 | + |
| 37 | +def main(args): |
| 38 | + # vdl |
| 39 | + writer = LogWriter("checkpoints/train_history") |
| 40 | + |
| 41 | + dataset = load(args.dataset) |
| 42 | + place = fluid.CUDAPlace(0) if args.use_cuda else fluid.CPUPlace() |
| 43 | + train_program = fluid.Program() |
| 44 | + startup_program = fluid.Program() |
| 45 | + test_program = fluid.Program() |
| 46 | + hidden_size = 64 |
| 47 | + num_layers = 7 |
| 48 | + |
| 49 | + with fluid.program_guard(train_program, startup_program): |
| 50 | + gw = pgl.graph_wrapper.GraphWrapper( |
| 51 | + name="graph", |
| 52 | + node_feat=dataset.graph.node_feat_info()) |
| 53 | + |
| 54 | + output = DeeperGCN(gw, |
| 55 | + gw.node_feat["words"], |
| 56 | + num_layers, |
| 57 | + hidden_size, |
| 58 | + dataset.num_classes, |
| 59 | + "deepercnn", |
| 60 | + 0.1) |
| 61 | + |
| 62 | + node_index = fluid.layers.data( |
| 63 | + "node_index", |
| 64 | + shape=[None, 1], |
| 65 | + dtype="int64", |
| 66 | + append_batch_size=False) |
| 67 | + node_label = fluid.layers.data( |
| 68 | + "node_label", |
| 69 | + shape=[None, 1], |
| 70 | + dtype="int64", |
| 71 | + append_batch_size=False) |
| 72 | + |
| 73 | + pred = fluid.layers.gather(output, node_index) |
| 74 | + loss, pred = fluid.layers.softmax_with_cross_entropy( |
| 75 | + logits=pred, label=node_label, return_softmax=True) |
| 76 | + acc = fluid.layers.accuracy(input=pred, label=node_label, k=1) |
| 77 | + loss = fluid.layers.mean(loss) |
| 78 | + |
| 79 | + test_program = train_program.clone(for_test=True) |
| 80 | + with fluid.program_guard(train_program, startup_program): |
| 81 | + adam = fluid.optimizer.Adam( |
| 82 | + regularization=fluid.regularizer.L2DecayRegularizer( |
| 83 | + regularization_coeff=0.0005), |
| 84 | + learning_rate=0.005) |
| 85 | + adam.minimize(loss) |
| 86 | + |
| 87 | + exe = fluid.Executor(place) |
| 88 | + exe.run(startup_program) |
| 89 | + |
| 90 | + feed_dict = gw.to_feed(dataset.graph) |
| 91 | + |
| 92 | + train_index = dataset.train_index |
| 93 | + train_label = np.expand_dims(dataset.y[train_index], -1) |
| 94 | + train_index = np.expand_dims(train_index, -1) |
| 95 | + |
| 96 | + val_index = dataset.val_index |
| 97 | + val_label = np.expand_dims(dataset.y[val_index], -1) |
| 98 | + val_index = np.expand_dims(val_index, -1) |
| 99 | + |
| 100 | + test_index = dataset.test_index |
| 101 | + test_label = np.expand_dims(dataset.y[test_index], -1) |
| 102 | + test_index = np.expand_dims(test_index, -1) |
| 103 | + |
| 104 | + # get beta param |
| 105 | + beta_param_list = [] |
| 106 | + for param in fluid.io.get_program_parameter(train_program): |
| 107 | + if param.name.endswith("_beta"): |
| 108 | + beta_param_list.append(param) |
| 109 | + |
| 110 | + dur = [] |
| 111 | + for epoch in range(200): |
| 112 | + if epoch >= 3: |
| 113 | + t0 = time.time() |
| 114 | + feed_dict["node_index"] = np.array(train_index, dtype="int64") |
| 115 | + feed_dict["node_label"] = np.array(train_label, dtype="int64") |
| 116 | + train_loss, train_acc = exe.run(train_program, |
| 117 | + feed=feed_dict, |
| 118 | + fetch_list=[loss, acc], |
| 119 | + return_numpy=True) |
| 120 | + for param in beta_param_list: |
| 121 | + beta = np.array(fluid.global_scope().find_var(param.name).get_tensor()) |
| 122 | + writer.add_scalar("beta/"+param.name, beta, epoch) |
| 123 | + |
| 124 | + if epoch >= 3: |
| 125 | + time_per_epoch = 1.0 * (time.time() - t0) |
| 126 | + dur.append(time_per_epoch) |
| 127 | + |
| 128 | + feed_dict["node_index"] = np.array(val_index, dtype="int64") |
| 129 | + feed_dict["node_label"] = np.array(val_label, dtype="int64") |
| 130 | + val_loss, val_acc = exe.run(test_program, |
| 131 | + feed=feed_dict, |
| 132 | + fetch_list=[loss, acc], |
| 133 | + return_numpy=True) |
| 134 | + |
| 135 | + log.info("Epoch %d " % epoch + "(%.5lf sec) " % np.mean(dur) + |
| 136 | + "Train Loss: %f " % train_loss + "Train Acc: %f " % train_acc |
| 137 | + + "Val Loss: %f " % val_loss + "Val Acc: %f " % val_acc) |
| 138 | + |
| 139 | + feed_dict["node_index"] = np.array(test_index, dtype="int64") |
| 140 | + feed_dict["node_label"] = np.array(test_label, dtype="int64") |
| 141 | + test_loss, test_acc = exe.run(test_program, |
| 142 | + feed=feed_dict, |
| 143 | + fetch_list=[loss, acc], |
| 144 | + return_numpy=True) |
| 145 | + log.info("Accuracy: %f" % test_acc) |
| 146 | + |
| 147 | + |
| 148 | +if __name__ == '__main__': |
| 149 | + parser = argparse.ArgumentParser(description='DeeperGCN') |
| 150 | + parser.add_argument( |
| 151 | + "--dataset", type=str, default="cora", help="dataset (cora, pubmed)") |
| 152 | + parser.add_argument("--use_cuda", action='store_true', help="use_cuda") |
| 153 | + args = parser.parse_args() |
| 154 | + log.info(args) |
| 155 | + main(args) |
0 commit comments