首页 > 代码库 > 《集体智慧编程》代码勘误:第六章
《集体智慧编程》代码勘误:第六章
一:勘误
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
暂时看到这里,发现的问题,若存在其他问题,还望告知。
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。