我有以下代码:
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
from numpy import linalg as LA
G = nx.read_graphml('/home/user/Documents/J_Data/brain_1.graphml')
Z = nx.to_numpy_matrix(G)
e_vals, e_vecs = LA.eigh(Z)
for x in range(0, len(e_vals)):
e_vecs_new[:, :x] = e_vecs[:, :x]*delta[:x]
print e_vecs_new
当我运行此代码时,似乎for循环无法正常运行。它旨在迭代e_vecs的每一列,并根据delta(0或1)中的值将整列设置为0。终端输出如下:
/usr/bin/python2.7 /home/user/PycharmProjects/Graph_Project/Graph.py
Traceback (most recent call last):
File "/home/amit/PycharmProjects/Graph_Project/Graph.py", line 37, in <module>
e_vecs_new[:, :x] = e_vecs[:, :x]*delta[:x]
File "/usr/lib/python2.7/dist-packages/numpy/matrixlib/defmatrix.py", line 341, in __mul__
return N.dot(self, asmatrix(other))
ValueError: matrices are not aligned
Process finished with exit code 1
当我运行预期循环的一次迭代时:
print e_vecs[:, :1]*delta[:1]
我得到了所需的输出,这是一个0到适当长度的列:
[[ 0.]
[ 0.]
.
.
.
[ 0.]
[ 0.]]
当我运行以下打印语句时:
print e_vecs_new.shape
print e_vecs.shape
print delta.shape
我得到以下输出:
/usr/bin/python2.7 /home/user/PycharmProjects/Graph_Project/Graph.py
(242, 242)
(242, 242)
(242,)
Process finished with exit code 0
delta的形状是(242,)而不是(242,1)是一个问题吗?
答案 0 :(得分:1)
如果delta
只是一个向量,您只需将其编入索引为delta[x]
delta[:1]
有效,因为你只要求第一个元素,但delta [:2]将超过一个整数,因此乘法被解释为点积。
>>> delta = np.array([1,2,3,4,5])
>>> delta[:1]
array([1])
>>> delta[:2]
array([1, 2])
等