1. 程式人生 > >《集體智慧編程》代碼勘誤:第六章

《集體智慧編程》代碼勘誤:第六章

close app alt fontsize 第六章 ng- ble 信息 to do

一:勘誤

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

臨時看到這裏。發現的問題,若存在其它問題。還望告知。

《集體智慧編程》代碼勘誤:第六章