【问题标题】:Latent Dirichlet allocation (LDA) in Spark - replicate modelSpark 中的潜在狄利克雷分配 (LDA) - 复制模型
【发布时间】:2019-06-28 04:21:11
【问题描述】:

我想从 pyspark ml-clustering 包中保存 LDA 模型,并在保存后将该模型应用于训练和测试数据集。然而,尽管设置了种子,结果却出现了分歧。我的代码如下:

1) 导入包

from pyspark.ml.clustering import LocalLDAModel, DistributedLDAModel
from pyspark.ml.feature import CountVectorizer , IDF

2) 准备数据集

countVectors = CountVectorizer(inputCol="requester_instruction_words_filtered_complete", outputCol="raw_features", vocabSize=5000, minDF=10.0)
cv_model = countVectors.fit(tokenized_stopwords_sample_df)
result_tf = cv_model.transform(tokenized_stopwords_sample_df)
vocabArray = cv_model.vocabulary
idf = IDF(inputCol="raw_features", outputCol="features")
idfModel = idf.fit(result_tf)
result_tfidf = idfModel.transform(result_tf)
result_tfidf = result_tfidf.withColumn("id", monotonically_increasing_id())    
corpus = result_tfidf.select("id", "features")

3) 训练 LDA 模型

lda = LDA(k=number_of_topics, maxIter=100, docConcentration = [alpha], topicConcentration = beta, seed = 123)
model = lda.fit(corpus)
model.save("LDA_model_saved")
topics = model.describeTopics(words_in_topic)  
topics_rdd = topics.rdd
modelled_corpus = model.transform(corpus)

4) 复制模型

#Prepare the data set
countVectors = CountVectorizer(inputCol="requester_instruction_words_filtered_complete", outputCol="raw_features", vocabSize=5000, minDF=10.0)
cv_model = countVectors.fit(tokenized_stopwords_sample_df)
result_tf = cv_model.transform(tokenized_stopwords_sample_df)
vocabArray = cv_model.vocabulary
idf = IDF(inputCol="raw_features", outputCol="features")
idfModel = idf.fit(result_tf)
result_tfidf = idfModel.transform(result_tf)   
result_tfidf = result_tfidf.withColumn("id", monotonically_increasing_id())
corpus_new = result_tfidf.select("id", "features")

#Load the model to apply to new corpus
newModel = LocalLDAModel.load("LDA_model_saved")
topics_new = newModel.describeTopics(words_in_topic)  
topics_rdd_new = topics_new.rdd
modelled_corpus_new = newModel.transform(corpus_new)

尽管我的假设是相等的,但以下结果是不同的: topics_rdd != topics_rdd_newmodelled_corpus != modelled_corpus_new(在检查提取的主题时,它们以及数据集上的预测类别也不同)

所以我觉得很奇怪,即使我在模型生成中设置了种子,同一个模型在同一个数据集上预测不同的类别(“主题”)。有复制 LDA 模型经验的人可以帮忙吗?

谢谢你:)

【问题讨论】:

    标签: apache-spark pyspark lda


    【解决方案1】:

    我在 PYSPARK 中实现 LDA 时遇到了类似的问题。即使我使用的是种子,但每次我在具有相同参数的相同数据上重新运行代码时,结果都是不同的。

    在尝试了很多事情之后,我想出了以下解决方案:

    1. 在运行一次后保存 cv_model 并在下一次迭代中加载它,而不是重新拟合它。

    2. 这和我的数据集比较相关。我使用的语料库中的一些文档的大小非常小(每个文档大约 3 个单词)。我过滤掉了这些文档并设置了一个限制,这样只有那些文档将被包含在至少 15 个单词的语料库中(您的单词可能更高)。我不确定为什么这个有效,可能与模型的复杂性有关。

    总而言之,即使经过多次迭代,我的结果仍然相同。希望这可以帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-08
      • 1970-01-01
      • 1970-01-01
      • 2014-09-24
      • 2022-07-04
      • 2016-10-20
      • 2020-07-21
      • 2019-08-04
      相关资源
      最近更新 更多