跟着官方文档学DGL框架第一天——DGL概览

主要参考:https://docs.dgl.ai/tutorials/basics/1_first.html

DGL是什么

DGL是一种用于简化图神经网络实现的包,感觉官方文档写得很亲民,打算好好拜读一下。

教程问题描述

文档先给出一个“Zachary空手道俱乐部问题”的小例子,以便熟悉DGL的基本操作。“Zachary空手道俱乐部是一个社交网络,包含34个成员及他们在俱乐部外的关系链接。俱乐部之后被分为两个分别由教练(节点0)和会长(节点33)领导的社区。”社交网络展示如下图:
在这里插入图片描述
任务是为每位成员分类,即区分他是教练这个社区的还是会长这个社区的。

第一步 用DGL构建图

来研究文档的代码:

import dgl
import numpy as np

def build_karate_club_graph():
    # All 78 edges are stored in two numpy arrays. One for source endpoints
    # while the other for destination endpoints.
    src = np.array([1, 2, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 7, 7, 7, 8, 8, 9, 10, 10,
        10, 11, 12, 12, 13, 13, 13, 13, 16, 16, 17, 17, 19, 19, 21, 21,
        25, 25, 27, 27, 27, 28, 29, 29, 30, 30, 31, 31, 31, 31, 32, 32,
        32, 32, 32, 32, 32, 32, 32, 32, 32, 33, 33, 33, 33, 33, 33, 33,
        33, 33, 33, 33, 33, 33, 33, 33, 33, 33])
    dst = np.array([0, 0, 1, 0, 1, 2, 0, 0, 0, 4, 5, 0, 1, 2, 3, 0, 2, 2, 0, 4,
        5, 0, 0, 3, 0, 1, 2, 3, 5, 6, 0, 1, 0, 1, 0, 1, 23, 24, 2, 23,
        24, 2, 23, 26, 1, 8, 0, 24, 25, 28, 2, 8, 14, 15, 18, 20, 22, 23,
        29, 30, 31, 8, 9, 13, 14, 15, 18, 19, 20, 22, 23, 26, 27, 28, 29, 30,
        31, 32])
    # Edges are directional in DGL; Make them bi-directional.
    u = np.concatenate([src, dst])
    print(u)
    v = np.concatenate([dst, src])
    # Construct a DGLGraph
    return dgl.DGLGraph((u, v))

G = build_karate_club_graph()
print('We have %d nodes.' % G.number_of_nodes())
print('We have %d edges.' % G.number_of_edges())

可以看出dgl.DGLGraph((u,v))中,u为头节点,v为尾节点。

DGL的边是有向边,但这里社交链接关系是双向的,所以既需要头节点指向尾节点的边,也需要尾节点指向头节点的边,于是将节点间的链接关系拆分为头节点和尾节点,分别存储在两个数组(src和dst),然后再按两种顺序拼接起来,让u前半部分是头节点,后半部分是尾节点,v则相反,以此实现双向的边。

可视化

这里的可视化需要networkx,先让刚才用DGLGraph构建的图转为networkx格式的无向图,然后使用nx.draw()画图。(要显示图还需要plt.show())

import networkx as nx
import matplotlib.pyplot as plt
# Since the actual graph is undirected, we convert it for visualization
# purpose.
nx_G = G.to_networkx().to_undirected()
# Kamada-Kawaii layout usually looks pretty for arbitrary graphs
pos = nx.kamada_kawai_layout(nx_G)

nx.draw(nx_G, pos, with_labels=True, node_color=[[.7, .7, .7]])
plt.show()

在这里插入图片描述
这里的’nx.kamada_kawai_layout’为布局设置,即画风。还有以下几种可选择:

circular_layout:节点在一个圆环上均匀分布
random_layout:节点随机分布
shell_layout:节点在同心圆上分布
spring_layout: 用Fruchterman-Reingold算法排列节点(样子类似多中心放射状)
spectral_layout:根据图的拉普拉斯特征向量排列节点

第二步 为点分配特征

由于没有输入特征,所以为34个节点初始化了一个5维embedding作为特征(embed)。

从’G.ndata[‘feat’] = embed.weight’可以看出,DGL为为节点一次性传入特征,'feat’是特征的名称,如果节点有多种特征,需要通过名称区分。

# In DGL, you can add features for all nodes at once, using a feature tensor that
# batches node features along the first dimension. The code below adds the learnable
# embeddings for all nodes:

import torch
import torch.nn as nn
import torch.nn.functional as F

embed = nn.Embedding(34, 5)  # 34 nodes with embedding dim equal to 5
G.ndata['feat'] = embed.weight

第三歩 定义图卷积神经网络(GCN)

这里使用了最简单的GCN的定义。聚合节点邻居的特征,然后通过非线性变换作为当前节点的新特征。
在这里插入图片描述
强大的DGL已经实现流行的GCN层,直接像CNN一样调用即可。

from dgl.nn.pytorch import GraphConv
class GCN(nn.Module):
    def __init__(self, in_feats, hidden_size, num_classes):
        super(GCN, self).__init__()
        self.conv1 = GraphConv(in_feats, hidden_size)
        self.conv2 = GraphConv(hidden_size, num_classes)

    def forward(self, g, inputs):
        h = self.conv1(g, inputs)
        h = torch.relu(h)
        h = self.conv2(g, h)
        return h

# The first layer transforms input features of size of 5 to a hidden size of 5.
# The second layer transforms the hidden layer and produces output features of
# size 2, corresponding to the two groups of the karate club.
net = GCN(5, 5, 2)

第四歩 数据准备和初始化

这是一个半监督的分类任务,只有教练节点(节点0)和会长节点(节点33)分别有标签0和1。
inputs = embed.weight
labeled_nodes = torch.tensor([0, 33]) # only the instructor and the president nodes are labeled
labels = torch.tensor([0, 1]) # their labels are different

第五歩 训练并可视化结果

训练步骤与传统pytorch完全一样:
1)构建优化器。这里使用了Adam优化器,训练的参数有网络中GraphConv层的参数和节点的embedding。
2)向模型输入数据
3)计算loss
4)迭代更新
注意F.log_softmax()与F.nll_loss()搭配使用

import itertools

optimizer = torch.optim.Adam(itertools.chain(net.parameters(), embed.parameters()), lr=0.01)
all_logits = []
for epoch in range(50):
    logits = net(G, inputs)
    # we save the logits for visualization later
    all_logits.append(logits.detach())
    logp = F.log_softmax(logits, 1)
    # we only 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()))

为了可视化保存了每个epoch的每个节点的logits,作为2D图上的坐标使用。

可视化

用logits作为坐标,画图。这里用了nx.draw_networkx(),感觉跟nx.draw()没啥区别。

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)

fig = plt.figure(dpi=150)
fig.clf()
ax = fig.subplots()
draw(0)  # draw the prediction of the first epoch
plt.show()

最后是以动画的形式展示训练过程:

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

在这里插入图片描述

  • 23
    点赞
  • 104
    收藏
    觉得还不错? 一键收藏
  • 10
    评论
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值