《集體智慧程式設計》程式碼勘誤:第六章
阿新 • • 發佈:2019-01-05
一:勘誤
classifier類中:def fprob(self, f, cat):
if self.catcount(cat) == 0:
return 0
#notice: rember change int to double or float
# + 0.0 or *1.0 is ok, other wise, may get 0.
return self.fcount(f, cat) * 1.0 / self.catcount(cat)
naviebayes類中:
def prob(self, item, cat): #notice: take care of *1.0 or + 0.0 catprob = self.catcount(cat)*1.0/self.totallcount() docprob = self.docprob(item, cat) return docprob * catprob
二:修改
classifier類中的 fcount 函式,通過引數來實現過載。函式有兩個功能,一是返回給定的 特徵 f 在所有分類中出現的次數,一個是返回給定特徵 f 屬於給定類別 cat 類中的次數。def fcount(self, f, cat = None): #get the count of f in all cats if cat == None: if f not in self.fc: return 0 return sum(self.fc[f].values()) #get the count of f labeled cat else: if f in self.fc and cat in self.fc[f]: return self.fc[f][cat] return 0
三:增加
為了便於以後處理更多更復雜的例項資料,應該通過檔案讀取文字及分類資訊,這裡添加了兩個檔案讀取函式,一個是文字內容的檔案,一個是文字分類的檔案,如:def loadText(textfile = 'a.txt'):
text = []
f = open(textfile)
lines = f.readlines()
for line in lines:
#delete the '\n' at the end line
line = line.strip('\n')
text.append(line)
f.close()
return text
def loadCat(catfile = 'b.txt'): cat = [] f = open(catfile) lines = f.readlines() for line in lines: line = line.strip('\n') cat.append(line) f.close() return cat
暫時看到這裡,發現的問題,若存在其他問題,還望告知。