簡體   English   中英

嘗試在Spark中使用TF-IDF和KMeans對文檔進行聚類。 這段代碼有什么問題?

[英]Attempting to cluster documents with TF-IDF and KMeans in Spark. What's wrong with this piece of code?

我有一個帶文本字段的CSV文件,使用2種語言(法語和英語)。 我正在嘗試進行聚類分析,並且由於語言的差異,我期望文本被分為兩個聚類。

我提出了以下代碼,這些代碼無法按預期工作:

import org.apache.spark.sql.SQLContext
import org.apache.spark.sql.types.{StructType, StructField, StringType}
import org.apache.spark.ml.feature.{HashingTF, IDF, Tokenizer}
import org.apache.spark.ml.clustering.KMeans

val sqlContext = new SQLContext(sc)

val customSchema = StructType(Array(
    StructField("id_suivi", StringType, true),
    StructField("id_ticket", StringType, true),
    StructField("id_affectation", StringType, true),
    StructField("id_contact", StringType, true),
    StructField("d_date", StringType, true),
    StructField("n_duree_passe", StringType, true),
    StructField("isPublic", StringType, true),
    StructField("Ticket_Request_Id", StringType, true),
    StructField("IsDoneInHNO", StringType, true),
    StructField("commments", StringType, true),
    StructField("reponse", StringType, true)))

val tokenizer = new Tokenizer().setInputCol("reponse").setOutputCol("words")
val hashingTF = new HashingTF().setInputCol("words").setOutputCol("rawFeatures").setNumFeatures(32768)
val idf = new IDF().setInputCol("rawFeatures").setOutputCol("features")

val df = sqlContext.read.format("com.databricks.spark.csv").
    option("header", "true").
    option("delimiter", ";").
    schema(customSchema).
    load("C:/noSave/tmp/22/tickets1.csv").
    select("id_suivi", "reponse")

val tokenizedDF = tokenizer.transform(df)
val hashedDF = hashingTF.transform(tokenizedDF).cache()

val idfModel = idf.fit(hashedDF)

val rescaledDF = idfModel.transform(hashedDF).cache()

val kmeans = new KMeans().setK(2).setSeed(1L).setFeaturesCol("features")
val model = kmeans.fit(rescaledDF)

val clusteredDF = model.transform(rescaledDF)

我認為這段代碼是正確的,或者至少我看不出錯誤在哪里。 但是,確實有問題,因為當我計算誤差時,誤差確實很大:

scala> model.computeCost(rescaledDF)
res0: Double = 3.1555983509935196E7

我還嘗試了不同的K值(我認為2是一個很好的值,因為我的文本使用2種語言(法語,英語)),例如10、100甚至更大,尋找“肘”值,但是沒有運氣。

誰能指出我正確的方向?

提前謝謝了 !

我會回答我自己的問題(希望這對於SO的禮節是可以接受的),以防萬一這一天對別人有用。

區分這兩種語言的一種更簡單的方法是考慮使用停用詞(即:每種語言中常見的詞)。

首先,使用TF-IDF是一個壞主意,因為它會使停用詞的作用無效(其目的是將重點放在文檔中的“非常見”術語上)

通過使用CountVectorizer,我設法更接近按語言進行聚類的目標,它創建了最常用術語的字典並對每個文檔進行計數。

最常用的術語是停用詞,我們最終使用停用詞對文檔進行聚類,停用詞在兩種語言中都是不同的集合,因此按語言聚類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM