4

我对机器学习算法和 Spark 非常陌生。我正在关注此处找到的 Twitter 流语言分类器:

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

除了每条推文都打印在每个集群下方之外,还会发生同样的事情。

这是我直觉认为正在发生的事情(如果错误,请纠正我的想法):这段代码将每条推文变成一个向量,随机挑选一些集群,然后运行 ​​kmeans 对推文进行分组(在非常高的级别上,集群,我假设,将是常见的“主题”)。因此,当它检查每条推文以查看 models.predict == 1 时,不同的推文集应该出现在每个集群下(并且因为它会根据自身检查训练集,所以每条推文都应该在一个集群中)。为什么不这样做?要么我对 kmeans 所做的理解有误,要么我的训练集太小,要么我错过了一步。

任何帮助是极大的赞赏

4

1 回答 1

3

嗯,首先 KMeans 是一种聚类算法,因此是无监督的。因此,没有“针对自身检查训练集”(好吧,您可以手动进行;)。

实际上,您的理解非常好,只是您错过了 model.predict(Utils.featurize(t)) 为您提供了由 KMeans 分配的 t 所属的集群。我想你想检查

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

在您的代码中,因为我遍历所有集群标签。

还有一点要注意:特征向量是在推文字符的 2-gram 模型上创建的。这个中间步骤很重要;)

2-gram (for words) 的意思是:“A bears calls at a bear” => {(A, bear), (bear,outshoos), (shouts, at), (at, a), (a bear)} 即“一只熊”被计算了两次。字符将是 (A,[space]), ([space], b), (b, e) 等等。

于 2015-03-08T18:42:08.623 回答