numpy.cov() 异常:'float' 对象没有属性 'shape'

numpy.cov() exception: 'float' object has no attribute 'shape'

我有一个不同植物物种的数据集,我将每个物种分成不同的 np.array

当尝试从这些物种中生成高斯模型时,我必须计算每个不同标签的均值和协方差矩阵。

问题是:在其中一个标签中使用 np.cov() 时,该函数会引发错误“'float' 对象没有属性 '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 函数都能优雅地处理这些 - 就像在这种情况下一样),因此检查它的来源并修复它可能很有意义那。

尝试

    label0.astype(float32)

然后计算你的cov。

可能是因为你的数据类型是对象。