def sigmoid(intX):
return 1.0/(1+exp(-intX))
dataMatrix = mat(dataMatIn)
weights = ones((n, 1))
h = sigmoid(dataMatrix*weights)
出错:
return 1.0/(1+math.exp(-intX))
TypeError: only length-1 arrays can be converted to Python scalars
因为dataMatrix 与weights均为numpy矩阵,相乘也是numpy矩阵,而math.exp()函数只处理python标准数值。
此处需要用numpy的exp()方法,如下:
import numpy as np
def sigmoid(self, intX):
return 1.0/(1+np.exp(-intX))
也可以在文件头添加from numpy import *,就可以直接用exp(-intX)了
def smoSimple(dataMatIn, classLabels, C, toler, maxIter):
dataMatrix = mat(dataMatIn)
labelMat = mat(classLabels).transpose()
iter = 0
while iter < maxIter:
alphaPairChanged = 0
for i in range(m):
fXi = float(multiply(alphas, labelMat).T * (dataMatrix * dataMatrix[i,:].T)) + b
.....
出错:
fXi = float(multiply(alphas, labelMat).T * (dataMatrix * dataMatrix[i,:].T)) + b
TypeError: only length-1 arrays can be converted to Python scalars
print
multiply(alphas, labelMat).T * (dataMatrix * dataMatrix[i,:].T)
[[ 0.]
[ 0.]
[ 0.]
[ 0.]
...
[ 0.]]
可见float()函数中是一个numpy数组,此例又证明标准python函数对numpy数组不适用。
修正Python与NumPy兼容性问题
本文介绍了在使用Python进行科学计算时遇到的关于NumPy数组与标准数学函数不兼容的问题,并给出了相应的解决办法。文章详细解释了如何正确地在涉及NumPy数组的操作中使用指数函数,并提供了一个具体的例子来说明如何修改代码以避免类型错误。
538

被折叠的 条评论
为什么被折叠?



