【问题标题】:Document classification in spark mllibspark mllib 中的文档分类
【发布时间】:2016-04-22 00:23:47
【问题描述】:

如果文档属于体育、娱乐、政治,我想对它们进行分类。我创建了一个单词包,输出如下内容:

(1, 'saurashtra') (1,'saumyajit') (1, 'satyendra')

我想使用 Spark mllib 实现用于分类的朴素贝叶斯算法。我的问题是如何将此输出转换为可以朴素贝叶斯用作 RDD 等分类的输入的东西,或者如果有任何技巧我可以直接将 html 文件转换为 mllib 朴素贝叶斯可以使用的东西。

【问题讨论】:

    标签: python apache-spark-mllib naivebayes document-classification


    【解决方案1】:

    对于文本分类,您需要:

    • 一本词典
    • 使用字典将文档转换为向量
    • 标记文档向量:

      doc_vec1 -> 标签1

      doc_vec2 -> 标签2

      ...

    这个sample 非常简单。

    【讨论】:

    • 感谢您的回答..但我对第二部分有点困惑:使用字典将文档转换为矢量,就好像我有(音乐、政治、娱乐)和前 50 个单词之类的标签每个文件。我如何映射它们以构建分类器。就 spark 示例而言,他们已经拥有可用作朴素贝叶斯输入的文本文件。
    • a doc vec 只是一个长数组,比如 50 个元素,数组的索引是你的字典中单词的 id,元素的值是 count 对应的单词。建议您normalize count
    【解决方案2】:
        from pyspark.ml.feature import RegexTokenizer, StopWordsRemover, CountVectorizer
        from pyspark.ml.classification import NaiveBayes
    
        # regular expression tokenizer
        regexTokenizer = RegexTokenizer(inputCol="Descript", outputCol="words", 
        pattern="\\W")
        # stop words
        add_stopwords = ["http","https","amp","rt","t","c","the"] 
        stopwordsRemover = 
      StopWordsRemover(inputCol="words",outputCol="filtered").setStopWords(add_stopwords)
        # bag of words count
        countVectors = CountVectorizer(inputCol="filtered", outputCol="features", 
        vocabSize=10000, minDF=5)
        (trainingData, testData) = dataset.randomSplit([0.7, 0.3], seed = 100)
        nb = NaiveBayes(smoothing=1)
        model = nb.fit(trainingData)
        predictions = model.transform(testData)
        predictions.filter(predictions['prediction'] == 0) \
         .select("Descript","Category","probability","label","prediction") \
         .orderBy("probability", ascending=False) \
         .show(n = 10, truncate = 30)
    

    【讨论】:

    • 以下是How do I write a good answer? 的一些指南。提供的这个答案可能是正确的,但它可以从解释中受益。仅代码答案不被视为“好”答案。来自review
    猜你喜欢
    • 2016-09-03
    • 2017-03-24
    • 2017-02-02
    • 2016-12-10
    • 2017-01-28
    • 2015-04-20
    • 2014-10-27
    • 2016-01-05
    相关资源
    最近更新 更多