呀呼907 2025-06-07 18:45 采纳率: 0%
浏览 44

使用LDA挖掘潜在主题,输出每个主题的 TOP10 关键词,分析主题含义(建议设定 2-5 个主题)使用bertopic库

使用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 方法中,我们对数据进行主题模型挖掘,并将结果存储在 topicsprobs 中。topics 中存储的是每个文档对应的主题索引,probs 中存储的是每个文档对应的主题概率。

    最后,我们使用 get_topic_words 方法来获取每个主题的 TOP10 关键词,并将结果打印出来。

    代码解释

    1. BERTopic 对象的创建:我们创建了一个 BERTopic 对象,并指定了主题的数量为 3,词向量模型为 distilbert-base-nli-mean-tokens
    2. 主题模型挖掘:我们对数据进行主题模型挖掘,并将结果存储在 topicsprobs 中。
    3. 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
    

    这些关键词可以帮助我们分析主题的含义和特点。

    评论

报告相同问题?

问题事件

  • 创建了问题 6月7日