图卷积网络详细介绍(二)

本文为图卷积网络详细介绍(一)的完整代码实现。

图卷积网络详细介绍(一)翻译自Tobias Skovgaard Jepsen写在Medium上的博客文章,该文用代码示例说明了如何通过GCN的隐藏层来传播信息,但是并没有给出完整的代码,尤其是最后的可视化部分。因此,本文给出了该文章案例对应的完整代码。

import networkx as nx
import numpy as np
import matplotlib.pyplot as plt

# load karate network 
zkc = nx.karate_club_graph()
order = sorted(list(zkc.nodes()))

# input parameters
A = nx.to_numpy_matrix(zkc, nodelist=order)
I = np.eye(zkc.number_of_nodes())
A_hat = A + I
D_hat = np.array(np.sum(A_hat, axis=1))
D_hat = [x[0] for x in D_hat]
D_hat = np.matrix(np.diag(D_hat))

# initializing weight
W_1 = np.random.normal(loc=0, scale=1, size=(zkc.number_of_nodes(), 4))  # Normal Distribution or Gaussian Distribution
W_2 = np.random.normal(loc=0, size=(W_1.shape[1], 2))
# loc is Mean (“centre”) of the distribution
# scale is Standard deviation (spread or “width”) of the distribution
# size is Output shape

# GCN Model
def relu(x):
    return np.maximum(x, 0)

def gcn_layer(A, D, X, W):
    return relu(D**-1*A*X*W)

H_1 = gcn_layer(A_hat, D_hat, I, W_1)
H_2 = gcn_layer(A_hat, D_hat, H_1, W_2)
output = H_2

# get feature representations of nodes
feature_representations = {node: np.array(output)[node] for node in zkc.nodes()}

# visualizing the features
plt.figure(figsize=(7, 5), dpi=180)  # set the size of the figure
pos = feature_representations
for x in zkc.nodes():
    if zkc.nodes[x]['club'] == 'Mr. Hi':
        nx.draw_networkx_nodes(zkc, pos, [x], node_size = 200, node_color = '#1f77b4', alpha=1)
        
    else:
        nx.draw_networkx_nodes(zkc, pos, [x], node_size = 200, node_color = '#ff7f0e', alpha=1) 

labels = {}
labels[0] = r'A'
labels[33] = r'I'
nx.draw_networkx_labels(zkc, pos, labels, font_size=8)
# plt.axis('off')
plt.show()

由于该案例中没有误差反向传播过程,即没有GCN的训练步骤,而且每次隐层的权重都是随机初始化的, 所以每次运行的结果会不一样,可能会出现较好的社区划分效果,如下图

在这里插入图片描述这样的
在这里插入图片描述
还有这样的

在这里插入图片描述也有可能效果不是很好,出现这样的

在这里插入图片描述
这样的
在这里插入图片描述

甚至这样的
在这里插入图片描述敬请期待后续文章

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值