如何识别文本中的主要主题
2024年4月11日(更新于2024年5月8日)
使用大语言模型(LLMs)识别文本数据中的主题要容易得多。与人工识别或潜在狄利克雷分配(LDA)等较早的技术相比,这些模型是一项实质性的进步。本指南阐述了使用大语言模型有效识别主题的三种稳健策略,即使对于简短文本也同样适用。
在深入介绍这些方法之前,建议先阅读一篇预印本论文(http://doi.org/10.2196/preprints.53376),该文对这些策略及其各自的优势进行了全面考察。您也可以使用 GitHub 上的数据集进行练习(https://github.com/lanceyuu/LLMforTM.git)。必须认识到某些局限性,例如大语言模型可分析的文本长度存在限制。
1. 使用大语言模型工具
分析文本时,您可以使用工具包中任何可用的大语言模型工具。请访问我们的工具包(Toolkit)。对于篇幅较长的文本,建议使用 GPT-4 或我开发的 GPT(Topic Modeller)。Le Chat 和 Claude 等其他模型也已展现出处理较长文本的能力,而 Llama 可能存在局限。对于中文文本,推荐使用 Kimi。此外,Gemini Pro 1.5 能够处理多达一百万个词元(token)。
提示示例(保留英文原文):
You are a qualitative researcher and your task is to identify the topics in the text. When generating the topics, prioritize correctness and ensure that your response is accurate and grounded in the context of the text.
Your summary should include three components: the first one is the title of the topic; the second one is the definition of the topic; the third one is the number of occurrences of the topic.
insert topic 1: Title, definition, occurrence
insert topic 2: Title, definition, occurrence
insert topic 3: Title, definition, occurrence
…
Here is the text
[paste your text here]
2. 用于分析结构化数据的 Python 脚本
如果您拥有结构化数据(例如 CSV 文件),或需要分析大量文本,与手动输入相比,Python 脚本可以提供更系统的方法。脚本如下。请将 API key 替换为您自己的密钥,并通过路径导入数据集。
!pip install openai==0.28
!pip install evaluate
!pip install rouge_score
!pip install panda
import openai
import evaluate
import pandas as pd
# Initialize OpenAI API with your key
openai_api_key = "your_openai_api_key"
openai.api_key = openai_api_key
# Load your test data
test_data_path = 'path/to/your/test.csv'
test_data = pd.read_csv(test_data_path)
# Define the summarization instruction within a chat interaction context
def generate_summary(review):
response = openai.ChatCompletion.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are an AI trained to summarize product reviews."},
{"role": "user", "content": review}
]
)
return response.choices[0].message['content']
# Generate summaries
results = []
actual_summaries = test_data['summary'].tolist() # Adjust the column name if needed
for review in test_data['reviews']: # Adjust the column name if needed
summary = generate_summary(review)
results.append(summary)
# Evaluate the summaries using ROUGE
rouge_scorer = evaluate.load('rouge')
rouge_scores = rouge_scorer.compute(predictions=results, references=actual_summaries)
# Directly print the ROUGE-1 score, assuming it's a numerical value
print("ROUGE-1 F1 Score:", rouge_scores['rouge1'])
对于具备较高专业水平的用户,还可以用 Yi 或 Qwen 等其他模型替代 GPT-4。开源大语言模型请参见此链接:https://huggingface.co/spaces/lmsys/chatbot-arena-leaderboard
建议使用 Google Colab 运行脚本。为确定提示的有效性,您可以计算 ROUGE-1 分数,并根据需要修改提示。后续教程将介绍如何评估主题建模的结果。
完成主题识别后,可以使用一个辅助脚本将每个文本片段与相关主题对应起来。
import csv
import requests
import openai
# Initialize the OpenAI API client
openai.api_key = 'please paste your API here'
# Open the tweet.csv file, you should upload it to colab or open it in your local enviroment.
with open("tweet.csv", "r") as csvfile:
reader = csv.DictReader(csvfile)
# Create a new file called: tweet_results.csv to store the results
with open("tweet_results.csv", "w") as csv_file: # you can change the name to newname.csv
writer = csv.DictWriter(csv_file, fieldnames=["tweet", "answer"]) # replace tweet and answer with the new variable name A and B you like.
writer.writeheader()
# Iterate over each tweet
for row in reader:
# Get the tweet text
tweet_text = row["tweet"] # here please replace tweet with the variable name of the text in your csv file.
# Ask ChatGPT 4.0 if the tweet contains related content
prompt = f"you are now a researcher and you will tell me if the following reply belongs to which topic. In total there are xxx number of topics: Topic 1 xxx; Topic 2 xxx \"{tweet_text}\""
response= openai.ChatCompletion.create(model="gpt-4",messages=[{"role": "user", "content": prompt}])
# Get the response from ChatGPT
#response_text = response["choices"][0]["text"]
response_text = response["choices"][0]["message"]["content"]
answer = response_text # replace answer with your new variable name B
# Write the results to the file
writer.writerow({"tweet": tweet_text, "answer": answer}) # replace tweet with your new variable name A, and answer with you new variable name B
关于这一方法的在线工作坊将于2024年9月推出。欢迎订阅以获取最新信息。
3. IBM Watsonx AI
我最近参加了一次 IBM 黑客马拉松,发现 Watsonx AI 在这一场景中非常实用。该工具便于进行提示微调和模型测试。详细内容将在即将发布的教程中介绍。
这些方法旨在提升您的文本分析工作。相信它们会对您的研究有所帮助。
标签: 文本分析





留言