我发现朴素贝叶斯的过程很难理解,我想知道是否有人能用英语解释一个简单的一步一步的过程。我知道它以发生次数为概率进行比较,但我不知道训练数据如何与实际数据集相关。

请给我解释一下训练集的作用。我在这里举一个非常简单的水果例子,比如香蕉

training set---
round-red
round-orange
oblong-yellow
round-red

dataset----
round-red
round-orange
round-red
round-orange
oblong-yellow
round-red
round-orange
oblong-yellow
oblong-yellow
round-red

当前回答

Ram Narasimhan explained the concept very nicely here below is an alternative explanation through the code example of Naive Bayes in action It uses an example problem from this book on page 351 This is the data set that we will be using In the above dataset if we give the hypothesis = {"Age":'<=30', "Income":"medium", "Student":'yes' , "Creadit_Rating":'fair'} then what is the probability that he will buy or will not buy a computer. The code below exactly answers that question. Just create a file called named new_dataset.csv and paste the following content.

Age,Income,Student,Creadit_Rating,Buys_Computer
<=30,high,no,fair,no
<=30,high,no,excellent,no
31-40,high,no,fair,yes
>40,medium,no,fair,yes
>40,low,yes,fair,yes
>40,low,yes,excellent,no
31-40,low,yes,excellent,yes
<=30,medium,no,fair,no
<=30,low,yes,fair,yes
>40,medium,yes,fair,yes
<=30,medium,yes,excellent,yes
31-40,medium,no,excellent,yes
31-40,high,yes,fair,yes
>40,medium,no,excellent,no

下面是代码,注释解释了我们在这里所做的一切!(python)

import pandas as pd 
import pprint 

class Classifier():
    data = None
    class_attr = None
    priori = {}
    cp = {}
    hypothesis = None


    def __init__(self,filename=None, class_attr=None ):
        self.data = pd.read_csv(filename, sep=',', header =(0))
        self.class_attr = class_attr

    '''
        probability(class) =    How many  times it appears in cloumn
                             __________________________________________
                                  count of all class attribute
    '''
    def calculate_priori(self):
        class_values = list(set(self.data[self.class_attr]))
        class_data =  list(self.data[self.class_attr])
        for i in class_values:
            self.priori[i]  = class_data.count(i)/float(len(class_data))
        print "Priori Values: ", self.priori

    '''
        Here we calculate the individual probabilites 
        P(outcome|evidence) =   P(Likelihood of Evidence) x Prior prob of outcome
                               ___________________________________________
                                                    P(Evidence)
    '''
    def get_cp(self, attr, attr_type, class_value):
        data_attr = list(self.data[attr])
        class_data = list(self.data[self.class_attr])
        total =1
        for i in range(0, len(data_attr)):
            if class_data[i] == class_value and data_attr[i] == attr_type:
                total+=1
        return total/float(class_data.count(class_value))

    '''
        Here we calculate Likelihood of Evidence and multiple all individual probabilities with priori
        (Outcome|Multiple Evidence) = P(Evidence1|Outcome) x P(Evidence2|outcome) x ... x P(EvidenceN|outcome) x P(Outcome)
        scaled by P(Multiple Evidence)
    '''
    def calculate_conditional_probabilities(self, hypothesis):
        for i in self.priori:
            self.cp[i] = {}
            for j in hypothesis:
                self.cp[i].update({ hypothesis[j]: self.get_cp(j, hypothesis[j], i)})
        print "\nCalculated Conditional Probabilities: \n"
        pprint.pprint(self.cp)

    def classify(self):
        print "Result: "
        for i in self.cp:
            print i, " ==> ", reduce(lambda x, y: x*y, self.cp[i].values())*self.priori[i]

if __name__ == "__main__":
    c = Classifier(filename="new_dataset.csv", class_attr="Buys_Computer" )
    c.calculate_priori()
    c.hypothesis = {"Age":'<=30', "Income":"medium", "Student":'yes' , "Creadit_Rating":'fair'}

    c.calculate_conditional_probabilities(c.hypothesis)
    c.classify()

输出:

Priori Values:  {'yes': 0.6428571428571429, 'no': 0.35714285714285715}

Calculated Conditional Probabilities: 

{
 'no': {
        '<=30': 0.8,
        'fair': 0.6, 
        'medium': 0.6, 
        'yes': 0.4
        },
'yes': {
        '<=30': 0.3333333333333333,
        'fair': 0.7777777777777778,
        'medium': 0.5555555555555556,
        'yes': 0.7777777777777778
      }
}

Result: 
yes  ==>  0.0720164609053
no  ==>  0.0411428571429

其他回答

Ram Narasimhan explained the concept very nicely here below is an alternative explanation through the code example of Naive Bayes in action It uses an example problem from this book on page 351 This is the data set that we will be using In the above dataset if we give the hypothesis = {"Age":'<=30', "Income":"medium", "Student":'yes' , "Creadit_Rating":'fair'} then what is the probability that he will buy or will not buy a computer. The code below exactly answers that question. Just create a file called named new_dataset.csv and paste the following content.

Age,Income,Student,Creadit_Rating,Buys_Computer
<=30,high,no,fair,no
<=30,high,no,excellent,no
31-40,high,no,fair,yes
>40,medium,no,fair,yes
>40,low,yes,fair,yes
>40,low,yes,excellent,no
31-40,low,yes,excellent,yes
<=30,medium,no,fair,no
<=30,low,yes,fair,yes
>40,medium,yes,fair,yes
<=30,medium,yes,excellent,yes
31-40,medium,no,excellent,yes
31-40,high,yes,fair,yes
>40,medium,no,excellent,no

下面是代码,注释解释了我们在这里所做的一切!(python)

import pandas as pd 
import pprint 

class Classifier():
    data = None
    class_attr = None
    priori = {}
    cp = {}
    hypothesis = None


    def __init__(self,filename=None, class_attr=None ):
        self.data = pd.read_csv(filename, sep=',', header =(0))
        self.class_attr = class_attr

    '''
        probability(class) =    How many  times it appears in cloumn
                             __________________________________________
                                  count of all class attribute
    '''
    def calculate_priori(self):
        class_values = list(set(self.data[self.class_attr]))
        class_data =  list(self.data[self.class_attr])
        for i in class_values:
            self.priori[i]  = class_data.count(i)/float(len(class_data))
        print "Priori Values: ", self.priori

    '''
        Here we calculate the individual probabilites 
        P(outcome|evidence) =   P(Likelihood of Evidence) x Prior prob of outcome
                               ___________________________________________
                                                    P(Evidence)
    '''
    def get_cp(self, attr, attr_type, class_value):
        data_attr = list(self.data[attr])
        class_data = list(self.data[self.class_attr])
        total =1
        for i in range(0, len(data_attr)):
            if class_data[i] == class_value and data_attr[i] == attr_type:
                total+=1
        return total/float(class_data.count(class_value))

    '''
        Here we calculate Likelihood of Evidence and multiple all individual probabilities with priori
        (Outcome|Multiple Evidence) = P(Evidence1|Outcome) x P(Evidence2|outcome) x ... x P(EvidenceN|outcome) x P(Outcome)
        scaled by P(Multiple Evidence)
    '''
    def calculate_conditional_probabilities(self, hypothesis):
        for i in self.priori:
            self.cp[i] = {}
            for j in hypothesis:
                self.cp[i].update({ hypothesis[j]: self.get_cp(j, hypothesis[j], i)})
        print "\nCalculated Conditional Probabilities: \n"
        pprint.pprint(self.cp)

    def classify(self):
        print "Result: "
        for i in self.cp:
            print i, " ==> ", reduce(lambda x, y: x*y, self.cp[i].values())*self.priori[i]

if __name__ == "__main__":
    c = Classifier(filename="new_dataset.csv", class_attr="Buys_Computer" )
    c.calculate_priori()
    c.hypothesis = {"Age":'<=30', "Income":"medium", "Student":'yes' , "Creadit_Rating":'fair'}

    c.calculate_conditional_probabilities(c.hypothesis)
    c.classify()

输出:

Priori Values:  {'yes': 0.6428571428571429, 'no': 0.35714285714285715}

Calculated Conditional Probabilities: 

{
 'no': {
        '<=30': 0.8,
        'fair': 0.6, 
        'medium': 0.6, 
        'yes': 0.4
        },
'yes': {
        '<=30': 0.3333333333333333,
        'fair': 0.7777777777777778,
        'medium': 0.5555555555555556,
        'yes': 0.7777777777777778
      }
}

Result: 
yes  ==>  0.0720164609053
no  ==>  0.0411428571429

公认的答案有许多k-NN (k-nearest neighbors)元素,这是一种不同的算法。

k-NN和NaiveBayes都是分类算法。从概念上讲,k-NN使用“接近度”的思想对新实体进行分类。在k-NN中,“接近度”是用欧几里得距离或余弦距离等思想建模的。相比之下,在朴素贝叶斯中,“概率”的概念被用于对新实体进行分类。

因为这个问题是关于朴素贝叶斯的,下面是我如何向别人描述的想法和步骤。我会尽量用更少的方程用更简单的英语来做。

首先,条件概率和贝叶斯规则

在人们能够理解和欣赏朴素贝叶斯的细微差别之前,他们需要首先了解几个相关的概念,即条件概率的概念和贝叶斯规则。(如果你熟悉这些概念,请跳过标题为“获取朴素贝叶斯”的部分)

简单来说,条件概率是指在已经发生的情况下,某件事发生的概率。

假设存在某个结果O和某个证据E。根据这些概率的定义:同时拥有结果O和证据E的概率是: (O发生的概率)乘以(假设O发生时E的概率)

一个理解条件概率的例子:

假设我们有一群美国参议员。参议员可以是民主党人也可以是共和党人。他们也是男性或女性。

如果我们完全随机选择一名参议员,这个人是民主党女性的概率是多少?条件概率可以帮我们回答这个问题。

(民主党和女性参议员)的概率=概率(参议员是民主党人)乘以女性是民主党人的条件概率。

  P(Democrat & Female) = P(Democrat) * P(Female | Democrat) 

我们可以用相反的方式计算出完全相同的东西

  P(Democrat & Female) = P(Female) * P(Democrat | Female) 

理解贝叶斯规则

从概念上讲,这是从P(证据|已知结果)到P(结果|已知证据)的一种方式。通常,在已知结果的情况下,我们知道观察到某些特定证据的频率。我们必须利用这个已知的事实来计算相反的情况,在有证据的情况下,计算结果发生的几率。

P(已知证据的结果)= P(已知结果的证据)乘以probb(结果),乘以P(证据)

理解贝叶斯规则的经典例子:

Probability of Disease D given Test-positive = 

               P(Test is positive|Disease) * P(Disease)
     _______________________________________________________________
     (scaled by) P(Testing Positive, with or without the disease)

以上只是朴素贝叶斯的序言。

得到朴素贝叶斯

到目前为止,我们只讨论了一项证据。在现实中,我们必须在有多种证据的情况下预测一个结果。在这种情况下,计算就变得非常复杂。为了避免这种复杂性,一种方法是将多个证据“分开”,并将每个证据视为独立的证据。这就是为什么它被称为朴素贝叶斯。

P(Outcome|Multiple Evidence) = 
P(Evidence1|Outcome) * P(Evidence2|outcome) * ... * P(EvidenceN|outcome) * P(Outcome)
scaled by P(Multiple Evidence)

许多人选择这样记:

                      P(Likelihood of Evidence) * Prior prob of outcome
P(outcome|evidence) = _________________________________________________
                                         P(Evidence)

注意这个等式的一些事情:

If the Prob(evidence|outcome) is 1, then we are just multiplying by 1. If the Prob(some particular evidence|outcome) is 0, then the whole prob. becomes 0. If you see contradicting evidence, we can rule out that outcome. Since we divide everything by P(Evidence), we can even get away without calculating it. The intuition behind multiplying by the prior is so that we give high probability to more common outcomes, and low probabilities to unlikely outcomes. These are also called base rates and they are a way to scale our predicted probabilities.

如何应用朴素贝叶斯预测结果?

只需对每个可能的结果运行上面的公式。由于我们正在尝试分类,每个结果被称为一个类,并且它有一个类标签。我们的工作是查看证据,考虑这个类别或那个类别的可能性有多大,并为每个实体分配一个标签。 同样,我们采用一种非常简单的方法:将概率最高的类声明为“获胜者”,并将该类标签分配给该证据组合。

水果的例子

让我们通过一个例子来增加我们的理解:OP要求一个“水果”识别的例子。

假设我们有1000个水果的数据。它们碰巧是香蕉、橙子或其他水果。 我们知道每种水果的3个特征:

是否长 无论是甜还是甜 如果它的颜色是黄色。

这是我们的训练集。我们将用它来预测我们遇到的任何新水果的类型。

Type           Long | Not Long || Sweet | Not Sweet || Yellow |Not Yellow|Total
             ___________________________________________________________________
Banana      |  400  |    100   || 350   |    150    ||  450   |  50      |  500
Orange      |    0  |    300   || 150   |    150    ||  300   |   0      |  300
Other Fruit |  100  |    100   || 150   |     50    ||   50   | 150      |  200
            ____________________________________________________________________
Total       |  500  |    500   || 650   |    350    ||  800   | 200      | 1000
             ___________________________________________________________________

我们可以预先计算很多关于水果收集的事情。

所谓的“先验”概率。(如果我们不知道任何水果属性,这将是我们的猜测。)这是我们的基准利率。

 P(Banana)      = 0.5 (500/1000)
 P(Orange)      = 0.3
 P(Other Fruit) = 0.2

“证据”概率

p(Long)   = 0.5
P(Sweet)  = 0.65
P(Yellow) = 0.8

“可能性”的概率

P(Long|Banana) = 0.8
P(Long|Orange) = 0  [Oranges are never long in all the fruit we have seen.]
 ....

P(Yellow|Other Fruit)     =  50/200 = 0.25
P(Not Yellow|Other Fruit) = 0.75

给定一种水果,如何将其分类?

假设我们已知一种未知水果的特性,并要求对其进行分类。我们被告知,这种水果是长、甜和黄色的。它是香蕉吗?它是橘子吗?还是其他水果?

我们可以一个一个地计算3个结果的数字。然后我们选择概率最高的水果,并根据我们之前的证据(我们的1000个水果训练集)将未知水果“分类”为属于概率最高的类别:

P(Banana|Long, Sweet and Yellow) 
      P(Long|Banana) * P(Sweet|Banana) * P(Yellow|Banana) * P(banana)
    = _______________________________________________________________
                      P(Long) * P(Sweet) * P(Yellow)
                      
    = 0.8 * 0.7 * 0.9 * 0.5 / P(evidence)

    = 0.252 / P(evidence)


P(Orange|Long, Sweet and Yellow) = 0


P(Other Fruit|Long, Sweet and Yellow)
      P(Long|Other fruit) * P(Sweet|Other fruit) * P(Yellow|Other fruit) * P(Other Fruit)
    = ____________________________________________________________________________________
                                          P(evidence)

    = (100/200 * 150/200 * 50/200 * 200/1000) / P(evidence)

    = 0.01875 / P(evidence)

以压倒性的优势(0.252 >> 0.01875),我们将这种甜/长/黄色的水果归类为香蕉。

为什么贝叶斯分类器如此受欢迎?

看看它最终会变成什么。只是一些计数和乘法。我们可以预先计算所有这些项,因此分类变得简单、快速和高效。

设z = 1 / P(证据)。现在我们快速计算以下三个量。

P(Banana|evidence) = z * Prob(Banana) * Prob(Evidence1|Banana) * Prob(Evidence2|Banana) ...
P(Orange|Evidence) = z * Prob(Orange) * Prob(Evidence1|Orange) * Prob(Evidence2|Orange) ...
P(Other|Evidence)  = z * Prob(Other)  * Prob(Evidence1|Other)  * Prob(Evidence2|Other)  ...

将类标签分配给最高的数字,然后就完成了。

尽管名字如此,朴素贝叶斯在某些应用中表现得非常出色。文本分类是它真正的亮点之一。

朴素贝叶斯属于监督机器学习,用于对数据集进行分类。 它用于基于先验知识和独立性假设来预测事物。

他们称之为天真,因为它的假设(它假设数据集中的所有特征都同样重要和独立)是非常乐观的,在大多数现实应用中很少是正确的。

对未知数据集进行决策的是分类算法。它基于贝叶斯定理,该定理描述了基于先验知识的事件的概率。

下图显示了朴素贝叶斯的工作原理

NB预测公式:

如何使用朴素贝叶斯算法?

让我们举一个N.B如何工作的例子

第一步:首先我们找出下图中显示是或否的概率的表的似然。 步骤2:求每个类的后验概率。

Problem: Find out the possibility of whether the player plays in Rainy condition?

P(Yes|Rainy) = P(Rainy|Yes) * P(Yes) / P(Rainy)

P(Rainy|Yes) = 2/9 = 0.222
P(Yes) = 9/14 = 0.64
P(Rainy) = 5/14 = 0.36

Now, P(Yes|Rainy) = 0.222*0.64/0.36 = 0.39 which is lower probability which means chances of the match played is low.

更多的参考参考这些博客。

参考GitHub Repository Naive-Bayes-Examples

我试着用一个例子来解释贝叶斯规则。

从社会中随机抽取一个吸烟者的概率是多少?

你可以回答10%,让我们假设这是对的。

现在,如果我说这个随机的人是一个15岁的男人呢?

你可能会说15%或20%,但为什么呢?

事实上,我们试图用新的证据更新我们最初的猜测(P(吸烟者)vs. P(吸烟者|证据))。贝叶斯规则是一种将这两种概率联系起来的方法。

P(smoker | evidence) = P(smoker)* p(evidence | smoker)/P(evidence)

每种证据都可能增加或减少这种可能性。例如,他是男性这一事实可能会增加几率,前提是不吸烟者中的这一比例(作为男性)较低。

换句话说,作为一个男人必须是一个吸烟者,而不是一个不吸烟者。因此,如果一个证据是某件事的指标,它就增加了这种可能性。

但我们怎么知道这是一个指标呢?

对于每个特征,您可以将该特征在给定条件下的共性(概率)与其单独的共性进行比较。(P(f | x) vs P(f))

P(smoker | evidence) / P(smoker) = P(evidence | smoker)/P(evidence)

For example, if we know that 90% of smokers are men, it's not still enough to say whether being a man is an indicator of being smoker or not. For example if the probability of being a man in the society is also 90%, then knowing that someone is a man doesn't help us ((90% / 90%) = 1. But if men contribute to 40% of the society, but 90% of the smokers, then knowing that someone is a man increases the chance of being a smoker (90% / 40%) = 2.25, so it increases the initial guess (10%) by 2.25 resulting 22.5%.

然而,如果在社会上成为男性的概率是95%,那么不管吸烟者中男性的比例很高(90%)!一个人是男性的证据降低了他成为吸烟者的机会!(90% / 95%) = 0.95)。

所以我们有:

P(smoker | f1, f2, f3,... ) = P(smoker) * contribution of f1* contribution of f2 *... 
=
P(smoker)* 
(P(being a man | smoker)/P(being a man))*
(P(under 20 | smoker)/ P(under 20))

请注意,在这个公式中,我们假设是男性和年龄在20岁以下是独立的特征,所以我们将它们相乘,这意味着知道某人年龄在20岁以下对猜测他是男性还是女性没有影响。但这可能不是真的,例如,也许社会中的大多数青少年都是男性……

在分类器中使用这个公式

The classifier is given with some features (being a man and being under 20) and it must decide if he is an smoker or not (these are two classes). It uses the above formula to calculate the probability of each class under the evidence (features), and it assigns the class with the highest probability to the input. To provide the required probabilities (90%, 10%, 80%...) it uses the training set. For example, it counts the people in the training set that are smokers and find they contribute 10% of the sample. Then for smokers checks how many of them are men or women .... how many are above 20 or under 20....In the other words, it tries to build the probability distribution of the features for each class based on the training data.

你的问题在我的理解中分为两部分,第一部分是你需要更好地理解朴素贝叶斯分类器,第二部分是围绕训练集的困惑。

一般来说,所有的机器学习算法都需要训练来完成有监督学习任务,如分类,预测等,或无监督学习任务,如聚类。

在训练步骤中,使用特定的输入数据集(训练集)教授算法,以便稍后我们可以测试它们的未知输入(它们从未见过),它们可以根据它们的学习进行分类或预测等(在监督学习的情况下)。这是大多数机器学习技术,如神经网络,支持向量机,贝叶斯等的基础。

因此,在一般的机器学习项目中,基本上你必须将输入集分为开发集(训练集+开发-测试集)和测试集(或评估集)。请记住,您的基本目标是您的系统学习并分类它们从未在Dev集中或测试集中见过的新输入。

测试集通常具有与训练集相同的格式。然而,非常重要的是,测试集与训练语料库是不同的:如果我们简单地 重复使用训练集作为测试集,那么一个简单地记住它的输入,而不学习如何推广到新的例子的模型将会得到误导性的高分。

一般来说,例如,我们70%的数据可以用作训练集案例。还记得将原始集随机划分为训练集和测试集。

现在我来谈谈你的另一个关于朴素贝叶斯的问题。

为了演示Naïve贝叶斯分类的概念,考虑下面给出的例子:

如上所示,对象可以分为绿色或红色。我们的任务是在新案例到来时对它们进行分类,即根据当前存在的对象决定它们属于哪个类标签。

由于GREEN对象的数量是RED对象的两倍,因此有理由相信一个新的情况(还没有被观察到)拥有GREEN成员而不是RED成员的可能性是两倍。在贝叶斯分析中,这种信念被称为先验概率。先验概率是基于之前的经验,在这种情况下是绿色和红色物体的百分比,通常用于在实际发生之前预测结果。

因此,我们可以这样写:

绿色物体的先验概率:绿色物体数量/物体总数

红色的先验概率:红色物体数量/物体总数

因为总共有60个对象,其中40个是绿色的,20个是红色的,所以我们的类成员的先验概率是:

绿色的先验概率:40 / 60

红色的先验概率:20 / 60

Having formulated our prior probability, we are now ready to classify a new object (WHITE circle in the diagram below). Since the objects are well clustered, it is reasonable to assume that the more GREEN (or RED) objects in the vicinity of X, the more likely that the new cases belong to that particular color. To measure this likelihood, we draw a circle around X which encompasses a number (to be chosen a priori) of points irrespective of their class labels. Then we calculate the number of points in the circle belonging to each class label. From this we calculate the likelihood:

从上图中可以清楚地看出,给定绿色的X的可能性小于给定红色的X的可能性,因为圆圈包含1个绿色物体和3个红色物体。因此:

Although the prior probabilities indicate that X may belong to GREEN (given that there are twice as many GREEN compared to RED) the likelihood indicates otherwise; that the class membership of X is RED (given that there are more RED objects in the vicinity of X than GREEN). In the Bayesian analysis, the final classification is produced by combining both sources of information, i.e., the prior and the likelihood, to form a posterior probability using the so-called Bayes' rule (named after Rev. Thomas Bayes 1702-1761).

最后,我们将X分类为RED,因为它的类成员达到了最大的后验概率。