PyTorch实现简单的图神经网络

原文首发于个人站点 基于PyTorch-DGL 实现图卷积网络 | 梦家


更新:
在此附上图卷积网络GCN理论篇:


基于PyTorch框架实现图卷积神经网络

项目源代码参考本人Github.

依赖库

  • DGL 0.1.3
  • PyTorch 0.4.1
  • networkX 2.2

利用DGL构建图

# -*- coding: utf-8 -*-

"""
@Date: 2019/1/11

@Author: dreamhome

@Summary:  DGL graph.
"""
import dgl
import torch
import networkx as nx

import matplotlib.pyplot as plt


def build_karate_club_graph():
    g = dgl.DGLGraph()
    # add 34 nodes into the graph; nodes are labeled from 0~33
    g.add_nodes(34)
    # all 78 edges as a list of tuples
    edge_list = [(1, 0), (2, 0), (2, 1), (3, 0), (3, 1), (3, 2),
                 (4, 0), (5, 0), (6, 0), (6, 4), (6, 5), (7, 0), (7, 1),
                 (7, 2), (7, 3), (8, 0), (8, 2), (9, 2), (10, 0), (10, 4),
                 (10, 5), (11, 0), (12, 0), (12, 3), (13, 0), (13, 1), (13, 2),
                 (13, 3), (16, 5), (16, 6), (17, 0), (17, 1), (19, 0), (19, 1),
                 (21, 0), (21, 1), (25, 23), (25, 24), (27, 2), (27, 23),
                 (27, 24), (28, 2), (29, 23), (29, 26), (30, 1), (30, 8),
                 (31, 0), (31, 24), (31, 25), (31, 28), (32, 2), (32, 8),
                 (32, 14), (32, 15), (32, 18), (32, 20), (32, 22), (32, 23),
                 (32, 29), (32, 30), (32, 31), (33, 8), (33, 9), (33, 13),
                 (33, 14), (33, 15), (33, 18), (33, 19), (33, 20), (33, 22),
                 (33, 23), (33, 26), (33, 27), (33, 28), (33, 29), (33, 30),
                 (33, 31), (33, 32)]
    # add edges two lists of nodes: src and dst
    src, dst = tuple(zip(*edge_list))
    g.add_edges(src, dst)
    # edges are directional in DGL; make them bi-directional
    g.add_edges(dst, src)

    return g


if __name__ == '__main__':
    G = build_karate_club_graph()
    print('%d nodes.' % G.number_of_nodes())
    print('%d edges.' % G.number_of_edges())

    fig, ax = plt.subplots()
    fig.set_tight_layout(False)
    nx_G = G.to_networkx().to_undirected()
    pos = nx.kamada_kawai_layout(nx_G)
    nx.draw(nx_G, pos, with_labels=True, node_color=[[0.5, 0.5, 0.5]])
    plt.show()

    # assign features to nodes or edges
    G.ndata['feat'] = torch.eye(34)
    print(G.nodes[2].data['feat'])
    print(G.nodes[1, 2].data['feat'])

构建图卷积神经网络

# -*- coding: utf-8 -*-

"""
@Date: 2019/1/14

@Author: dreamhome

@Summary: define a Graph Convolutional Network (GCN)
"""
import torch
import torch.nn as nn


def gcn_message(edges):
    """
    compute a batch of message called 'msg' using the source nodes' feature 'h'
    :param edges:
    :return:
    """
    return {'msg': edges.src['h']}


def gcn_reduce(nodes):
    """
    compute the new 'h' features by summing received 'msg' in each node's mailbox.
    :param nodes:
    :return:
    """
    return {'h': torch.sum(nodes.mailbox['msg'], dim=1)}


class GCNLayer(nn.Module):
    """
    Define the GCNLayer module.
    """

    def __init__(self, in_feats, out_feats):
        super(GCNLayer, self).__init__()
        self.linear = nn.Linear(in_feats, out_feats)

    def forward(self, g, inputs):
        # g is the graph and the inputs is the input node features
        # first set the node features
        g.ndata['h'] = inputs
        # trigger message passing on all edges
        g.send(g.edges(), gcn_message)
        # trigger aggregation at all nodes
        g.recv(g.nodes(), gcn_reduce)
        # get the result node features
        h = g.ndata.pop('h')
        # perform linear transformation
        return self.linear(h)


class GCN(nn.Module):
    """
    Define a 2-layer GCN model.
    """
    def __init__(self, in_feats, hidden_size, num_classes):
        super(GCN, self).__init__()
        self.gcn1 = GCNLayer(in_feats, hidden_size)
        self.gcn2 = GCNLayer(hidden_size, num_classes)

    def forward(self, g, inputs):
        h = self.gcn1(g, inputs)
        h = torch.relu(h)
        h = self.gcn2(g, h)
        return h


if __name__ == '__main__':
    net = GCN(34, 5, 2)

训练过程

# -*- coding: utf-8 -*-

"""
@Date: 2019/1/14

@Author: dreamhome

@Summary: train  semi-supervised setting
"""
import torch
import torch.nn.functional as F

import networkx as nx
import matplotlib.animation as animation
import matplotlib.pyplot as plt

from model import GCN
from build_graph import build_karate_club_graph

import warnings
warnings.filterwarnings('ignore')


net = GCN(34, 5, 2)
print(net)
G = build_karate_club_graph()

inputs = torch.eye(34)
labeled_nodes = torch.tensor([0, 33])  # only the instructor and the president nodes are labeled
labels = torch.tensor([0, 1])

optimizer = torch.optim.Adam(net.parameters(), lr=0.01)
all_logits = []

for epoch in range(20):
    logits = net(G, inputs)
    all_logits.append(logits.detach())
    logp = F.log_softmax(logits, 1)

    # compute loss for labeled nodes
    loss = F.nll_loss(logp[labeled_nodes], labels)

    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

    print('Epoch %d | Loss: %.4f' % (epoch, loss.item()))


def draw(i):
    cls1color = '#00FFFF'
    cls2color = '#FF00FF'
    pos = {}
    colors = []
    for v in range(34):
        pos[v] = all_logits[i][v].numpy()
        cls = pos[v].argmax()
        colors.append(cls1color if cls else cls2color)
    ax.cla()
    # ax.axis('off')
    ax.set_title('Epoch: %d' % i)
    nx.draw_networkx(nx_G.to_undirected(), pos, node_color=colors, with_labels=True, node_size=300, ax=ax)


nx_G = G.to_networkx().to_undirected()
fig = plt.figure(dpi=150)
fig.clf()
ax = fig.subplots()
# draw(1)  # draw the prediction of the first epoch

ani = animation.FuncAnimation(fig, draw, frames=len(all_logits), interval=200)
plt.show()

训练过程可视化

在这里插入图片描述

项目参考:教程

  • 30
    点赞
  • 223
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
### 回答1: Graph Neural Network(GNN)是一种神经网络,能够处理输入数据为的情况。PyTorch是一个非常流行的深度学习框架,可以用来实现GNN。 在PyTorch中,可以使用dgl(Deep Graph Library)来实现GNN。首先,需要将数据转化为dgl的Graph对象,并对Graph对象进行一些预处理。然后,可以定义模型的网络结构,包括使用不同类型的层、激活函数等。最后,将数据输入模型,并对模型进行训练或测试。下面是一个基本的PyTorch GNN代码框架: import dgl import torch import torch.nn as nn class GNN(nn.Module): def __init__(self, in_dim, hidden_dim, out_dim, n_layers): super(GNN, self).__init__() self.layers = nn.ModuleList() self.layers.append(nn.Linear(in_dim, hidden_dim)) for i in range(n_layers - 2): self.layers.append(nn.Linear(hidden_dim, hidden_dim)) self.layers.append(nn.Linear(hidden_dim, out_dim)) def forward(self, g): h = g.ndata['feature'] for i, layer in enumerate(self.layers): h = layer(g, h) if i != len(self.layers) - 1: h = nn.functional.relu(h) return h # create graph g = dgl.DGLGraph() g.add_nodes(num_nodes) g.add_edges(u, v) # prepare data g.ndata['feature'] = feature g.ndata['label'] = label # create model model = GNN(in_dim, hidden_dim, out_dim, n_layers) # train model optimizer = torch.optim.Adam(model.parameters()) criterion = nn.CrossEntropyLoss() for epoch in range(num_epochs): optimizer.zero_grad() logits = model(g) loss = criterion(logits, g.ndata['label']) loss.backward() optimizer.step() # test model model.eval() with torch.no_grad(): logits = model(g) result = compute_result(logits, g.ndata['label']) 这个代码框架可以用于实现很多不同类型的GNN,包括GCN、GAT、GraphSAGE等。要根据具体情况调整模型的参数和架构,以获得最好的结果。 ### 回答2: PyTorch是一个开源的机器学习库,它提供了很多实现深度学习模型的工具,包括神经网络GNN)。对于GNNPyTorch的DGL库是非常好的选择。DGL是一个用于神经网络的Python库,由华盛顿大学、纽约大学和北京大学开发。它提供了灵活的API,可以用于实现各种类型的神经网络模型,包括GCN、GAT、GraphSAGE等。 在使用DGL实现GNN时,首先需要构建一个Python类来定义模型。这个类应该继承自DGL中的GraphConv模块,并在__init__函数中定义卷积层(GraphConv),并定义forward函数。forward函数中需要将连通性和节点特征传递给卷积层,并将结果返回。 代码示例: ```python import torch import dgl import dgl.function as fn import torch.nn as nn import torch.nn.functional as F class GCN(nn.Module): def __init__(self, in_feats, h_feats, num_classes): super(GCN, self).__init__() self.conv1 = dgl.nn.GraphConv(in_feats, h_feats) self.conv2 = dgl.nn.GraphConv(h_feats, num_classes) def forward(self, g, inputs): h = self.conv1(g, inputs) h = F.relu(h) h = self.conv2(g, h) return h ``` 上面的代码定义了一个简单的两层GCN模型,输入特征的维度为in_feats,输出特征的维度为num_classes,隐藏层的维度为h_feats。 在构建模型之后,我们需要使用PyTorch的DataLoader来将数据加载到我们的模型中。在将数据加载到模型中后,我们可以使用PyTorch自带的优化器来训练我们的模型。模型的训练过程和其他深度学习模型的训练过程相似,唯一的区别是我们需要考虑结构。 需要注意的是,在结构不变的情况下,我们可以将节点特征和边权重存储在DGL数据结构中,这不仅可以加快计算过程,还可以更好地利用GPU进行并行计算。如果结构发生了变化,我们需要重新构建结构并进行计算。 总之,在使用PyTorch实现GNN时,我们可以使用DGL库来简化模型的实现和数据的处理。通过Python的面向对象编程,可以方便地对节点和边进行操作,并使用PyTorch的自动微分功能进行模型训练。 ### 回答3: 神经网络GNN)是一种用于处理数据的深度学习模型。随着近年来数据的广泛应用,神经网络也越来越受到关注。PyTorch是一种广泛使用的深度学习框架,其灵活性和易用性使其成为实现GNN模型的优秀选择。 以下是一个基于PyTorch实现GNN代码示例: ```python import torch import torch.nn as nn import torch.optim as optim class GraphConvLayer(nn.Module): def __init__(self, input_dim, output_dim): super(GraphConvLayer, self).__init__() self.linear = nn.Linear(input_dim, output_dim) def forward(self, X, A): X = self.linear(X) X = torch.matmul(A, X) return X class GraphNet(nn.Module): def __init__(self, input_dim, hidden_dim, output_dim): super(GraphNet, self).__init__() self.conv1 = GraphConvLayer(input_dim, hidden_dim) self.conv2 = GraphConvLayer(hidden_dim, hidden_dim) self.linear = nn.Linear(hidden_dim, output_dim) def forward(self, X, A): X = self.conv1(X, A) X = torch.relu(X) X = self.conv2(X, A) X = torch.relu(X) X = self.linear(X) return X # 构造模型和数据 input_dim = 10 hidden_dim = 16 output_dim = 2 model = GraphNet(input_dim, hidden_dim, output_dim) X = torch.randn(32, input_dim) A = torch.randn(32, 32) # 定义损失函数和优化器 criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(model.parameters()) # 训练模型 for epoch in range(100): optimizer.zero_grad() output = model(X, A) loss = criterion(output, target) loss.backward() optimizer.step() # 测试模型 X_test = torch.randn(16, input_dim) A_test = torch.randn(16, 16) output_test = model(X_test, A_test) ``` 上面的代码实现了一个有两个GraphConvLayer层的GNN模型。模型输入为一个特征矩阵X和邻接矩阵A,输出为一个预测标签。在训练过程中使用交叉熵损失函数和Adam优化器来优化模型。在测试时,可以使用新的输入和邻接矩阵来进行预测。 需要注意的是,该示例仅仅是个简单示例,实际的GNN模型可能更加复杂并具有更强的表达能力。因此,为了训练高质量的GNN模型,还需要加强对数据和深度学习的理解,并熟练使用PyTorch等深度学习框架。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值