spark-lda报错

学习使用spark的LDA进行文章主题词聚类,最终没有成功,先占个坑,记录错误。。

一、整体流程

  1.  原始数据读取及准备:切词、去停用词;
  2.  语料库准备:词典建立、词频文档矩阵建立;
  3.  LDA 模型训练

二、实际操作

前期数据是按照某种规则切好的词,每行代表一个文档,其内容为以'\t'分割的word,所以直接读取:
f_cut = 'hadoop_path_to_file'
data = sc.textFile(f_cut)
data_sp = data.map(lambda line: line.strip().split())
由于在切词过程中,已经去掉了停用词和不相关词性的词,所以不再通过 TF-IDF建立特征矩阵,使用 TF 建立。使用的是 spark 的Countervectorsizer。
from pyspark.ml.feature import CountVectorizer
corpus = data_sp.zipWithIndex().map(lambda x: [x[1], x[0]]).cache()
df_corpus = corpus.toDF()

df_corpus = df_corpus.select(col("_1").alias("idx"), col("_2").alias("words"))
cv = CountVectorizer(inputCol="words", outputCol="features", minDF=1.0)

tf_model = cv.fit(df_corpus)
result = tf_model.transform(df_corpus)
学到的 result 示例如下:

这里再多说一点,前期尝试过使用 sklearn 的Countervectorsizer构建词文档矩阵,由于其结果是一个系数矩阵,在转换至 rdd 过程中出错(未解决)。
建立语料库,注意输入到LDA模型的数据一定要是一个 rdd, 并且第一个数表示 特征的索引。

corpus = result.select(col("idx").cast("long"), "features").rdd.map(lambda x: [x[0], x[1]])
# corpus.first()
# [0, SparseVector(5, {3: 1.0})]


训练 LDA 模型
from pyspark.mllib.clustering import LDA

lda_model = LDA.train(rdd=corpus, k=10, seed=12, maxIterations=50)

走到这里就开始报错了

嗯,找了好久都没有解决。。。





发布了120 篇原创文章 · 获赞 35 · 访问量 17万+

猜你喜欢

转载自blog.csdn.net/u012328476/article/details/78993576