基于Pandas的评论文本粗细分类:寻求开源Python工具解决方案
可行的开源Python方案推荐
针对你需要给无预定义字典的评论自动分配大类(Broad_cat)和细类(Fine_cat)的需求,以下是几个实用的开源方案:
1. 基于Hugging Face Transformers的零样本分类
零样本分类无需预训练特定领域数据集,能直接对未见过的类别进行匹配,非常适配你这种无预定义字典的场景。你可以先定义一套通用的大类候选(比如Stationary、Electrical、Clothing等),让模型自动匹配文本对应的大类;细类则可结合关键词提取或实体识别从文本中提取核心内容。
示例代码:
import pandas as pd from transformers import pipeline # 初始化零样本分类管道 classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli") # 定义大类候选 broad_categories = ["Stationary", "Electrical", "Clothing", "Food", "Home Appliance"] # 目标DataFrame df = pd.DataFrame({ "Text": [ "I like this pen", "this is the worst light bulb ever", "these pants fit me just fine" ] }) # 分配大类 def assign_broad_cat(text): result = classifier(text, candidate_labels=broad_categories) return result["labels"][0] df["Broad_cat"] = df["Text"].apply(assign_broad_cat) # 提取细类(基于spaCy实体识别) def extract_fine_cat(text): import spacy nlp = spacy.load("en_core_web_sm") doc = nlp(text) # 提取核心名词短语作为细类 nouns = [chunk.text.strip() for chunk in doc.noun_chunks if chunk.root.pos_ == "NOUN"] return nouns[-1] if nouns else "Unknown" df["Fine_cat"] = df["Text"].apply(extract_fine_cat) print(df)
2. 结合Sentence-BERT的语义匹配分类
先构建一个包含大类、细类及对应样本文本的小型参考集(几十条即可),用Sentence-BERT将评论文本和参考类别文本转换成向量,通过余弦相似度找到最匹配的大类和细类。这种方法灵活性高,能快速适配不同领域的评论。
示例代码:
import pandas as pd from sentence_transformers import SentenceTransformer, util # 加载预训练语义模型 model = SentenceTransformer('all-MiniLM-L6-v2') # 构建参考类别集(可按需补充) reference_data = { "Broad_cat": ["Stationary", "Electrical", "Clothing"], "Fine_cat": ["Pen", "Light Bulb", "Pants"], "Sample_Text": ["This is a pen", "I bought a light bulb", "These are my pants"] } ref_df = pd.DataFrame(reference_data) # 生成参考文本向量 ref_vectors = model.encode(ref_df["Sample_Text"].tolist(), convert_to_tensor=True) # 目标DataFrame df = pd.DataFrame({ "Text": [ "I like this pen", "this is the worst light bulb ever", "these pants fit me just fine" ] }) # 匹配对应类别 def match_category(text): text_vector = model.encode(text, convert_to_tensor=True) # 计算余弦相似度 cos_scores = util.cos_sim(text_vector, ref_vectors)[0] # 获取最相似的类别索引 top_idx = cos_scores.argmax().item() return ref_df["Broad_cat"][top_idx], ref_df["Fine_cat"][top_idx] # 分配大类和细类 df[["Broad_cat", "Fine_cat"]] = df["Text"].apply(lambda x: pd.Series(match_category(x))) print(df)
3. spaCy自定义分类管道
基于spaCy的预训练模型,可添加自定义文本分类组件。若有少量标注样本,可微调模型提升准确率;若无标注样本,可结合规则+语义识别的方式,先提取文本中的实体,再映射到对应类别。
额外提示
- 若评论数量较多,建议先做文本预处理(去除停用词、标点),能有效提升分类准确率。
- 零样本分类的效果依赖于大类候选的覆盖度,可根据实际评论场景逐步补充候选类别。
内容的提问来源于stack exchange,提问作者user18334254
相关产品推荐
相关产品推荐

