numpy:TypeError中的错误:只能将长度为1的数组转换为Python标量 [英] error in numpy:TypeError: only length-1 arrays can be converted to Python scalars
本文介绍了numpy:TypeError中的错误:只能将长度为1的数组转换为Python标量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我写了一个函数sigmoid:
I write a function sigmoid:
def sigmoid(inX):
return 1.0 / (1 + exp(-inX))
并且当inX是100x1大小的矩阵时,会出现错误:
and when the inX is a matrix of 100x1 size, the error arises:
/home/abyss/python/machine/logistic/logReg.py in sigmoid(inX)
12
13 def sigmoid(inX):
---> 14 r = 1.0 / (1 + exp(-inX))
15 return r
16
TypeError: only length-1 arrays can be converted to Python scalars
但是我可以在命令行中直接使用此表达式:
but I can directly use this expression in command line:
In [59]: r = 1.0 / (1 + exp(-h))
In [60]: shape(r)
Out[60]: (100, 1)
我很困惑,这是怎么发生的?
I am totally confused, how did this happen?
推荐答案
当采用数组或其他不想使用Python数学库的指数时,请改用NumPy库:
When you are taking the exponent of an array or anything else you don't want to use Python's math library, use NumPy library instead:
import numpy as np
def sigmoid(inX):
r = 1.0/(1+ np.exp(-inX))
return r
这篇关于numpy:TypeError中的错误:只能将长度为1的数组转换为Python标量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文