错误:TypeError: can't multiply sequence by non-int of type 'numpy.float64'

错误: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                                                      #返回
  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值