我有一个不同植物物种的数据集,我将每个物种分成不同的 np.array
。
当尝试从这些物种中生成高斯模型时,我必须计算每个不同标签的均值和协方差矩阵。
问题是:在其中一个标签中使用 np.cov()
时,该函数会引发错误“'float' object has no attribute 'shape'”,我真的不能弄清楚问题出在哪里。我使用的确切代码行如下:
covx = np.cov(label0, rowvar=False)
其中 label0
是形状为 (50,3) 的 numpy ndarray,其中列代表不同的变量,每一行代表不同的观察值。
准确的错误轨迹是:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-81-277aa1d02ff0> in <module>()
2
3 # Get the covariances
----> 4 np.cov(label0, rowvar=False)
C:\Users\Matheus\Anaconda3\lib\site-packages\numpy\lib\function_base.py in cov(m, y, rowvar, bias, ddof, fweights, aweights)
3062 w *= aweights
3063
-> 3064 avg, w_sum = average(X, axis=1, weights=w, returned=True)
3065 w_sum = w_sum[0]
3066
C:\Users\Matheus\Anaconda3\lib\site-packages\numpy\lib\function_base.py in average(a, axis, weights, returned)
1143
1144 if returned:
-> 1145 if scl.shape != avg.shape:
1146 scl = np.broadcast_to(scl, avg.shape).copy()
1147 return avg, scl
AttributeError: 'float' object has no attribute 'shape'
有什么问题吗?
最佳答案
如果数组是dtype=object
,错误是可重现的:
import numpy as np
label0 = np.random.random((50, 3)).astype(object)
np.cov(label0, rowvar=False)
AttributeError: 'float' object has no attribute 'shape'
如果可能,您应该将其转换为数字类型。例如:
np.cov(label0.astype(float), rowvar=False) # works
注意:object
数组很少有用(它们很慢,而且并非所有 NumPy 函数都能优雅地处理这些 - 就像在本例中一样),因此检查它的来源以及解决这个问题。
关于python - numpy.cov() 异常 : 'float' object has no attribute 'shape' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45670487/