numpy中matrix的坑

numpy中matrix的坑

在看一篇利用numpy实现简单的GCN网络的文章时,遇到了matplotlib中scatter函数一直显示“Masked arrays must be 1-D”这个错误。后面查阅资料得知是numpy中matrix的维度一定为2维

import networkx as nx
import numpy as np
from GCN import gcn_layer
import matplotlib.pyplot as plt


zkc = nx.karate_club_graph()
order = sorted(list(zkc.nodes()))
A = nx.to_numpy_matrix(zkc, nodelist=order)
I = np.eye(zkc.number_of_nodes())
A_hat = A + I
D_hat = np.array(A_hat.sum(axis=0))[0]  # D_hat.shape = (1,34)
D_hat = np.matrix(np.diag(D_hat))  # the usage of np.diag :D_hat.shape must be 1-dim
w1 = np.random.normal(loc=0, scale=1, size=(zkc.number_of_nodes(), 8))  # generate weight1 randomly (n,4)
w2 = np.random.normal(loc=0, size=(w1.shape[1], 2))  # match the shape of the first gcn_layer's output
H1 = gcn_layer(D_hat, A_hat, I, w1)
H2 = gcn_layer(D_hat, A, H1, w2)
feature_representations = {node: np.array(H2)[node] for node in zkc.nodes()}
x = H2.T[0]
y = H2.T[1]
plt.scatter(x, y)
plt.title("Feature representations of Zachary")
plt.show()

官方文档的解释

Note: It is no longer recommended to use this class, even for linear algebra. Instead use regular arrays. The class may be removed in the future.
A matrix is a specialized 2-D array that retains its 2-D nature through operations.
因此在matrix使用过程中会一直保持二维数组的特性,在scatter函数中,scatter(x,y)中x,y均为一维数组。
Solution:将其转化为array再变为1-D array即可

x = np.array(H2.T[0])
y = np.array(H2.T[1])
# 或者
y = np.asarray(H2.T[0])
y = np.asarray(H2.T[1])

运行结果

得到的节点的representations

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值