簡體   English   中英

計算簡單標准差時,“AttributeError:sqrt”

[英]“AttributeError: sqrt” when calculating a simple standard deviation

在嘗試計算二維numpy數組的標准偏差時,我發現了一個非常不尋常的錯誤。 基本上,我這樣做:

np.std(myarray, axis=1)

這給出了以下錯誤:

/home/user/env/local/lib/python2.7/site-packages/numpy/core/fromnumeric.pyc in std(a, axis, dtype, out, ddof, keepdims)
   2588 
   2589     return _methods._std(a, axis=axis, dtype=dtype, out=out, ddof=ddof,
-> 2590                                 keepdims=keepdims)
   2591 
   2592 def var(a, axis=None, dtype=None, out=None, ddof=0,

/home/user/env/local/lib/python2.7/site-packages/numpy/core/_methods.pyc in _std(a, axis, dtype, out, ddof, keepdims)
    103 
    104     if isinstance(ret, mu.ndarray):
--> 105         ret = um.sqrt(ret, out=ret)
    106     else:
    107         ret = um.sqrt(ret)

AttributeError: sqrt

在第105行中,ret定義為:

array([0.0757800982464383, 0.6065241443345735, 0.3162436337971689,
       0.025387106329804794, 0.023465650294750118, 0.01234409423996419,
       0.03686346121524665, 0.456152653196993, 0.15598749370862977,
       0.0041977155187445945, 0.018816207536006213, 0.018011541017004237,
       0.01046808236307669, 0.0037176987848958156, 0.004346127061033225,
       0.06885161954332783, 0.004758430435294487, 0.010064124660786879,
       0.08732648466448349, 0.14957009536890314, 0.007277246755033778,
       0.0043521569980290355, 0.010174973078043143, 0.33905025844712544,
       0.7960121881423348], dtype=object)

type(myarray): <type 'numpy.ndarray'>

repr(myarray): array([[1.2258313, 1.2258313, 1.3756552, 1.1849703, 1.334794, 1.1849703,
            1.1441092, 1.334794, 1.3075534, 1.2258313, 1.3756552, 0.95342433,
            1.1441092, 1.0760075, 1.1168685, 1.1168685, 1.334794, 0.8036005,
            0.46309182, 0.3405087],
           [1.3756552, 0.95342433, 1.1441092, 1.0760075, 1.1168685, 1.1168685,
            1.334794, 0.8036005, 0.46309182, 0.3405087, 0.313268, 0.38136974,
            0.27240697, 0.38136974, -1.8387468999999996, -0.50395286,
            -0.14982383, -0.46309182, -0.3405087, -0.19068487],...

買我看不出那個陣列有什么問題。 np.sum和np.mean正常工作。

可能是導致此錯誤的原因是什么?

似乎問題是dtype設置為object 即使numpy允許它,通常也是一個壞主意,因為你失去了大多數內部優化。

僅與axis關鍵字一起使用例外:

>>> import numpy as np
>>> a = np.arange(10).reshape(5,2)
>>> b = np.arange(10, dtype=object).reshape(5,2)
>>> np.std(a)
2.8722813232690143
>>> np.std(a, axis=1)
array([ 0.5,  0.5,  0.5,  0.5,  0.5])
>>> np.std(b)
2.8722813232690143
>>> np.std(b, axis=1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/dist-packages/numpy/core/fromnumeric.py", line 2590, in std
    keepdims=keepdims)
  File "/usr/lib/python2.7/dist-packages/numpy/core/_methods.py", line 105, in _std
    ret = um.sqrt(ret, out=ret)
AttributeError: sqrt

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM