错误:TypeError: can’t multiply sequence by non-int of type ‘numpy.float64’
错误代码:
该代码是逻辑回归(Logistic Regression)中的改进后的随机梯度上升算法
def stocGradAscent1(dataMatrix, classLabels, numIter=150):
#dataMatrix=np.array(dataMatrix)
m,n = np.shape(dataMatrix) #返回dataMatrix的大小。m为行数,n为列数。
weights = np.ones(n) #参数初始化
for j in range(numIter):
dataIndex = list(range(m))
for i in range(m):
alpha = 4/(1.0+j+i)+0.01 #降低alpha的大小,每次减小1/(j+i)。
randIndex = int(random.uniform(0,len(dataIndex))) #随机选取样本
h = sigmoid(sum(dataMatrix[randIndex]*weights)) #选择随机选取的一个样本,计算h
error = classLabels[randIndex] - h #计算误差
weights = weights + alpha * error * dataMatrix[randIndex] #更新回归系数
del(dataIndex[randIndex]) #删除已经使用的样本
return weights #返回
纠错后的代码:
把上面代码中第二行注释去掉就行,原因是在倒数第三行的乘法中出现了错误,传进来的dataMatrix是一个列表,要先转化成np的数组,才能与error相乘。
- 虽然是个低级错误,但是单看报错内容可能比较难发现,希望能帮到你。
def stocGradAscent1(dataMatrix, classLabels, numIter=150):
#改了下面
dataMatrix=np.array(dataMatrix)
m,n = np.shape(dataMatrix) #返回dataMatrix的大小。m为行数,n为列数。
weights = np.ones(n) #参数初始化
for j in range(numIter):
dataIndex = list(range(m))
for i in range(m):
alpha = 4/(1.0+j+i)+0.01 #降低alpha的大小,每次减小1/(j+i)。
randIndex = int(random.uniform(0,len(dataIndex))) #随机选取样本
h = sigmoid(sum(dataMatrix[randIndex]*weights)) #选择随机选取的一个样本,计算h
error = classLabels[randIndex] - h #计算误差
weights = weights + alpha * error * dataMatrix[randIndex] #更新回归系数
del(dataIndex[randIndex]) #删除已经使用的样本
return weights #返回