TypeError: unsupported operand type(s) for +=: ‘float‘ and ‘list‘ in bayes.py for Naive Bayes
TypeError: unsupported operand type(s) for +=: 'float' and 'list' in bayes.py for Naive Bayes
·
Error Discreptions:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-57-76c361767a88> in <module>
----> 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:
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
已为社区贡献10条内容
所有评论(0)