图神经网路:DGL基础(2)
原文链接:https://blog.csdn.net/beilizhang/article/details/108413282
DGL是一种用于简化图神经网络实现的包
文档先给出一个“Zachary空手道俱乐部问题”的小例子,以便熟悉DGL的基本操作。“Zachary空手道俱乐部是一个社交网络,包含34个成员及他们在俱乐部外的关系链接,俱乐部之后被分为两个分别由教练(节点0)和会长(节点33)领导的社区
构建图
一共34个节点,156条边。
src表示其实节点,dst表示目标节点,一 一对应构成156条边,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())
可视化
可视化需要networkx,先让刚才用DGLGraph构建的图转为networkx格式的无向图,然后使用nx.draw()画图。(要显示图还需要plt.show())
布局设置:kamada_kawai_layout
(G, dist=None, pos=None, weight=‘weight’, scale=1, center=None, dim=2)
使用Kamada Kawai路径长度成本函数定位节点。
-
参数
G ( 网络图或节点列表 )–一个位置将分配给G中的每个节点。dist ( dict (default=None) )–按源节点和目标节点索引的节点间最佳距离的两级字典。如果没有,则使用最短路径长度()计算距离。pos ( dict or None optional (default=None) )–节点作为字典的初始位置,节点作为键,值作为坐标列表或元组。如果没有,则对dim>=2使用圆形布局(),对dim==1使用线性布局。重量 ( string or None optional (default=‘weight’) )–保留用于边缘权重的数值的边缘属性。如果没有,则所有边权重都为1。规模 ( 数字(默认值:1) )–位置的比例因子。中心 ( array-like or None )–以布局为中心的坐标对。dim ( int )–布局尺寸。
-
返回
pos --由节点键控的位置字典。
-
返回类型
这里的’nx.kamada_kawai_layout’为布局设置,即画风。还有以下几种可选择:
circular_layout:节点在一个圆环上均匀分布
random_layout:节点随机分布
shell_layout:节点在同心圆上分布
spring_layout: 用Fruchterman-Reingold算法排列节点(样子类似多中心放射状)
spectral_layout:根据图的拉普拉斯特征向量排列节点
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()
分配特征
给34个节点随机初始化一个5维度的向量,'feat’是特征的名称,如果节点有多种特征,需要通过名称区分
import torch
import torch.nn as nn
import torch.nn.functional as F
# 给34个节点随机初始化一个5维度的向量
embed = nn.Embedding(34, 5) # 34 nodes with embedding dim equal to 5
G.ndata['feat'] = embed.weight
print(G.edata,G.ndata)
定义图卷积神经网络
定义一个包含两个GCN层的更深入的GCN模型
第一层将大小为5的输入特征转化为大小为5的隐藏特征。
再通过一个relu激活函数
第二层转换隐藏层并产生大小为2的输出特征,对应空手道俱乐部的两组。
第一个函数的参数分别表示:输入的特征大小、隐藏层的特征大小、以及输出的特征大小
第二个函数的参数分别表示:图,图中节点的特征
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
这里的embed是前面的34个节点的特征信息
inputs表示34个节点的具体特征
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()搭配使用
Python中有一种特有的概念,称之为迭代器。迭代器最大的特点是惰性求值,即只有当迭代至某个值时,才会对其进行计算,而不是一开始就计算出全部的值。迭代器特别适合应用于大文件,无限集合等,因为无需将他们一次性传入内存中。itertools是Python内置的模块,其中包含了一系列迭代器相关的函数和类。
chain的使用格式如下:chain(iterable1, iterable2, iterable3, …)作用是接收多个迭代器,并将他们连接起来返回一个新的迭代器。
Adam,名字来自:Adaptive Moment Estimation,自适应矩估计。是2014年提出的一种万金油式的优化器,使用起来非常方便,梯度下降速度快,但是容易在最优值附近震荡。竞赛中性能会略逊于SGD,毕竟最简单的才是最有效的。但是超强的易用性使得Adam被广泛使用。
detach():返回一个新的tensor
,从当前计算图中分离下来的,但是仍指向原变量的存放位置,不同之处只是requires_grad为false,得到的这个tensor
永远不需要计算其梯度,不具有grad
损失函数-NLLLoss:常用于多分类任务,NLLLoss 函数输入 input 之前,需要对 input 进行 log_softmax 处理,即将 input 转换成概率分布的形式,并且取对数,底数为 e
-
optimizer.zero_grad():第一个是将梯度清零,因为训练的过程通常使用mini-batch方法,所以如果不将梯度清零的话,梯度会与上一个batch的数据相关,因此该函数要写在反向传播和梯度下降之前。(训练的时候要分为多个batch)optimizer.zero_grad()函数会遍历模型的所有参数,通过p.grad.detach_()方法截断反向传播的梯度流,再通过p.grad.zero_()函数将每个参数的梯度值设为0,即上一次的梯度记录被清空。
-
loss.backward():PyTorch的反向传播(即tensor.backward())是通过autograd包来实现的,autograd包会根据tensor进行过的数学运算来自动计算其对应的梯度,如果没有进行tensor.backward()的话,梯度值将会是None,因此loss.backward()要写在optimizer.step()之前
-
optimizer.step():step()函数的作用是执行一次优化步骤,通过梯度下降法来更新参数的值。因为梯度下降是基于梯度的,所以在执行optimizer.step()函数前应先执行loss.backward()函数来计算梯度。
注意:optimizer只负责通过梯度下降进行优化,而不负责产生梯度,梯度是tensor.backward()方法产生的。
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保存logit,以便后面可视化
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()
x_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()