使用LLM(Ollama部署)为Bertopic确定的主题命名

使用本地部署的 Ollama + Qwen3:14b 模型,结合 BERTopic 输出的关键词与样本摘要,自动生成 3--4 个词的主题名称。整个流程自动化、可复用,适用于学术论文、新闻聚类、客户反馈分析等多种场景。


实现思路

我们设计了一个简单的 Python 函数 generate_topic_name(),它接收两个参数:

  • topic_keywords:由 BERTopic 生成的当前主题关键词列表;
  • sample_abstracts:属于该主题的若干样本摘要(用于提供上下文)。

函数构造一个清晰的提示词(prompt),调用本地 Ollama 模型进行推理,并对输出结果进行后处理,移除模型可能生成的 <think>...</think> 思考标签(常见于 Qwen 系列模型),最终返回干净的主题名称。


代码详解

python 复制代码
import ollama
import re

def remove_thinking_tags(text):
    """
    移除所有 <think>...<think> 标签及其内部内容(支持跨行)
    """
    pattern = r'<think>.*?</think>'
    cleaned = re.sub(pattern, '', text, flags=re.DOTALL)
    return cleaned.strip()

def generate_topic_name(topic_keywords, sample_abstracts):
    prompt = f""" /no_thinking

You are a helpful assistant for naming topics from research paper abstracts.
Given the following keywords generated using BERTopic and sample abstracts, generate a short and meaningful topic name.

The topic name should be very short, maximum of 3 to 4 words --- not a sentence or description.

Keywords: {', '.join(topic_keywords)}

Abstracts:
{chr(10).join(f"- {abs}" for abs in sample_abstracts)}

Give a concise 3--4 word topic name:"""

    response = ollama.chat(
        model='Qwen3:14b',
        messages=[
            {'role': 'user', 'content': prompt}
        ],
        options={
            'temperature': 0.7,
            'num_predict': 3000  # 类似 max_tokens
        }
    )
    raw_content = response['message']['content'].strip()
    # 清理 thinking 标签内容
    cleaned_content = remove_thinking_tags(raw_content)
    return cleaned_content

renamed_topics = {}

for entry in llm_input:
    name = generate_topic_name(entry["topic_keywords"], entry["sample_abstracts"][:5])
    renamed_topics[entry["topic_num"]] = name
    print(f"Topic {entry['topic_num']}: {name}")
相关推荐
彼岸花开了吗1 小时前
构建AI智能体:八十、SVD知识整理与降维:从数据混沌到语义秩序的智能转换
人工智能·python·llm
拖拉斯旋风2 小时前
从零开始:使用 Ollama 在本地部署开源大模型并集成到 React 应用
前端·javascript·ollama
栀秋6662 小时前
智能驱动的 Git 提交:基于 Ollama 大模型的规范化提交信息生成方案
react.js·llm·ollama
AI架构师易筋4 小时前
AIOps 告警归因中的提示工程:从能用到可上生产(4 阶梯)
开发语言·人工智能·llm·aiops·rag
小小宫城狮5 小时前
BPE 算法原理与训练实现
算法·llm
怎么追摩羯座7 小时前
使用PyCharm调用Ollama,制作智能问答机器人
ide·python·pycharm·大模型·ollama
且去填词7 小时前
DeepSeek :基于 AST 与 AI 的遗留系统“手术刀”式治理方案
人工智能·自动化·llm·ast·agent·策略模式·deepseek
且去填词7 小时前
构建基于 DeepEval 的 LLM 自动化评估流水线
运维·人工智能·python·自动化·llm·deepseek·deepeval
xiaoxue..7 小时前
把大模型装进自己电脑:Ollama 本地部署大模型完全指南
javascript·面试·node.js·大模型·ollama
ohyeah1 天前
打造 AI 驱动的 Git 提交规范助手:基于 React + Express + Ollama+langchain 的全栈实践
langchain·全栈·ollama