python - numpy.cov() 异常 : 'float' object has no attribute 'shape'

标签 python arrays numpy attributeerror

我有一个不同植物物种的数据集,我将每个物种分成不同的 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/

相关文章:

Python - 错误 : couldn't open . png 文件

java - Java 中的 10,000,000 整数数组插入排序

Java数组,NullPointerException?

c# - 将单行从多维数组复制到新的一维数组

python - 通过单击按钮使用启动画面下载文件

python - 检查列表元素中的多个字符串

python - 如何在python中使用uber h3将shapefile/geojson转换为六边形?

python - Numpy/展平列表

python - numpy 点积但保留为矢量(不添加元素)

python - pandas 向量的点积