python实现朴素贝叶斯分类器

yipeiwu_com6年前Python基础

本文用的是sciki-learn库的iris数据集进行测试。用的模型也是最简单的,就是用贝叶斯定理P(A|B) = P(B|A)*P(A)/P(B),计算每个类别在样本中概率(代码中是pLabel变量)

以及每个类下每个特征的概率(代码中是pNum变量)。

写得比较粗糙,对于某个类下没有此特征的情况采用p=1/样本数量。

有什么错误有人发现麻烦提出,谢谢。

[python] view plain copy
# -*- coding:utf-8 -*- 
from numpy import * 
from sklearn import datasets 
import numpy as np 
 
class NaiveBayesClassifier(object): 
 
  def __init__(self): 
    self.dataMat = list() 
    self.labelMat = list() 
    self.pLabel = {} 
    self.pNum = {} 
 
  def loadDataSet(self): 
    iris = datasets.load_iris() 
    self.dataMat = iris.data 
    self.labelMat = iris.target 
    labelSet = set(iris.target) 
    labelList = [i for i in labelSet] 
    labelNum = len(labelList) 
    for i in range(labelNum): 
      self.pLabel.setdefault(labelList[i]) 
      self.pLabel[labelList[i]] = np.sum(self.labelMat==labelList[i])/float(len(self.labelMat)) 
 
  def seperateByClass(self): 
    seperated = {} 
    for i in range(len(self.dataMat)): 
      vector = self.dataMat[i] 
      if self.labelMat[i] not in seperated: 
        seperated[self.labelMat[i]] = [] 
      seperated[self.labelMat[i]].append(vector) 
    return seperated 
 
  # 通过numpy array二维数组来获取每一维每种数的概率 
  def getProbByArray(self, data): 
    prob = {} 
    for i in range(len(data[0])): 
      if i not in prob: 
        prob[i] = {} 
      dataSetList = list(set(data[:, i])) 
      for j in dataSetList: 
        if j not in prob[i]: 
          prob[i][j] = 0 
        prob[i][j] = np.sum(data[:, i] == j) / float(len(data[:, i])) 
    prob[0] = [1 / float(len(data[:,0]))] # 防止feature不存在的情况 
    return prob 
 
  def train(self): 
    featureNum = len(self.dataMat[0]) 
    seperated = self.seperateByClass() 
    t_pNum = {} # 存储每个类别下每个特征每种情况出现的概率 
    for label, data in seperated.iteritems(): 
      if label not in t_pNum: 
        t_pNum[label] = {} 
      t_pNum[label] = self.getProbByArray(np.array(data)) 
    self.pNum = t_pNum 
 
  def classify(self, data): 
    label = 0 
    pTest = np.ones(3) 
    for i in self.pLabel: 
      for j in self.pNum[i]: 
        if data[j] not in self.pNum[i][j]: 
          pTest[i] *= self.pNum[i][0][0] 
        else: 
          pTest[i] *= self.pNum[i][j][data[j]] 
    pMax = np.max(pTest) 
    ind = np.where(pTest == pMax) 
    return ind[0][0] 
 
  def test(self): 
    self.loadDataSet() 
    self.train() 
    pred = [] 
    right = 0 
    for d in self.dataMat: 
      pred.append(self.classify(d)) 
    for i in range(len(self.labelMat)): 
      if pred[i] == self.labelMat[i]: 
        right += 1 
    print right / float(len(self.labelMat)) 
 
if __name__ == '__main__': 
  NB = NaiveBayesClassifier() 
  NB.test() 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Pytorch入门之mnist分类实例

本文实例为大家分享了Pytorch入门之mnist分类的具体代码,供大家参考,具体内容如下 #!/usr/bin/env python # -*- coding: utf-8 -*-...

python+opencv实现车牌定位功能(实例代码)

python+opencv实现车牌定位功能(实例代码)

写在前面 HIT大三上学期视听觉信号处理课程中视觉部分的实验三,经过和学长们实验的对比发现每一级实验要求都不一样,因此这里标明了是2019年秋季学期的视觉实验三。 由于时间紧张,代码没有...

python 实现矩阵按对角线打印

python 实现矩阵按对角线打印

如下所示: Description: 将一个矩阵(二维数组)按对角线向右进行打印。(搜了一下发现好像是美团某次面试要求半小时手撕的题) Example: Input: [ [1,2,...

教你用Python写安卓游戏外挂

教你用Python写安卓游戏外挂

本次我们选择的安卓游戏对象叫“单词英雄”,大家可以先下载这个游戏。 游戏的界面是这样的: 通过选择单词的意思进行攻击,选对了就正常攻击,选错了就象征性的攻击一下。玩了一段时间之后琢磨可...

Python 元组拆包示例(Tuple Unpacking)

1.元组? 元组的特点: 相当于不可变得列表; 可用于没有字段名的记录。 pythn里的元组就相当于C语言里的数组,是不可变的,但是也可以容纳不同类型的元素,也是容器的一种。 >...