代码之家  ›  专栏  ›  技术社区  ›  Prof.Plague

typeerror:只有length-1数组可以转换为python scalars python array和numpy

  •  -1
  • Prof.Plague  · 技术社区  · 6 年前

    这是我的密码但我有上述错误。我以前找过,但没帮我找到答案这段代码中有什么不正确?

    import numpy as np 
    import math
    
    def sigmoid(x):
        s = np.array(None)
        for i in x:
            np.append(s,(1/(math.exp(-x)+1)))
    
        return s
    
    x = np.array([1, 2, 3])
    sigmoid(x)
    

    <ipython-input-31-8e002c20e792> in sigmoid(x)
         17     s = np.array(None)`
         18     for i in x:
    ---> 19         np.append(s,(1/(math.exp(-x)+1)))
         20     return s
    TypeError: only length-1 arrays can be converted to Python scalars
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   John Zwinck    6 年前

    简单地替换 math.exp 通过 np.exp . 前者是一个内置的python,它只理解标量(因此产生了错误消息)。

    还要注意 np.append() 返回结果,并且不修改其参数。所以你需要把结果分配回 s . 还要注意,重复附加到NumPy数组是一种反模式——应该在开始时分配整个数组。