《集体智慧编程》代码勘误:第六章

一:勘误

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 '
' at the end line
		line = line.strip('
')
		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('
')
		cat.append(line)
	f.close()
	return cat

临时看到这里。发现的问题,若存在其它问题。还望告知。

原文地址:https://www.cnblogs.com/llguanli/p/7103461.html