栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

numpy中matrix的坑

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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])
运行结果

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/724927.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号