Mat*_*mes 13 python arrays numpy attributeerror
我有一个不同植物物种的数据集,我将每个物种分成不同的物种np.array.
当试图从这些物种中生成高斯模型时,我不得不计算每个不同标签的平均值和协方差矩阵.
问题是:当np.cov()在其中一个标签中使用时,该函数会引发错误"'float'对象没有属性'shape'",我无法确定问题的来源.我正在使用的确切代码行如下:
covx = np.cov(label0, rowvar=False)
Run Code Online (Sandbox Code Playgroud)
哪个label0是numpy ndarray of shape(50,3),其中列代表不同的变量,每行是不同的观察.
确切的错误跟踪是:
---------------------------------------------------------------------------
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'
Run Code Online (Sandbox Code Playgroud)
什么是错误的想法?
MSe*_*ert 13
如果数组是以下数组,则错误是可重现的dtype=object:
import numpy as np
label0 = np.random.random((50, 3)).astype(object)
np.cov(label0, rowvar=False)
Run Code Online (Sandbox Code Playgroud)
AttributeError:'float'对象没有属性'shape'
如果可能,您应该将其转换为数字类型.例如:
np.cov(label0.astype(float), rowvar=False) # works
Run Code Online (Sandbox Code Playgroud)
注意:object数组很少有用(它们很慢并且并非所有NumPy函数都能优雅地处理它们 - 就像在这种情况下一样),因此检查它的来源并修复它是有意义的.
小智 11
尝试
label0.astype(float32)
Run Code Online (Sandbox Code Playgroud)
然后计算你的cov。
这可能是因为您的 dtype 是对象。