在 NLP 任务中,情感分析和实体分析是两个重要的文本标注场景。高质量的文本数据标注对于情感分类、命名实体识别(NER)、关系抽取等任务至关重要。
本指南将详细介绍:
- 情感分析标注(Sentiment Analysis)
- 实体分析标注(Named Entity Recognition, NER)
- 手动标注工具
- 自动化标注
- 数据存储与管理
- 主动学习优化标注
- Python 代码示例
1. 情感分析(Sentiment Analysis)标注
1.1 情感分析简介
文本情感分析(Sentiment Analysis)是 NLP 任务之一,主要用于识别文本的情绪倾向,例如:
- 二分类:正面(positive)、负面(negative)
- 三分类:正面(positive)、中性(neutral)、负面(negative)
- 多级分类:1-5 星评分
- 细粒度情感分析:愤怒、喜悦、悲伤、惊讶等
数据标注任务主要包括:
- 文本预处理
- 手动或自动标注
- 数据存储
- 质量评估
1.2 手动标注工具
Label Studio
Label Studio 是一个开源的数据标注工具,支持文本分类、情感分析、NER等任务。
安装 Label Studio
pip install label-studio
label-studio start
- 选择 "Text Classification" 任务
- 上传文本数据
- 进行人工标注
- 导出 JSON/CSV 格式
1.3 自动标注(TextBlob + Transformers)
如果已经有预训练情感分析模型,可以自动标注数据。
安装 TextBlob
pip install textblob
使用 TextBlob 进行情感分析
from textblob import TextBlob
text = "I love this product, it's amazing!"
sentiment = TextBlob(text).sentiment.polarity # 范围:-1(负面)到 1(正面)
label = "positive" if sentiment > 0 else "negative" if sentiment < 0 else "neutral"
print("情感标注:", label)
输出:
情感标注: positive
1.4 使用 Hugging Face Transformers 进行情感分析
pip install transformers torch
from transformers import pipeline
classifier = pipeline("sentiment-analysis")
text = "I really enjoy this movie, it's fantastic!"
result = classifier(text)
print(result)
输出示例:
[{"label": "POSITIVE", "score": 0.99}]
1.5 生成 JSON 标注数据
import json
annotations = [
{"text": "I love this product!", "label": "positive"},
{"text": "This is terrible!", "label": "negative"}
]
with open("sentiment_annotations.json", "w") as f:
json.dump(annotations, f, indent=4)
print("情感标注数据已保存")
输出格式(JSON):
[
{"text": "I love this product!", "label": "positive"},
{"text": "This is terrible!", "label": "negative"}
]
2. 实体分析(Named Entity Recognition, NER)标注
2.1 实体分析简介
命名实体识别(NER)用于提取文本中的特定实体,例如:
- 人名(PERSON):Elon Musk
- 地点(LOCATION):New York
- 组织(ORGANIZATION):Google
- 日期(DATE):2024-02-22
- 产品(PRODUCT):iPhone 15
数据标注任务主要包括:
- 文本预处理
- 手动或自动标注
- 数据存储
- 质量评估