main_pgl.py 9.4 KB
Newer Older
L
liweibin 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""test ogb
"""
import argparse
W
Webbley 已提交
17 18
import time
import logging
L
liweibin 已提交
19
import numpy as np
W
Webbley 已提交
20

L
liweibin 已提交
21
import paddle.fluid as fluid
W
Webbley 已提交
22 23

import pgl
L
liweibin 已提交
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
from pgl.contrib.ogb.linkproppred.dataset_pgl import PglLinkPropPredDataset
from pgl.utils import paddle_helper
from ogb.linkproppred import Evaluator


def send_func(src_feat, dst_feat, edge_feat):
    """send_func"""
    return src_feat["h"]


def recv_func(feat):
    """recv_func"""
    return fluid.layers.sequence_pool(feat, pool_type="sum")


class GNNModel(object):
    """GNNModel"""

    def __init__(self, name, num_nodes, emb_dim, num_layers):
        self.num_nodes = num_nodes
        self.emb_dim = emb_dim
        self.num_layers = num_layers
        self.name = name

        self.src_nodes = fluid.layers.data(
            name='src_nodes',
W
Webbley 已提交
50
            shape=[None],
L
liweibin 已提交
51 52 53 54
            dtype='int64', )

        self.dst_nodes = fluid.layers.data(
            name='dst_nodes',
W
Webbley 已提交
55
            shape=[None],
L
liweibin 已提交
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
            dtype='int64', )

        self.edge_label = fluid.layers.data(
            name='edge_label',
            shape=[None, 1],
            dtype='float32', )

    def forward(self, graph):
        """forward"""
        h = fluid.layers.create_parameter(
            shape=[self.num_nodes, self.emb_dim],
            dtype="float32",
            name=self.name + "_embedding")

        for layer in range(self.num_layers):
            msg = graph.send(
                send_func,
                nfeat_list=[("h", h)], )
            h = graph.recv(msg, recv_func)
            h = fluid.layers.fc(
                h,
                size=self.emb_dim,
                bias_attr=False,
                param_attr=fluid.ParamAttr(name=self.name + '_%s' % layer))
            h = h * graph.node_feat["norm"]
            bias = fluid.layers.create_parameter(
                shape=[self.emb_dim],
                dtype='float32',
                is_bias=True,
                name=self.name + '_bias_%s' % layer)
            h = fluid.layers.elementwise_add(h, bias, act="relu")

W
Webbley 已提交
88 89
        src = fluid.layers.gather(h, self.src_nodes, overwrite=False)
        dst = fluid.layers.gather(h, self.dst_nodes, overwrite=False)
L
liweibin 已提交
90 91 92 93 94 95 96 97 98
        edge_embed = src * dst
        pred = fluid.layers.fc(input=edge_embed,
                               size=1,
                               name=self.name + "_pred_output")

        prob = fluid.layers.sigmoid(pred)

        loss = fluid.layers.sigmoid_cross_entropy_with_logits(pred,
                                                              self.edge_label)
W
Webbley 已提交
99
        loss = fluid.layers.reduce_sum(loss)
L
liweibin 已提交
100 101 102 103 104 105 106 107 108 109 110 111

        return pred, prob, loss


def main():
    """main
    """
    # Training settings
    parser = argparse.ArgumentParser(description='Graph Dataset')
    parser.add_argument(
        '--epochs',
        type=int,
W
Webbley 已提交
112
        default=4,
L
liweibin 已提交
113 114 115 116 117 118
        help='number of epochs to train (default: 100)')
    parser.add_argument(
        '--dataset',
        type=str,
        default="ogbl-ppa",
        help='dataset name (default: protein protein associations)')
W
Webbley 已提交
119 120 121 122 123
    parser.add_argument('--use_cuda', action='store_true')
    parser.add_argument('--batch_size', type=int, default=5120)
    parser.add_argument('--embed_dim', type=int, default=64)
    parser.add_argument('--num_layers', type=int, default=2)
    parser.add_argument('--lr', type=float, default=0.001)
L
liweibin 已提交
124
    args = parser.parse_args()
W
Webbley 已提交
125
    print(args)
L
liweibin 已提交
126

W
Webbley 已提交
127
    place = fluid.CUDAPlace(0) if args.use_cuda else fluid.CPUPlace()
L
liweibin 已提交
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144

    ### automatic dataloading and splitting
    print("loadding dataset")
    dataset = PglLinkPropPredDataset(name=args.dataset)
    splitted_edge = dataset.get_edge_split()
    print(splitted_edge['train_edge'].shape)
    print(splitted_edge['train_edge_label'].shape)

    print("building evaluator")
    ### automatic evaluator. takes dataset name as input
    evaluator = Evaluator(args.dataset)

    graph_data = dataset[0]
    print("num_nodes: %d" % graph_data.num_nodes)

    train_program = fluid.Program()
    startup_program = fluid.Program()
W
Webbley 已提交
145

L
liweibin 已提交
146 147 148 149 150
    # degree normalize
    indegree = graph_data.indegree()
    norm = np.zeros_like(indegree, dtype="float32")
    norm[indegree > 0] = np.power(indegree[indegree > 0], -0.5)
    graph_data.node_feat["norm"] = np.expand_dims(norm, -1).astype("float32")
W
Webbley 已提交
151
    #  graph_data.node_feat["index"] = np.array([i for i in range(graph_data.num_nodes)], dtype=np.int64).reshape(-1,1)
L
liweibin 已提交
152 153 154 155 156

    with fluid.program_guard(train_program, startup_program):
        model = GNNModel(
            name="gnn",
            num_nodes=graph_data.num_nodes,
W
Webbley 已提交
157 158
            emb_dim=args.embed_dim,
            num_layers=args.num_layers)
L
liweibin 已提交
159 160 161 162 163 164 165 166 167 168
        gw = pgl.graph_wrapper.GraphWrapper(
            "graph",
            place,
            node_feat=graph_data.node_feat_info(),
            edge_feat=graph_data.edge_feat_info())
        pred, prob, loss = model.forward(gw)

    val_program = train_program.clone(for_test=True)

    with fluid.program_guard(train_program, startup_program):
W
Webbley 已提交
169 170 171 172 173
        global_steps = int(splitted_edge['train_edge'].shape[0] /
                           args.batch_size * 2)
        learning_rate = fluid.layers.polynomial_decay(args.lr, global_steps,
                                                      0.00005)

L
liweibin 已提交
174
        adam = fluid.optimizer.Adam(
W
Webbley 已提交
175
            learning_rate=learning_rate,
L
liweibin 已提交
176 177 178 179 180 181 182
            regularization=fluid.regularizer.L2DecayRegularizer(
                regularization_coeff=0.0005))
        adam.minimize(loss)

    exe = fluid.Executor(place)
    exe.run(startup_program)
    feed = gw.to_feed(graph_data)
W
Webbley 已提交
183 184 185 186 187 188 189

    print("evaluate result before training: ")
    result = test(exe, val_program, prob, evaluator, feed, splitted_edge)
    print(result)

    print("training")
    cc = 0
L
liweibin 已提交
190
    for epoch in range(1, args.epochs + 1):
W
Webbley 已提交
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
        for batch_data, batch_label in data_generator(
                graph_data,
                splitted_edge["train_edge"],
                splitted_edge["train_edge_label"],
                batch_size=args.batch_size):
            feed['src_nodes'] = batch_data[:, 0].reshape(-1, 1)
            feed['dst_nodes'] = batch_data[:, 1].reshape(-1, 1)
            feed['edge_label'] = batch_label.astype("float32")

            res_loss, y_pred, b_lr = exe.run(
                train_program,
                feed=feed,
                fetch_list=[loss, prob, learning_rate])
            if cc % 1 == 0:
                print("epoch %d | step %d | lr %s | Loss %s" %
                      (epoch, cc, b_lr[0], res_loss[0]))
            cc += 1

            if cc % 20 == 0:
                print("Evaluating...")
                result = test(exe, val_program, prob, evaluator, feed,
                              splitted_edge)
                print("epoch %d | step %d" % (epoch, cc))
                print(result)


def test(exe, val_program, prob, evaluator, feed, splitted_edge):
    """Evaluation"""
    result = {}
    feed['src_nodes'] = splitted_edge["valid_edge"][:, 0].reshape(-1, 1)
    feed['dst_nodes'] = splitted_edge["valid_edge"][:, 1].reshape(-1, 1)
    feed['edge_label'] = splitted_edge["valid_edge_label"].astype(
        "float32").reshape(-1, 1)
    y_pred = exe.run(val_program, feed=feed, fetch_list=[prob])[0]
    input_dict = {
W
Webbley 已提交
226 227 228 229
        "y_pred_pos":
        y_pred[splitted_edge["valid_edge_label"] == 1].reshape(-1, ),
        "y_pred_neg":
        y_pred[splitted_edge["valid_edge_label"] == 0].reshape(-1, )
W
Webbley 已提交
230 231 232 233 234 235 236 237 238
    }
    result["valid"] = evaluator.eval(input_dict)

    feed['src_nodes'] = splitted_edge["test_edge"][:, 0].reshape(-1, 1)
    feed['dst_nodes'] = splitted_edge["test_edge"][:, 1].reshape(-1, 1)
    feed['edge_label'] = splitted_edge["test_edge_label"].astype(
        "float32").reshape(-1, 1)
    y_pred = exe.run(val_program, feed=feed, fetch_list=[prob])[0]
    input_dict = {
W
Webbley 已提交
239 240 241 242
        "y_pred_pos":
        y_pred[splitted_edge["test_edge_label"] == 1].reshape(-1, ),
        "y_pred_neg":
        y_pred[splitted_edge["test_edge_label"] == 0].reshape(-1, )
W
Webbley 已提交
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
    }
    result["test"] = evaluator.eval(input_dict)
    return result


def data_generator(graph, data, label_data, batch_size, shuffle=True):
    """Data Generator"""
    perm = np.arange(0, len(data))
    if shuffle:
        np.random.shuffle(perm)

    offset = 0
    while offset < len(perm):
        batch_index = perm[offset:(offset + batch_size)]
        offset += batch_size
        pos_data = data[batch_index]
        pos_label = label_data[batch_index]

        neg_src_node = pos_data[:, 0]
        neg_dst_node = np.random.choice(
            pos_data.reshape(-1, ), size=len(neg_src_node))
        neg_data = np.hstack(
            [neg_src_node.reshape(-1, 1), neg_dst_node.reshape(-1, 1)])
        exists = graph.has_edges_between(neg_src_node, neg_dst_node)
        neg_data = neg_data[np.invert(exists)]
        neg_label = np.zeros(shape=len(neg_data), dtype=np.int64)

        batch_data = np.vstack([pos_data, neg_data])
        label = np.vstack([pos_label.reshape(-1, 1), neg_label.reshape(-1, 1)])
        yield batch_data, label
L
liweibin 已提交
273 274 275 276


if __name__ == "__main__":
    main()