我在python中得到了最奇怪的属性错误,而且我似乎在网上找不到任何关于它的信息。我试图求和矩阵y的所有列的元素,并将它们保存在一个新的矩阵中。Y是1.s和0‘s的1063 x 1063恒等矩阵,mat是一个70000 x 1063稀疏矩阵。
mat = scipy.sparse.rand(70000, 1063, density=0.01, format='coo', dtype=None, random_state=None)
mat.shape 给我:
(70000, 1063)现在我创建y,一个1063 x 1063恒等矩阵:
y = np.matlib.identity(1063)
ind = np.nonzero((mat.sum(axis=0) < 20))
y[ind, :] = 0 # replace element at given index with 0
x = np.sum(y, axis=1) # here i want to count the elements of all columns of y关于最后一行,我得到了以下错误:
AttributeError: 'numpy.ndarray' object has no attribute '_collapse'我迷路了。对如何解决这个问题有什么想法吗?
发布于 2015-01-05 01:11:16
在matrixlib/defmtrix.py中,_collapse定义为类Matrix的一种方法。
def _collapse(self, axis):
"""A convenience function for operations that want to collapse
to a scalar like _align, but are using keepdims=True
"""
if axis is None:
return self[0, 0]
else:
return self_collapse正被用于:
def sum(self, axis=None, dtype=None, out=None):
return N.ndarray.sum(self, axis, dtype, out, keepdims=True)._collapse(axis)它在.mean、.prod、.any、.max等方法中也是这样使用的。基本上,任何通常会减少矩阵维数的操作。
通常,这些操作返回一个与输入类型相同的数组,所以如果y是一个矩阵,它应该返回一个矩阵。由于矩阵总是2d,所以使用keepdims=True。如果操作将矩阵缩减为标量(例如,轴为空),则需要._collapse。那么我们需要一个真正的标量,而不是一个包裹在矩阵中的标量。
我怀疑这部分代码是否在数年内发生了变化(我将再次检查github)。
所以它是为matrix定义的,而不是为ndarray定义的。
In [154]: np.matrix([[1,0],[0,1]])._collapse(0)
Out[154]:
matrix([[1, 0],
[0, 1]])
In [155]: np.array([[1,0],[0,1]])._collapse(0)
...
AttributeError: 'numpy.ndarray' object has no attribute '_collapse'即使输入是一个,np.sum似乎也不会返回一个matrix。
我想知道其他的约简函数是否有同样的问题,例如
y.max(axis=0)
np.add.reduce(y, axis=0)y.max、y.prod等都与y.sum编码相同。对于matrix,这意味着使用底层的ndarray函数,然后是._collapse。
np.add.reduce(y, axis=1, keepdims=True)在功能上非常相似,尽管底层C代码的路由是不同的。它也不尝试调用._collapse,这意味着对于axis=None,它不会将结果降为标量;它只剩下一个(1,1)矩阵。仍然可以使用._collapse,如:
np.add.reduce(np.matrix('1 2 3; 4 5 6'),axis=None, keepdims=True)._collapse(None)
# 21围绕np.sum问题的另一个选项是将y转换为数组(并可选择返回到matrix):
np.matrix(np.sum(y.A, axis=1, keepdims=True))sparse采取了另一条实现.sum的方法--用1s的矩阵乘以该矩阵:
y * np.asmatrix(np.ones((y.shape[1],1),int))我想知道您的问题是否是由您正在导入的其他模块引起的,其中一个模块正在覆盖某些定义,比如matrix类型。你有一个pandas标签。这是否意味着作为计算的一部分加载pandas?我没有指责pandas,但这表明程序环境更加复杂。用最简单的程序尝试计算。
https://stackoverflow.com/questions/27766807
复制相似问题