使用LDA挖掘潜在主题,输出每个主题的 TOP10 关键词,分析主题含义(建议设定 2-5 个主题)使用bertopic库。
5条回答 默认 最新
阿里嘎多学长 2025-06-07 18:45关注阿里嘎多学长整理AIGC生成,因移动端显示问题导致当前答案未能完全显示,请使用PC端查看更加详细的解答过程
使用 LDA挖掘潜在主题,输出每个主题的 TOP10 关键词,分析主题含义(建议设定 2-5 个主题)使用bertopic库
使用
bertopic库可以轻松地实现主题模型的挖掘和主题关键词的提取。下面是一个简单的示例代码:import pandas as pd from bertopic import BERTopic # 加载数据 df = pd.read_csv('your_data.csv') # 创建 BERTopic 对象 topic_model = BERTopic(num_topics=3, embedding_model='distilbert-base-nli-mean-tokens') # 对数据进行主题模型挖掘 topics, probs = topic_model.fit_transform(df['column_name']) # 输出每个主题的 TOP10 关键词 for topic, words in zip(topics, topic_model.get_topic_words()): print(f'Topic {topic}: {", ".join(words[:10])}')其中,
num_topics参数指定了主题的数量,embedding_model参数指定了使用的词向量模型。在上面的代码中,我们使用distilbert-base-nli-mean-tokens作为词向量模型。在
fit_transform方法中,我们对数据进行主题模型挖掘,并将结果存储在topics和probs中。topics中存储的是每个文档对应的主题索引,probs中存储的是每个文档对应的主题概率。最后,我们使用
get_topic_words方法来获取每个主题的 TOP10 关键词,并将结果打印出来。代码解释
BERTopic对象的创建:我们创建了一个BERTopic对象,并指定了主题的数量为 3,词向量模型为distilbert-base-nli-mean-tokens。- 主题模型挖掘:我们对数据进行主题模型挖掘,并将结果存储在
topics和probs中。 - TOP10 关键词提取:我们使用
get_topic_words方法来获取每个主题的 TOP10 关键词,并将结果打印出来。
代码示例
import pandas as pd from bertopic import BERTopic # 加载数据 df = pd.read_csv('your_data.csv') # 创建 BERTopic 对象 topic_model = BERTopic(num_topics=3, embedding_model='distilbert-base-nli-mean-tokens') # 对数据进行主题模型挖掘 topics, probs = topic_model.fit_transform(df['column_name']) # 输出每个主题的 TOP10 关键词 for topic, words in zip(topics, topic_model.get_topic_words()): print(f'Topic {topic}: {", ".join(words[:10])}')结果
输出结果将是每个主题的 TOP10 关键词,例如:
Topic 0: apple, banana, orange, fruit, healthy, diet, nutrition, food, eat, health Topic 1: car, truck, bus, vehicle, transportation, road, traffic, drive, ride, travel Topic 2: book, read, novel, story, author, literature, fiction, nonfiction, writing, publish这些关键词可以帮助我们分析主题的含义和特点。
解决 无用评论 打赏 举报