第三周.01.DGL应用介绍

文章目录


本文内容整理自深度之眼《GNN核心能力培养计划》

补充知识:交叉熵

这块知识其他课程里面有,核心就是交叉熵有两种形式,一种是原始的形式,一种是用log_softmax和nll_loss来完成交叉熵计算。
具体说明可以参考这里。
例子中的class对应的是索引2维度。

karate可视化by DGL

karate数据集,可以在 https://github.com/aditya-grover/node2vec/ 上下载。DGL里面带有这个数据集,这个数据集含有34个点,代表一个俱乐部的34个成员,成员之间如果在俱乐部之外有联系,则有边链接两个节点(78条)。
第三周.01.DGL应用介绍
上图中0号是instructor(教练?),33号是俱乐部的主席(president),二者边都相对密集一些。黄色和红色也分别代表俱乐部里面两种身份。

1.建图

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.
    # 上下各有78个元素,每个位置的元素分别对应边起点和终点
    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])
    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())

结果:
We have 34 nodes.
We have 156 edges.无向图=边数×2
由于networkx是图可视化常用的包,因此,DGL提供了将图转化为networkx的接口:

import networkx as nx
# Since the actual graph is undirected, we convert it for visualization purpose.
# https://docs.dgl.ai/en/0.6.x/generated/dgl.to_networkx.html
# networkx支持无向图,因此转化的时候要注意指定无向图
nx_G = G.to_networkx().to_undirected()
# Kamada-Kawaii layout usually looks pretty for arbitrary graphs
# Kamada-Kawaii不知道啥意思,但是Kawaii 卡哇伊都应该明白。。。
pos = nx.kamada_kawai_layout(nx_G)
# 设置显示label和颜色
nx.draw(nx_G, pos, with_labels=True, node_color=[[.7, .7, .7]])

结果:
第三周.01.DGL应用介绍

2. 设置特征

按常规套路,要根据节点或者边的属性来做一把特征工程,但是这个数据集里面貌似没有属性,这里就可以随意弄个5维的向量随机初始化。当然如果节点和文字有关,可以用预训练模型的结果来初始化向量。

# 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

# 一次初始化34个结点
embed = nn.Embedding(34, 5)  # 34 nodes with embedding dim equal to 5
# 然后丢进图的ndata字典
G.ndata['feat'] = embed.weight

打印验证特征:

# print out node 2's input feature
print(G.ndata['feat'][2])

# print out node 10 and 11's input features
print(G.ndata['feat'][[10, 11]])

tensor([-0.9475, -1.3200, -0.6651, -2.1578, -0.7142], grad_fn=)
tensor([[-0.9597, -0.4622, 0.6970, 0.0271, -0.6930],
[ 0.2889, -1.0445, 1.3782, 0.9861, 1.4973]],
grad_fn=)

定义GCN模型

这里注意,GCN在做消息传递的时候要拼接节点本身的信息。
再复习一下定义模型套路:
1.自定义卷积层或者使用DGL自带的卷积层对模型进行初始化(init,注意维度);
2.定义模型结构(forward,注意层数);

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.
# 输入维度是刚才随机初始化的5维,中间层维度是5,最后是二分类,所以输出维度是2.这句话应该放训练那里更加合适
net = GCN(5, 5, 2)

数据初始化

这里有ground truth的只有两个节点,分别是0和33.

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

模型训练及结果可视化

训练

训练套路:
1.创建优化器,通常是Adam
2.丢训练数据
3.计算Loss
4.反向传播更新模型参数

import itertools

# 1.创建优化器
optimizer = torch.optim.Adam(itertools.chain(net.parameters(), embed.parameters()), lr=0.01)
all_logits = []#全局变量,保存每个epoch的每个节点的预测结果
for epoch in range(50):
	# 2.丢训练数据
    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
    # 3.计算Loss
    loss = F.nll_loss(logp[labeled_nodes], labels)

	# 4.反向传播更新模型参数
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

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

第三周.01.DGL应用介绍

可视化

每次可以画一个epoch的结果,当然后面可以用动画的方式进行展示

import matplotlib.animation as animation
import matplotlib.pyplot as plt

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()
plt.close()

第三周.01.DGL应用介绍
第三周.01.DGL应用介绍
第三周.01.DGL应用介绍
第三周.01.DGL应用介绍
第三周.01.DGL应用介绍
第三周.01.DGL应用介绍
为什么排布好难看。。。估计要设置layout

nx.draw_networkx前面加卡哇伊就好了,最终形态:
第三周.01.DGL应用介绍

上一篇:2021-06-18线上问题记录


下一篇:构建企业级就绪Kubernetes容器平台