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数组不适用。