Spark MLlib機(jī)器學(xué)習(xí)開發(fā)指南(6)--特征提取--CountVectorizer

Spark MLlib機(jī)器學(xué)習(xí)開發(fā)指南(6)--特征提取,轉(zhuǎn)換,選擇--CountVectorizer

翻譯自CountVectorizer,基于最新2.2.0版本翻譯,轉(zhuǎn)載注明出處 xcrossed 機(jī)器學(xué)習(xí)

CountVectorizer

CountVectorizer和CountVectorizerModel的目標(biāo)是幫助將一個(gè)文檔集合轉(zhuǎn)換成一個(gè)包含token計(jì)數(shù)的向量當(dāng)沒有預(yù)先的字典可用時(shí)。CountVectorizer可用作估計(jì)器來提取詞匯表,生成CountVectorizerModel。該模型為文檔中的文檔生成稀疏的詞匯表示形式,然后將這些文檔傳遞給LDA等其他算法。

在擬合過程中,CountVectorizer將在語料庫中選擇由詞頻排序最高的詞匯。一個(gè)可選的參數(shù)minDF也通過指定一個(gè)詞匯必須出現(xiàn)在詞匯表中的最小值(或小于1.0)來影響擬合過程。另一個(gè)可選的二進(jìn)制切換參數(shù)控制輸出向量。如果設(shè)置為真,所有非零計(jì)數(shù)都設(shè)置為1。這對(duì)于離散的概率模型來說尤其有用,模型是二進(jìn)制的,而不是整數(shù)的。

Examples
假定我們有一個(gè)列名為id和texts的DataFrame

 id | texts
----|----------
 0  | Array("a", "b", "c")
 1  | Array("a", "b", "b", "c", "a")

每行在texts列中表示的是一個(gè)Array[String]類型的文檔,調(diào)用CountVectorizer的fit()方法能產(chǎn)生一個(gè)包含詞匯表(a, b, c)的CountVectorizerModel.轉(zhuǎn)換后包含一個(gè)vector的輸出列

 id | texts                           | vector
----|---------------------------------|---------------
 0  | Array("a", "b", "c")            | (3,[0,1,2],[1.0,1.0,1.0])
 1  | Array("a", "b", "b", "c", "a")  | (3,[0,1,2],[2.0,2.0,1.0])

每個(gè)向量表示該文檔在詞匯表上的出現(xiàn)計(jì)數(shù)。

詳細(xì)API參考CountVectorizer Scala docsCountVectorizerModel Scala docs

import org.apache.spark.ml.feature.{CountVectorizer, CountVectorizerModel}

val df = spark.createDataFrame(Seq(
  (0, Array("a", "b", "c")),
  (1, Array("a", "b", "b", "c", "a"))
)).toDF("id", "words")

// fit a CountVectorizerModel from the corpus
val cvModel: CountVectorizerModel = new CountVectorizer()
  .setInputCol("words")
  .setOutputCol("features")
  .setVocabSize(3)
  .setMinDF(2)
  .fit(df)

// alternatively, define CountVectorizerModel with a-priori vocabulary
val cvm = new CountVectorizerModel(Array("a", "b", "c"))
  .setInputCol("words")
  .setOutputCol("features")

cvModel.transform(df).show(false)

完整示例代碼在spark代碼倉庫"examples/src/main/scala/org/apache/spark/examples/ml/CountVectorizerExample.scala"

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容