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)是幫助將一個文檔集合轉(zhuǎn)換成一個包含token計數(shù)的向量當(dāng)沒有預(yù)先的字典可用時分井。CountVectorizer可用作估計器來提取詞匯表,生成CountVectorizerModel荒椭。該模型為文檔中的文檔生成稀疏的詞匯表示形式声旺,然后將這些文檔傳遞給LDA等其他算法笔链。
在擬合過程中,CountVectorizer將在語料庫中選擇由詞頻排序最高的詞匯艾少。一個可選的參數(shù)minDF也通過指定一個詞匯必須出現(xiàn)在詞匯表中的最小值(或小于1.0)來影響擬合過程卡乾。另一個可選的二進(jìn)制切換參數(shù)控制輸出向量。如果設(shè)置為真缚够,所有非零計數(shù)都設(shè)置為1幔妨。這對于離散的概率模型來說尤其有用,模型是二進(jìn)制的谍椅,而不是整數(shù)的误堡。
Examples
假定我們有一個列名為id和texts的DataFrame
id | texts
----|----------
0 | Array("a", "b", "c")
1 | Array("a", "b", "b", "c", "a")
每行在texts列中表示的是一個Array[String]類型的文檔,調(diào)用CountVectorizer的fit()方法能產(chǎn)生一個包含詞匯表(a, b, c)的CountVectorizerModel.轉(zhuǎn)換后包含一個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])
每個向量表示該文檔在詞匯表上的出現(xiàn)計數(shù)雏吭。
詳細(xì)API參考CountVectorizer Scala docs和CountVectorizerModel 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"