美文网首页
第五周 - 20180507

第五周 - 20180507

作者: RootHarold | 来源:发表于2018-06-15 03:10 被阅读0次

    朴素贝叶斯的思路及实现

    一、朴素贝叶斯简介

    朴素贝叶斯法(Naive Bayes)是基于贝叶斯定理与特征条件独立假设的分类方法,属于统计学分类方法。简单来说,朴素贝叶斯分类器假设在给定样本类别的条件下,样本的每个特征与其他特征均不相关,对于给定的输入,利用贝叶斯定理,求出后验概率最大的输出。朴素贝叶斯法实现简单,学习与预测的效率均较高,在文本分类领域有广泛的应用。

    二、Naive Bayes在此项目中遇到的问题

    首先是分词的问题。像朴素贝叶斯这种传统机器学习算法在进行情感分类时,更多的还是使用原生文本的分词而不是词向量。这种情况下,一个靠谱的中文分词器尤为重要,该项目最后选择的是结巴分词器

    主流的朴素贝叶斯都是二分型的,该项目的标签数为3,为了解决这个问题,项目组提出了两种方案,一种是以Majority Voting的规则利用多个朴素贝叶斯堆叠实现多分类,另一种则是目前采用的重写Naive Bayes的分类逻辑。

    代码中Naive Bayes模块没有使用现有框架,均为手工搭建,详情请参见代码包。

    三、核心代码

    朴素贝叶斯的训练过程如下:

    def train_bayes(featureFile, textFile, modelFile):

    ''' 训练朴素贝叶斯模型'''

    print("Naive Bayes training...")docCounts, features = load_feature_words(featureFile)wordCount = collections.defaultdict(lambda: doc_dict())

    # 每类文档特征词出现的次数

    tCount = [0] * len(docCounts)

    for line in textFile:

           lable, text = line.strip().split(' ', 1)

           index = lable2id(lable[0])

           words = text.split(' ')

           for word in words:

                if word in features:

                      tCount[index] += 1

                      wordCount[word][index] += 1

    outModel = open(modelFile, 'w')

    print("Export the model...")

    for k, v in wordCount.items():

           # 拉普拉斯平滑

           scores = [(v[i] + 1) * 1.0 / (tCount[i] + len(wordCount)) for i in range(len(v))]                     outModel.write(k + "\t" + scores.__str__() + "\n")outModel.close()

    预测部分的逻辑则为:

    def predict(featureFile, modelFile, testText):

    '''

        预测文档的类别,标准输入为每一行为一个文档

    '''

    docCounts, features = load_feature_words(featureFile)

    docScores = [math.log(count * 1.0 / sum(docCounts)) for count in docCounts]

    scores = load_model(modelFile)

    rCount = 0

    docCount = 0

    print("Testing...")

    for line in testText:

        lable, text = line.strip().split(' ', 1)

        index = lable2id(lable[0])

        words = text.split(' ')

        preValues = list(docScores)

        for word in words:

            if word in features:

                for i in range(len(preValues)):

                    preValues[i] += math.log(scores[word][i])

        m = max(preValues)

        pIndex = preValues.index(m)

        if pIndex == index:

            rCount += 1

        # print lable,lables[pIndex],text

        docCount += 1

    print("总数: %d , 正确预测数: %d, 准确度:%f" % (rCount, docCount, rCount * 1.0 / docCount))

    相关文章

      网友评论

          本文标题:第五周 - 20180507

          本文链接:https://www.haomeiwen.com/subject/lqfpeftx.html