简单的贝叶斯分类器的python实现

简介:   1 # -*- coding: utf-8 -*- 2 ''' 3 >>> c = Classy() 4 >>> c.train(['cpu', 'RAM', 'ALU', 'io', 'bridge', 'disk'], 'architecture') 5 True 6 >>> c.

 

 

  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)

 

目录
相关文章
|
5月前
|
Python
Python中的贝叶斯分类器以及如何使用Sklearn库实现它。
【4月更文挑战第23天】Sklearn库支持多种贝叶斯分类器,如高斯朴素贝叶斯、多项式朴素贝叶斯和伯努利朴素贝叶斯。以下是一个使用GaussianNB的简要示例:导入必要库,加载鸢尾花数据集,将其划分为训练集和测试集,创建高斯朴素贝叶斯分类器,训练模型,预测并评估(通过准确率)模型性能。
61 0
|
机器学习/深度学习 Python
【机器学习】贝叶斯分类器代码实现(python+sklearn)
【机器学习】贝叶斯分类器代码实现(python+sklearn)
255 0
|
机器学习/深度学习 算法 数据处理
机器学习:基于概率的朴素贝叶斯分类器详解--Python实现以及项目实战
机器学习:基于概率的朴素贝叶斯分类器详解--Python实现以及项目实战
360 0
机器学习:基于概率的朴素贝叶斯分类器详解--Python实现以及项目实战
|
算法 Python
使用Python实现贝叶斯分类器-------文章中有源码
使用Python实现贝叶斯分类器-------文章中有源码
108 0
使用Python实现贝叶斯分类器-------文章中有源码
|
机器学习/深度学习 算法 测试技术
|
机器学习/深度学习 算法 Python
【机器学习算法-python实现】扫黄神器-朴素贝叶斯分类器的实现
(转载请注明出处:http://blog.csdn.net/buptgshengod) 1.背景      以前我在外面公司实习的时候,一个大神跟我说过,学计算机就是要一个一个贝叶斯公式的套用来套用去。嗯,现在终于用到了。朴素贝叶斯分类器据说是好多扫黄软件使用的算法,贝叶斯公式也比较简单,大学做概率题经常会用到。核心思想就是找出特征值对结果影响概率最大的项。公式如下:        什么是朴
991 0
|
1天前
|
机器学习/深度学习 Linux Python
Python编程教学
Python教学
24 13
|
1天前
|
机器学习/深度学习 数据挖掘 开发者
探索Python编程:从基础到实战
【9月更文挑战第34天】在这篇文章中,我们将一起踏上Python编程的旅程。无论你是初学者还是有一定经验的开发者,这篇文章都将为你提供有价值的信息。我们将从Python的基础语法开始,逐步深入到更复杂的主题,如面向对象编程和网络应用开发。我们还将探讨如何在实际项目中应用这些知识,以及如何通过持续学习和实践来提高你的编程技能。让我们一起探索Python的世界,发现它的无限可能!
|
2天前
|
机器学习/深度学习 人工智能 数据可视化
Python比较适合哪些场景的编程?
Python比较适合哪些场景的编程?
14 7
下一篇
无影云桌面