0.前言

近来工作不算忙,工作时间主要在忙解析文档的工作,期间经历了从手撸规则到编写机器学习模型再到深度学习模型(从全连接到Bi-LSTM-CRF)的转变,自己对深度学习的应用框架编写和落地有了更多的理解,尤其是如何在对任务深入理解之上将其建模为机器学习分类任务的流程,之后会另起文章详述,此处不表。

知识图谱和深度学习相结合的一个点就是图神经网络模型(GNN),这里自己也算开始接触并开启实践之旅了。

1.DGL简单使用

1.1 DGL介绍

DGL是一个易于使用,高性能和可扩展的Python包,用于深入学习图形。
DGL与框架无关,这意味着如果一个深度图模型是端到端应用程序的一个组件,那么其余的逻辑可以在任何主要框架中实现,比如PyTorch、Apache MXNet或TensorFlow。

Github地址:dmlc/dgl: Python package built to ease deep learning on graph, on top of existing DL frameworks.

1.2 示例代码

说明:以下代码在jupyter notebook中运行,且主要搬运自DGL at a Glance — DGL 0.5.0 documentation

引入依赖库

import dgl
import numpy as np

使用DGL创建图

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])
    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.

查看图结构

import networkx as nx
# 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=[[.2, .5, .7]])

输出:

dgl_1

为节点或边分配特征

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

# 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]])

定义一个图卷积神经网络(GCN)

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)

数据准备和初始化

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

训练模型

训练代码:

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 0 | Loss: 0.8586
Epoch 1 | Loss: 0.8109
Epoch 2 | Loss: 0.7692
Epoch 3 | Loss: 0.7338
Epoch 4 | Loss: 0.7082
Epoch 5 | Loss: 0.6831
Epoch 6 | Loss: 0.6582
Epoch 7 | Loss: 0.6352
Epoch 8 | Loss: 0.6149
Epoch 9 | Loss: 0.5956
Epoch 10 | Loss: 0.5762
Epoch 11 | Loss: 0.5572
Epoch 12 | Loss: 0.5374
Epoch 13 | Loss: 0.5179
Epoch 14 | Loss: 0.4981
Epoch 15 | Loss: 0.4777
Epoch 16 | Loss: 0.4574
Epoch 17 | Loss: 0.4363
Epoch 18 | Loss: 0.4148
Epoch 19 | Loss: 0.3934
Epoch 20 | Loss: 0.3716
Epoch 21 | Loss: 0.3494
Epoch 22 | Loss: 0.3266
Epoch 23 | Loss: 0.3034
Epoch 24 | Loss: 0.2805
Epoch 25 | Loss: 0.2589
Epoch 26 | Loss: 0.2377
Epoch 27 | Loss: 0.2172
Epoch 28 | Loss: 0.1975
Epoch 29 | Loss: 0.1790
Epoch 30 | Loss: 0.1615
Epoch 31 | Loss: 0.1451
Epoch 32 | Loss: 0.1297
Epoch 33 | Loss: 0.1156
Epoch 34 | Loss: 0.1028
Epoch 35 | Loss: 0.0912
Epoch 36 | Loss: 0.0809
Epoch 37 | Loss: 0.0721
Epoch 38 | Loss: 0.0642
Epoch 39 | Loss: 0.0572
Epoch 40 | Loss: 0.0510
Epoch 41 | Loss: 0.0455
Epoch 42 | Loss: 0.0407
Epoch 43 | Loss: 0.0364
Epoch 44 | Loss: 0.0327
Epoch 45 | Loss: 0.0294
Epoch 46 | Loss: 0.0266
Epoch 47 | Loss: 0.0241
Epoch 48 | Loss: 0.0218
Epoch 49 | Loss: 0.0199

可视化

%matplotlib inline
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()

初始图节点状态:

动画效果:

%matplotlib inline
from matplotlib import animation, rc
from IPython.display import HTML
rc('animation', html='html5')
ani = animation.FuncAnimation(fig, draw, frames=len(all_logits), interval=200)
plt.show()
# HTML(ani.to_html5_video()) # 将动画转为h5 video,和下面两种方式都行
HTML(ani.to_jshtml()) # 可视化效果更佳,且好像不依赖ffmpeg?

如图:

dgl_3

2.遇到的问题

2.1 无法实现动画效果

发现报Matplotlib-Animation “No MovieWriters Available”的错误,后来通过stackoverflow找到了解决方案,即下载ffmpeg并配置环境变量。

3.参考

  1. DGL at a Glance — DGL 0.5.0 documentation
  2. dmlc/dgl: Python package built to ease deep learning on graph, on top of existing DL frameworks.
  3. python - Matplotlib-Animation “No MovieWriters Available” - Stack Overflow
  4. python - Inline animations in Jupyter - Stack Overflow
  5. 在 jupyter notebook 中使用 matplotlib 绘图的注意事项_WeiSenhui的博客-CSDN博客

评论




博客内容遵循 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 协议

本站使用 Volantis 作为主题,总访问量为
载入天数...载入时分秒...
冀ICP备20001334号