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