关于GCN的基础原理见图卷积神经网络(GCN)。
GCN的传递公式:
通过本文也顺便记录下一些numpy对矩阵的处理方法方便以后使用:
首先我们需要掌握的就是D波浪A波浪的代码实现方法。(参考这篇文章)
先建立这个图的邻接矩阵:
#建立邻接矩阵
A = np.array(
[[0, 1, 0, 0],
[0, 0, 1, 1],
[0, 1, 0, 0],
[1, 0, 1, 0]],
dtype=float
)
对角线矩阵
#建立对角线矩阵
I=np.eye(A.shape[0])
#shape函数可以获得矩阵的规模 A.shape输出为(4,4),A.shape[0]即行输出,A.shape[1]即列输出
A_hat=A+I
>>>[[1. 1. 0. 0.]
[0. 1. 1. 1.]
[0. 1. 1. 0.]
[1. 0. 1. 1.]]
#这里用纯粹的索引作为节点的特征
X = np.array([[i, -i]
for i in range(A.shape[0])],
dtype=float
)
>>>[[ 0. 0.]
[ 1. -1.]
[ 2. -2.]
[ 3. -3.]]
度矩阵
#计算A_hat的度矩阵
#np.sum函数的用法:axis为默认值,输出整个矩阵所有元素的和;
#axis=0,输出整个矩阵每列的和,压缩为一个行,形式为一个array;
#axis=1:,输出整个矩阵每行的和,压缩为一列,形式为一个array
D_hat=np.sum(A_hat, axis=0)
print(D_hat)
>>>[2. 3. 3. 2.]
D_hat=np.diag(D_hat)
print(D_hat)
>>>[[2. 0. 0. 0.]
[0. 3. 0. 0.]
[0. 0. 3. 0.]
[0. 0. 0. 2.]]
#随机建立一个初始化的参数矩阵W,W的列数代表希望得到的每个节点的特征数
W=np.array([[1, -1],
[1, -1]],
dtype=float)
逆矩阵&-1/2次矩阵
#计算D波浪的逆矩阵
D_hat_I=np.linalg.inv(D_hat)
print(D_hat_I)
>>>[[0.5 0. 0. 0. ]
[0. 0.33333333 0. 0. ]
[0. 0. 0.33333333 0. ]
[0. 0. 0. 0.5 ]]
#计算D波浪的-1/2次矩阵
D_hat_I_=D_hat_I**0.5
print(D_hat_I_)
>>>[[0.70710678 0. 0. 0. ]
[0. 0.57735027 0. 0. ]
[0. 0. 0.57735027 0. ]
[0. 0. 0. 0.70710678]]
矩阵乘
#为了写代码简单,把array都转化成matrix类型
D_hat_I_=np.matrix(D_hat_I_)
A_hat=np.matrix(A_hat)
X=np.matrix(X)
W=np.matrix(W)
#实现公式D_hat_I_=np.matrix(D_hat_I_)
A_hat=np.matrix(A_hat)
X=np.matrix(X)
W=np.matrix(W)
H=D_hat_I_*A_hat*D_hat_I_*X*W
print(H)
H=D_hat_I_*A_hat*D_hat_I_*X*W
print(H)
>>>[[ 0.81649658 -0.81649658]
[ 4.44948974 -4.44948974]
[ 2. -2. ]
[ 4.63299316 -4.63299316]]
至此即实现了网络的传播。
代码参考https://blog.csdn.net/weixin_42052081/article/details/89108966