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

一:勘误

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

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值