0


Python实现朴素贝叶斯分类器

朴素贝叶斯分类器

文章目录



一、贝叶斯分类器是什么?

贝叶斯分类器是以贝叶斯决策论为基础的一类分类器。和频率决策论不同,贝叶斯决策论使用后验概率来计算将某个数据data分类为某一类c的风险概率。对分类任务来说,在所有相关概率都已知的理想情况下,贝叶斯决策论考虑如何基于这些概率和误判损失来选择最优的类别标记。

贝叶斯判定准则

假设对于数据集D,有N种可能的类别标记,即

  1. Y
  2. =
  3. {
  4. c
  5. 1
  6. ,
  7. c
  8. 2
  9. .
  10. .
  11. .
  12. c
  13. n
  14. ,
  15. }
  16. Y=\{c_{1},c_{2}...c_{n},\}
  17. Y={c1​,c2​...cn​,},
  18. λ
  19. i
  20. j
  21. \lambda_{ij}
  22. λij​是将一个真实标记为
  23. c
  24. j
  25. c_{j}
  26. cj​的样本误分类为
  27. c
  28. i
  29. c_{i}
  30. ci​的损失,基于后验概率
  31. P
  32. (
  33. c
  34. i
  35. x
  36. )
  37. P(c_{i}|x)
  38. P(ci​∣x)可获得将样本x分类为
  39. c
  40. i
  41. c_{i}
  42. ci​所产生的期望损失,即在样本x上的“条件概率”。
  43. R
  44. (
  45. c
  46. i
  47. x
  48. )
  49. =
  50. j
  51. =
  52. i
  53. N
  54. λ
  55. i
  56. j
  57. P
  58. (
  59. c
  60. j
  61. x
  62. )
  63. R(c_{i}|x)=\sum^{N}_{j=i}{\lambda_{ij}P(c_{j}|x)}
  64. R(ci​∣x)=j=iN​λijP(cj​∣x)

我们的任务就是寻找一个判定标准

  1. h
  2. :
  3. X
  4. Y
  5. h:X\rightarrow Y
  6. h:XY以最小化总体风险。
  7. R
  8. (
  9. h
  10. )
  11. =
  12. E
  13. x
  14. [
  15. R
  16. (
  17. h
  18. (
  19. x
  20. )
  21. x
  22. )
  23. ]
  24. R(h)=E_{x}[R(h(x)|x)]
  25. R(h)=Ex​[R(h(x)∣x)]

对于每个样本x,若h能以最小化条件风险R(h(x)|x),则总体风险R(h)也将被最小化。这就产生了贝叶斯判定准则(Bayes decision rule):为最小化总体风险,只需在每个样本上选择那个能使条件风险R(c|x)最小的类别标记,即

  1. h
  2. (
  3. x
  4. )
  5. =
  6. a
  7. r
  8. g
  9. m
  10. i
  11. n
  12. c
  13. Y
  14. R
  15. (
  16. c
  17. x
  18. )
  19. h^{*}(x)=arg\quad min_{c\in Y}{R(c|x)}
  20. h∗(x)=argmincYR(cx)此时,
  21. h
  22. h^{*}
  23. h∗称为贝叶斯最优分类器,与之对应的总体风险R(h*)称为在贝叶斯风险。

具体来说,若目标是最小化分类风险,那么

  1. λ
  2. i
  3. j
  4. =
  5. {
  6. 0
  7. i
  8. f
  9. i
  10. =
  11. j
  12. 1
  13. o
  14. t
  15. h
  16. e
  17. r
  18. w
  19. i
  20. s
  21. e
  22. \lambda_{ij}=\begin{cases}0&if\quad i=j\\1&otherwise\end{cases}
  23. λij​={01ifi=jotherwise

此时条件风险

  1. R
  2. (
  3. c
  4. x
  5. )
  6. =
  7. 1
  8. P
  9. (
  10. c
  11. x
  12. )
  13. R(c|x)=1-P(c|x)
  14. R(cx)=1P(cx)于是,最小化分类错误率的贝叶斯最优分类器为
  15. h
  16. (
  17. x
  18. )
  19. =
  20. a
  21. r
  22. g
  23. m
  24. a
  25. x
  26. c
  27. Y
  28. P
  29. (
  30. c
  31. x
  32. )
  33. (
  34. 1.1
  35. )
  36. h^{*}(x)=arg\quad max_{c\in Y}P(c|x)\quad(1.1)
  37. h∗(x)=argmaxcYP(cx)(1.1) ,即对每个样本x,选择能使后验概率
  38. P
  39. (
  40. c
  41. x
  42. )
  43. P(c|x)
  44. P(cx)最大的类别标记。基于贝叶斯定理,
  45. P
  46. (
  47. c
  48. x
  49. )
  50. P(c|x)
  51. P(cx)可写为
  52. P
  53. (
  54. c
  55. x
  56. )
  57. =
  58. P
  59. (
  60. c
  61. )
  62. P
  63. (
  64. x
  65. c
  66. )
  67. P
  68. (
  69. x
  70. )
  71. (
  72. 1.2
  73. )
  74. P(c|x)=\dfrac{P(c)P(x|c)}{P(x)}\quad(1.2)
  75. P(cx)=P(x)P(c)P(xc)​(1.2),其中,
  76. P
  77. (
  78. c
  79. )
  80. P(c)
  81. P(c)是类“先验(prior)”概率;
  82. P
  83. (
  84. x
  85. c
  86. )
  87. P(x|c)
  88. P(xc)是样本x相对于类别标记c的条件概率。

朴素贝叶斯分类器

不难发现,基于贝叶斯公式来估计后验概率

  1. P
  2. (
  3. c
  4. x
  5. )
  6. P(c|x)
  7. P(cx)的主要难度在于类条件概率
  8. P
  9. (
  10. x
  11. c
  12. )
  13. P(x|c)
  14. P(xc)是所有属性的联合概率,难以从有限的训练集上进行直接计算。为了避开这个坑,朴素贝叶斯分类器的做法是,假设所有属性都互相独立。那么,基于属性条件独立假设,式(1.2)可重写为
  15. P
  16. (
  17. c
  18. x
  19. )
  20. =
  21. P
  22. (
  23. c
  24. )
  25. P
  26. (
  27. x
  28. )
  29. i
  30. =
  31. 1
  32. d
  33. P
  34. (
  35. x
  36. i
  37. c
  38. )
  39. (
  40. 1.3
  41. )
  42. P(c|x)=\dfrac{P(c)}{P(x)}\prod^{d}_{i=1}{P(x_{i}|c)}\quad(1.3)
  43. P(cx)=P(x)P(c)​i=1dP(xi​∣c)(1.3)

其中

  1. d
  2. d
  3. d为属性数目,
  4. x
  5. i
  6. x_{i}
  7. xi​为
  8. x
  9. \mathbf{x}
  10. x在第
  11. i
  12. i
  13. i个属性上的取值。

由于对于所有类别来说

  1. P
  2. (
  3. x
  4. )
  5. P(x)
  6. P(x)相同,因此基于式(1.1)的贝叶斯判定准则有
  7. h
  8. n
  9. b
  10. (
  11. x
  12. )
  13. =
  14. a
  15. r
  16. g
  17. m
  18. a
  19. x
  20. c
  21. Y
  22. P
  23. (
  24. c
  25. )
  26. i
  27. =
  28. 1
  29. d
  30. P
  31. (
  32. x
  33. i
  34. c
  35. )
  36. h_{nb}(x)=argmax_{c\in Y}P(c)\prod^{d}_{i=1}P(x_{i}|c)
  37. hnb​(x)=argmaxcYP(c)i=1dP(xi​∣c)。

显然,朴素贝叶斯分类器的训练过程就是基于训练集D来估计先验概率

  1. P
  2. (
  3. c
  4. )
  5. P(c)
  6. P(c),并为每个属性估计条件概率
  7. P
  8. (
  9. x
  10. i
  11. c
  12. )
  13. P(x_{i}|c)
  14. P(xi​∣c)。令
  15. D
  16. c
  17. D_{c}
  18. Dc​表示训练集D种第
  19. c
  20. c
  21. c类样本组成的集合,若有充足的独立同分布样本,则可容易地估计出类先验概率
  22. P
  23. (
  24. c
  25. )
  26. =
  27. D
  28. c
  29. D
  30. P(c)=\dfrac{|D_{c}|}{|D|}
  31. P(c)=∣D∣∣Dc​∣​。

对于离散属性而言,令

  1. D
  2. c
  3. ,
  4. x
  5. i
  6. D_{c,x_{i}}
  7. Dc,xi​​表示
  8. D
  9. c
  10. D_{c}
  11. Dc​中在第
  12. i
  13. i
  14. i个属性上取值为
  15. x
  16. i
  17. x_{i}
  18. xi​的样本组成的集合,则条件概率
  19. P
  20. x
  21. i
  22. c
  23. Px_{i}|c
  24. Pxi​∣c)可估计为
  25. P
  26. (
  27. x
  28. i
  29. c
  30. )
  31. =
  32. D
  33. c
  34. ,
  35. x
  36. i
  37. D
  38. c
  39. P(x_{i}|c)=\dfrac{|D_{c,x_{i}}|}{|D_{c}|}
  40. P(xi​∣c)=∣Dc​∣∣Dc,xi​​∣​。

对于连续属性可考虑概率密度函数,假定

  1. p
  2. (
  3. x
  4. i
  5. c
  6. )
  7. N
  8. (
  9. μ
  10. c
  11. ,
  12. i
  13. ,
  14. σ
  15. c
  16. ,
  17. i
  18. 2
  19. )
  20. p(x_{i}|c)~\mathcal{N}(\mu_{c,i},\sigma^{2}_{c,i})
  21. p(xi​∣c) Nc,i​,σc,i2​),其中
  22. μ
  23. c
  24. ,
  25. i
  26. \mu_{c,i}
  27. μc,i​和
  28. σ
  29. c
  30. ,
  31. i
  32. 2
  33. \sigma^{2}_{c,i}
  34. σc,i2​分别是第
  35. c
  36. c
  37. c类样本在第
  38. i
  39. i
  40. i个属性上取值的均值和方差,则有
  41. p
  42. (
  43. x
  44. i
  45. c
  46. )
  47. =
  48. 1
  49. 2
  50. π
  51. σ
  52. c
  53. ,
  54. i
  55. e
  56. x
  57. p
  58. (
  59. (
  60. x
  61. i
  62. μ
  63. c
  64. ,
  65. i
  66. )
  67. 2
  68. 2
  69. σ
  70. c
  71. ,
  72. i
  73. 2
  74. )
  75. p(x_{i}|c)=\dfrac{1}{\sqrt{2\pi }\sigma_{c,i}}exp(-\dfrac{(x_{i}-\mu_{c,i})^{2}}{2\sigma^{2}_{c,i}})
  76. p(xi​∣c)=2π​σc,i1exp(−2σc,i2​(xi​−μc,i​)2​)

举个栗子

在这里插入图片描述
如上图所示的西瓜数据集,对测试样例编号1进行分类。对于先验概率

  1. P
  2. (
  3. c
  4. )
  5. P(c)
  6. P(c),有
  7. P
  8. (
  9. =
  10. )
  11. =
  12. 8
  13. 17
  14. P(好瓜=是)=\dfrac{8}{17}
  15. P(好瓜=是)=178
  16. P
  17. (
  18. =
  19. )
  20. =
  21. 9
  22. 17
  23. P(好瓜=否)=\dfrac{9}{17}
  24. P(好瓜=否)=179

然后为每个属性估计条件概率

  1. P
  2. (
  3. x
  4. i
  5. c
  6. )
  7. P(x_{i}|c)
  8. P(xi​∣c):
  9. P
  10. 绿
  11. =
  12. P
  13. (
  14. =
  15. 绿
  16. =
  17. )
  18. =
  19. 3
  20. 8
  21. P_{青绿|是}=P(色泽=青绿|好瓜=是)=\dfrac{3}{8}
  22. P青绿∣是​=P(色泽=青绿∣好瓜=是)=83
  23. P
  24. =
  25. P
  26. (
  27. =
  28. =
  29. )
  30. =
  31. 5
  32. 8
  33. P_{蜷缩|是}=P(根蒂=蜷缩|好瓜=是)=\dfrac{5}{8}
  34. P蜷缩∣是​=P(根蒂=蜷缩∣好瓜=是)=85​…
  35. p
  36. 0.697
  37. =
  38. p
  39. (
  40. =
  41. 0.697
  42. =
  43. )
  44. =
  45. 1
  46. 2
  47. π
  48. 0.129
  49. e
  50. x
  51. p
  52. (
  53. (
  54. 0.697
  55. 0.574
  56. )
  57. 2
  58. 2
  59. 0.12
  60. 9
  61. 2
  62. )
  63. p_{密度:0.697|是}=p(密度=0.697|好瓜=是)=\dfrac{1}{\sqrt{2\pi}*0.129}exp(-\dfrac{(0.697-0.574)^{2}}{2*0.129^{2}})
  64. p密度:0.697∣是​=p(密度=0.697∣好瓜=是)=2π​∗0.1291exp(−20.1292(0.6970.574)2​)

其余属性条件概率略
最后,

  1. P
  2. (
  3. =
  4. )
  5. 0.063
  6. P(好瓜=是)\approx 0.063
  7. P(好瓜=是)≈0.063
  8. P
  9. (
  10. =
  11. )
  12. 6.80
  13. 1
  14. 0
  15. 5
  16. P(好瓜=否)\approx 6.80*10^{-5}
  17. P(好瓜=否)≈6.80105

由于

  1. 0.063
  2. >
  3. 6.80
  4. 1
  5. 0
  6. 5
  7. 0.063>6.80*10^{-5}
  8. 0.063>6.80105因此将样例1判定为“好瓜”。

二、相关代码

1.数据处理

该数据集是我通过西瓜书上的西瓜数据集随机生成的10000条数据。需要的评论留言。

代码如下(示例):

  1. import numpy as np
  2. import pandas as pd
  3. data=pd.read_csv("DataOrDocu/NewWatermelon2.csv",index_col=0)
  4. attributes=data.columns
  5. path="DataOrDocu/PosterProbDict.npy"
  6. feature=data[:,:-1]
  7. label=data[:,-1]
  8. featureTrain,featureTest,labelTrain,labelTest=train_test_split(feature,label,train_size=0.7,random_state=10)
  9. labelTrain=np.reshape(labelTrain,(labelTrain.shape[0],1))
  10. labelTest=np.reshape(labelTest,(labelTest.shape[0],1))
  11. dataTrain=np.concatenate((featureTrain,labelTrain),axis=1)
  12. dataTrain=pd.DataFrame(dataTrain,columns=attributes,index=None)
  13. dataTest=np.concatenate((featureTest,labelTest),axis=1)
  14. dataTest=pd.DataFrame(dataTest,columns=attributes,index=None)

2.生成朴素贝叶斯表(字典)

逻辑很简单,即根据式(1.3),先计算《好瓜=是|否》的先验概率,即

  1. P
  2. (
  3. =
  4. )
  5. P(好瓜=是)
  6. P(好瓜=是)和
  7. P
  8. (
  9. =
  10. )
  11. P(好瓜=否)
  12. P(好瓜=否),并以字典形式返回。然后计算各种条件概率比如
  13. P
  14. (
  15. =
  16. 绿
  17. =
  18. )
  19. P(色泽=青绿|好瓜=是)
  20. P(色泽=青绿∣好瓜=是)等等,如果是离散属性,那么保存
  21. P
  22. (
  23. a
  24. =
  25. a
  26. i
  27. =
  28. o
  29. r
  30. )
  31. P(a=a_{i}|好瓜=是or否)
  32. P(a=ai​∣好瓜=是or否)等一系列条件概率;如果是连续属性,那么保存
  33. p
  34. ,
  35. a
  36. p_{好瓜,属性a}
  37. p好瓜,属性a​的均值和方差。最后,将生成的字典保存成npy文件,方便后续使用。

关于如何判断属性的连续或离散性

此外,有一个问题其中有一个函数,用于判断某个属性是离散属性还是连续属性,我考虑了2种方案,但实际上并不都是完美的逻辑,只是针对具体的数据集具有逻辑的相对完备性。一是判断数据是否为字符类型,一般字符类型将其判断为离散属性,其他判断为连续属性,但很容易在其他数据集上发现例外;二是计算某属性的所有数据集中包含的值的所有种类,如果种类数量<一定的范围,那么,我即认定为其为离散值,大于该范围的,认定其为连续值。但当遇到稀疏数据时,此类办法也会经常失效。

具体代码如下:

  1. import numpy as np
  2. defPosteriorProbDivided(data,attributes,label,path):
  3. priorProba={}
  4. length=data.shape[0]
  5. labelKinds=KindsGet(data,label)#获取标签的所有类别
  6. posterProbTable={}try:for i in labelKinds:
  7. dataTemp=data.loc[data[label]==i]
  8. tempLength=dataTemp.shape[0]
  9. tempPrior=tempLength/length
  10. priorProba.update({i:tempPrior})
  11. tempAttr ={}# 用于保存所有属性的条件概率for j in attributes:if IfDivideAttr(data,j):
  12. tempPosterProb=DivCondiProba(data,j,length)
  13. tempAttr.update({j:tempPosterProb})#将该属性的条件概率保存else:
  14. averageVar=ContiCondiProba(data,j)#如果该属性是连续值,那么将该属性的平均值和方差求出,并保存
  15. tempAttr.update({j:averageVar})
  16. posterProbTable.update({i:tempAttr})try:
  17. np.save(path,posterProbTable)except FileExistsError as error:print(error)return priorProba
  18. except IndexError as error:print(error)defIfDivideAttr(data,attribute):#第一种判断属性离散还是连续的函数
  19. values=np.unique(data[attribute]).shape[0]#获取某一属性的值的种类
  20. length=data.shape[0]if values!=0:if values<=length/10:#如果某一属性的取值数量小于等于总数据量的十分之一,即判定其为离散值returnTrueelse:returnFalsedefIfDivideAttr2(data,attribute):#第二种判断属性离散还是连续的函数returnnotisinstance(data[attribute],float)defKindsGet(data,attribute):#用于将离散属性的所有值返回if IfDivideAttr(data,attribute):
  21. values=np.unique(np.array(data[attribute]))return values
  22. returnNonedefDivCondiProba(data,attribute,length):#计算某一离散属性的条件概率
  23. tempAttrValues = KindsGet(data, attribute)
  24. tempPosterProb ={}# 用于保存某一属性的后验概率for k in tempAttrValues:
  25. tempAttrPoster = data.loc[data[attribute]== k].shape[0]/ length # 计算出当某属性a的值为k时,其在标签c上的条件概率P(k|c),并将其压进列表
  26. tempPosterProb.update({k: tempAttrPoster})return tempPosterProb
  27. defContiCondiProba(data,attribute):#计算某一连续属性的平均值和方差
  28. contiValue=data[attribute]
  29. contiValue=np.array(contiValue)
  30. average=np.average(contiValue)
  31. variance=np.var(contiValue)return average,variance

根据朴素贝叶斯表计算预测标签

针对某个数据的每一个属性对应的值,如果是离散属性,那么就从表中获取,如果是离散属性,那么就根据表中的均值和方差计算条件概率。但是区别于式(1.3),在程序中我对连乘做了一个取对数,防止指数爆炸(方正就是防止差距过大)。然后一个判断正确率的函数,单纯计算预测数据中的正确比例。

  1. defPosteriorFind(data,posterProbTabel,priorProba):#用于计算某单个数据的最后标签
  2. posterValues=[]#用于保存每一个标签的后验概率
  3. bayesProba=0for label in posterProbTabel:for attribute in posterProbTabel[label]:# attrValue=list(attribute.keys())[0] #取出字典键值对中的健if IfDivideAttr2(data,attribute):
  4. tempValue=np.log(posterProbTabel[label][attribute][data[attribute]])
  5. bayesProba+=tempValue
  6. else:
  7. averageVar=posterProbTabel[label][attribute]
  8. xi=data[attribute]
  9. average,variance=averageVar[0],averageVar[1]
  10. tempValue=1/(np.square(2*pi)*variance)*np.exp(-(xi-average)**2/2*variance**2)
  11. tempValue=np.log(tempValue)
  12. bayesProba+=tempValue
  13. labelKey=label #取出label的key
  14. labelPrior=priorProba[labelKey]
  15. bayesProba+=np.log(labelPrior)#将该循环内的标签c所对应的先验概率加入其中
  16. posterValues.append(bayesProba)
  17. bayesProba=0
  18. posterDict=zip(posterValues,list(posterProbTabel.keys()))
  19. posterDict=dict(posterDict)
  20. bestValue=np.max(posterValues)
  21. bestLabel=posterDict[bestValue]return bestLabel
  22. defAccCal(data,label,PosterProbaTabel,priorProba):
  23. length=data.shape[0]
  24. acc=0for i inrange(data.shape[0]):
  25. labelPre=PosteriorFind(data.loc[i],PosterProbaTabel,priorProba)if labelPre==data[label][i]:
  26. acc+=1
  27. ratio=acc/length
  28. return ratio

总结

使用随机生成的10000条数据,按照0.7训练集,0.3测试集的比例。最后的正确率大概是百分之四十几
在这里插入图片描述
之后又使用了一下鸢尾花的数据集
结果如下正确率是百分之三十一(可以说是很辣鸡了
在这里插入图片描述
最后附上sklearn的高斯贝叶斯和决策树跑鸢尾花的正确率
在这里插入图片描述
要不怎么说人家是专业的呢(doge


本文转载自: https://blog.csdn.net/lyx369639/article/details/125600236
版权归原作者 山隆木对 所有, 如有侵权,请联系我们删除。

“Python实现朴素贝叶斯分类器”的评论:

还没有评论