TypeError: only length-1 arrays can be converted to Python scalars

本文介绍了在使用Python进行科学计算时遇到的关于NumPy数组与标准数学函数不兼容的问题,并给出了相应的解决办法。文章详细解释了如何正确地在涉及NumPy数组的操作中使用指数函数,并提供了一个具体的例子来说明如何修改代码以避免类型错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

因为dataMatrixweights均为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数组不适用。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值