设为首页 收藏本站
查看: 817|回复: 0

[经验分享] 简单的贝叶斯分类器的python实现

[复制链接]

尚未签到

发表于 2015-12-2 09:26:08 | 显示全部楼层 |阅读模式
  
  



  1 # -*- coding: utf-8 -*-
  2 '''
  3 >>> c = Classy()
  4 >>> c.train(['cpu', 'RAM', 'ALU', 'io', 'bridge', 'disk'], 'architecture')
  5 True
  6 >>> c.train(['monitor', 'mouse', 'keyboard', 'microphone', 'headphones'], 'input_devices')
  7 True
  8 >>> c.train(['desk', 'chair', 'cabinet', 'lamp'], 'office furniture')
  9 True
10 >>> my_office = ['cpu', 'monitor', 'mouse', 'chair']
11 >>> c.classify(my_office)
12 ('input_devices', -1.0986122886681098)
13 ...
14 >>> c = Classy()
15 >>> c.train(['cpu', 'RAM', 'ALU', 'io', 'bridge', 'disk'], 'architecture')
16 True
17 >>> c.train(['monitor', 'mouse', 'keyboard', 'microphone', 'headphones'], 'input_devices')
18 True
19 >>> c.train(['desk', 'chair', 'cabinet', 'lamp'], 'office furniture')
20 True
21 >>> my_office = ['cpu', 'monitor', 'mouse', 'chair']
22 >>> c.classify(my_office)
23 ('input_devices', -1.0986122886681098)
24 ...
25 '''
26
27 from collections import Counter
28 import math
29
30 class ClassifierNotTrainedException(Exception):
31     
32     def __str__(self):
33         return "Classifier is not trained."
34
35 class Classy(object):
36     
37     def __init__(self):
38         self.term_count_store = {}
39         self.data = {
40             'class_term_count': {},
41             'beta_priors': {},
42             'class_doc_count': {},
43         }
44         self.total_term_count = 0
45         self.total_doc_count = 0
46         
47     def train(self, document_source, class_id):
48     
49         '''
50         Trains the classifier.
51         
52         '''
53         count = Counter(document_source)
54         try:
55             self.term_count_store[class_id]
56         except KeyError:
57             self.term_count_store[class_id] = {}
58         for term in count:
59             try:
60                 self.term_count_store[class_id][term] += count[term]
61             except KeyError:
62                 self.term_count_store[class_id][term] = count[term]
63         try:
64             self.data['class_term_count'][class_id] += document_source.__len__()
65         except KeyError:
66             self.data['class_term_count'][class_id] = document_source.__len__()
67         try:
68             self.data['class_doc_count'][class_id] += 1
69         except KeyError:
70             self.data['class_doc_count'][class_id] = 1
71         self.total_term_count += document_source.__len__()
72         self.total_doc_count += 1
73         self.compute_beta_priors()
74         return True
75         
76     def classify(self, document_input):
77         if not self.total_doc_count: raise ClassifierNotTrainedException()
78         
79         term_freq_matrix = Counter(document_input)
80         arg_max_matrix = []
81         for class_id in self.data['class_doc_count']:
82             summation = 0
83             for term in document_input:
84                 try:
85                     conditional_probability = (self.term_count_store[class_id][term] + 1)
86                     conditional_probability = conditional_probability / (self.data['class_term_count'][class_id] + self.total_doc_count)
87                     summation += term_freq_matrix[term] * math.log(conditional_probability)
88                 except KeyError:
89                     break
90             arg_max = summation + self.data['beta_priors'][class_id]
91             arg_max_matrix.insert(0, (class_id, arg_max))
92         arg_max_matrix.sort(key=lambda x:x[1])
93         return (arg_max_matrix[-1][0], arg_max_matrix[-1][1])
94         
95     def compute_beta_priors(self):
96         if not self.total_doc_count: raise ClassifierNotTrainedException()
97         
98         for class_id in self.data['class_doc_count']:
99             tmp = self.data['class_doc_count'][class_id] / self.total_doc_count
100             self.data['beta_priors'][class_id] = math.log(tmp)
  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-146147-1-1.html 上篇帖子: Python-WSGI详解汇总 下篇帖子: python学习笔记九:正则表达式
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表