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:
?
|