我对机器学习算法和 Spark 非常陌生。我正在关注此处找到的 Twitter 流语言分类器:
特别是这段代码:
除了我试图在它从 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 所做的理解有误,要么我的训练集太小,要么我错过了一步。
任何帮助是极大的赞赏