4

我對機器學習算法和Spark非常陌生。我跟着 Twitter的數據流語言分類在這裏找到:Spark MLlib/K-Means直覺

http://databricks.gitbooks.io/databricks-spark-reference-applications/content/twitter_classifier/README.html

具體驗證碼:

http://databricks.gitbooks.io/databricks-spark-reference-applications/content/twitter_classifier/scala/src/main/scala/com/databricks/apps/twitter_classifier/ExamineAndTrain.scala

除了我試圖在批處理模式下的一些鳴叫它運行拉出了Cassandra的 ,在這種情況下總共有200條推文。

如示例所示,我使用此對象爲「向量化」一組鳴叫:

object Utils{ 
    val numFeatures = 1000 
    val tf = new HashingTF(numFeatures) 

    /** 
    * Create feature vectors by turning each tweet into bigrams of 
    * characters (an n-gram model) and then hashing those to a 
    * length-1000 feature vector that we can pass to MLlib. 
    * This is a common way to decrease the number of features in a 
    * model while still getting excellent accuracy (otherwise every 
    * pair of Unicode characters would potentially be a feature). 
    */ 
    def featurize(s: String): Vector = { 
    tf.transform(s.sliding(2).toSeq) 
    } 
} 

這是我的代碼是從ExaminAndTrain.scala修改:

val noSets = rawTweets.map(set => set.mkString("\n")) 

val vectors = noSets.map(Utils.featurize).cache() 
vectors.count() 

val numClusters = 5 
val numIterations = 30 

val model = KMeans.train(vectors, numClusters, numIterations) 

    for (i <- 0 until numClusters) { 
    println(s"\nCLUSTER $i") 
    noSets.foreach { 
     t => if (model.predict(Utils.featurize(t)) == 1) { 
      println(t) 
     } 
     } 
    } 

這代碼運行,每個羣集打印「羣集0」,「羣集1」等 ,沒有任何打印在下面。如果我翻轉

models.predict(Utils.featurize(t)) == 1 

models.predict(Utils.featurize(t)) == 0 

同樣的事情發生,除了每鳴叫打印每簇之下。

這是我直覺地認爲正在發生的事情(請糾正我 想,如果它的錯誤):此代碼打開各推入載體, 隨機選取若干個簇,然後運行K均值到組的tweet(在 真的高水平,我認爲,集羣將是共同的 「主題」)。因此,當它檢查每條推文以查看models.predict == 1時,在每個羣集下面應該出現不同的推文集(並且 是因爲它針對自己檢查訓練集,每個推文 應該位於羣集中)。爲什麼不這樣做?我的 瞭解什麼kmeans做錯了,我的訓練集太 小或我錯過了一步。

任何幫助是極大的讚賞

回答

3

嗯,首先KMEANS的是一個聚類算法,因此不受監督。所以沒有「檢查自己的訓練集」(好吧,你可以手動完成)。

您的理解實際上相當不錯,只是您錯過了model.predict(Utils.featurize(t))爲您提供由KMeans分配的屬於該集羣的點。我想你想檢查

models.predict(Utils.featurize(t)) == i

在你的代碼,因爲我經歷了所有類羣標籤迭代。

此外還有一個小小的評論:特徵向量創建在一個2克模型的個字符的推文。這個中間步驟很重要;)

2-gram(for words)意思是:「熊對熊的叫喊」=> {(A,熊),(熊,叫喊),(叫喊,at),( at,a),(bear)}即「一隻熊」被計數兩次。字符將是(A,[空間]),([空間],b),(b,e)等等。

+1

它是'bigrams of characters',所以它應該是'{(「A」,「b」,「be」...}' – 2015-03-09 14:01:56

+0

你是對的,滑動被一個Seq調用[Char]。 – uberwach 2015-03-09 14:59:54

+0

感謝你的這個反應uberwatch。我做了這個改變,它打印了5個集羣,除了集羣0擁有所有的tweets,而其餘的集羣沒有,我假設意味着所有的tweets被分配到集羣0.這是因爲數據集太小了?(我認爲在databricks提供的例子中,他們訓練kmeans模型的時候有1200萬條推文,而我只用了200條)或者應該調整numClusters/numIterations? – plambre 2015-03-09 16:08:24