TypeError: unsupported operand type

TypeError: unsupported operand type,第1张

Error Discreptions:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
 in 
----> 1 p0V,p1V,pAb=bayes.trainNB0(trainMat,listClasses)

D:\maxwelllearning\maxwellhandon\machine learning in action\bayes.py in trainNB0(trainMatrix, trainCategory)
     38             p1Denom += sum(trainMatrix[i])     #Vector addition
     39         else:
---> 40             p0Num += trainMatrix[i]
     41             p0Denom += sum(trainMatrix[i])
     42     p1Vect = log(p1Num/p1Denom)      # change to log()

TypeError: unsupported operand type(s) for +=: 'float' and 'list'

Error Picture as below:

 Original Code :

def trainNB0(trainMatrix,trainCategory):
    numTrainDocs = len(trainMatrix)
    numWords = len(trainMatrix[0])
    pAbusive = sum(trainCategory)/float(numTrainDocs)
    p0Num = ones(numWords);p1Num = ones(numWords)   #Initialize probabilities
    p0Num = 2.0 ; p1Denom = 2.0
    for i in range(numTrainDocs):
        if trainCategory[i] == 1:
            p1Num += trainMatrix[i]
            p1Denom += sum(trainMatrix[i])     #Vector addition
        else:
            p0Num += trainMatrix[i]
            p0Denom += sum(trainMatrix[i])
    p1Vect = log(p1Num/p1Denom)      # change to log()
    p0Vect = log(p0Num/p0Denom)      # change to log()
    return p0Vect,p1Vect,pAbusive  # Element-wise division

Modified Code:

def trainNB0(trainMatrix,trainCategory):
    numTrainDocs = len(trainMatrix)
    numWords = len(trainMatrix[0])
    pAbusive = sum(trainCategory)/float(numTrainDocs)
    p0Num = ones(numWords);p1Num = ones(numWords)   #Initialize probabilities
    p0Denom = 2.0 ; p1Denom = 2.0
    for i in range(numTrainDocs):
        if trainCategory[i] == 1:
            p1Num += trainMatrix[i]
            p1Denom += sum(trainMatrix[i])     #Vector addition
        else:
            p0Num += trainMatrix[i]
            p0Denom += sum(trainMatrix[i])
    p1Vect = log(p1Num/p1Denom)      # change to log()
    p0Vect = log(p0Num/p0Denom)      # change to log()
    return p0Vect,p1Vect,pAbusive  # Element-wise division

Root Cause:

Due to make a mistake for variable definiation,use p0Denom instead of  p0Num is correct.

 Display:

 

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/715489.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-25
下一篇 2022-04-25

发表评论

登录后才能评论

评论列表(0条)

保存