语言: tr
标签:
- bert
- turkish
- 文本分类
- 攻击性语言检测
许可证: mit
数据集:
- offenseval2020_tr
评估指标:
- 准确率
- f1值
- 精确率
- 召回率
土耳其语攻击性语言检测模型
模型描述
该模型基于dbmdz/bert-base-turkish-128k-uncased模型,使用OffensEval 2020数据集进行微调。
offenseval-tr数据集包含31,756条标注推文。
数据集分布
|
非攻击性(0) |
攻击性 (1) |
训练集 |
25625 |
6131 |
测试集 |
2812 |
716 |
预处理步骤
处理步骤 |
描述 |
重音字符转换 |
将带重音字符转换为其无重音等效形式 |
小写转换 |
将所有文本转换为小写 |
移除@用户提及 |
从文本中删除@user格式的用户提及 |
移除标签表达式 |
从文本中删除#hashtag格式的标签 |
移除URL |
从文本中删除网址链接 |
移除标点符号和标点表情 |
从文本中删除标点符号及标点构成的表情符号 |
移除表情符号 |
从文本中删除表情符号 |
土耳其字符还原 |
将ASCII文本转换为包含土耳其字符的文本 |
分析每种预处理步骤的效果后发现:
移除数字和保留标签对结果无显著影响。
使用方法
安装必要库:
pip install git+https://github.com/emres/turkish-deasciifier.git
pip install keras_preprocessing
预处理函数如下:
from turkish.deasciifier import Deasciifier
def deasciifier(text):
deasciifier = Deasciifier(text)
return deasciifier.convert_to_turkish()
def remove_circumflex(text):
circumflex_map = {
'â': 'a',
'î': 'i',
'û': 'u',
'ô': 'o',
'Â': 'A',
'Î': 'I',
'Û': 'U',
'Ô': 'O'
}
return ''.join(circumflex_map.get(c, c) for c in text)
def turkish_lower(text):
turkish_map = {
'I': 'ı',
'İ': 'i',
'Ç': 'ç',
'Ş': 'ş',
'Ğ': 'ğ',
'Ü': 'ü',
'Ö': 'ö'
}
return ''.join(turkish_map.get(c, c).lower() for c in text)
使用以下函数清洗文本:
import re
def clean_text(text):
text = remove_circumflex(text)
text = turkish_lower(text)
text = deasciifier(text)
text = re.sub(r"@\S*", " ", text)
text = re.sub(r'#\S+', ' ', text)
text = re.sub(r"http\S+|www\S+|https\S+", ' ', text, flags=re.MULTILINE)
text = re.sub(r'[^\w\s]|(:\)|:\(|:D|:P|:o|:O|;\))', ' ', text)
emoji_pattern = re.compile("["
u"\U0001F600-\U0001F64F"
u"\U0001F300-\U0001F5FF"
u"\U0001F680-\U0001F6FF"
u"\U0001F1E0-\U0001F1FF"
u"\U00002702-\U000027B0"
u"\U000024C2-\U0001F251"
"]+", flags=re.UNICODE)
text = emoji_pattern.sub(r' ', text)
text = re.sub(r'\s+', ' ', text).strip()
return text
模型初始化
from transformers import AutoTokenizer, AutoModelForSequenceClassification
tokenizer = AutoTokenizer.from_pretrained("TURKCELL/bert-offensive-lang-detection-tr")
model = AutoModelForSequenceClassification.from_pretrained("TURKCELL/bert-offensive-lang-detection-tr")
检测语句是否具有攻击性:
import numpy as np
def is_offensive(sentence):
d = {
0: '非攻击性',
1: '攻击性'
}
normalize_text = clean_text(sentence)
test_sample = tokenizer([normalize_text], padding=True, truncation=True, max_length=256, return_tensors='pt')
test_sample = {k: v.to(device) for k, v in test_sample.items()}
output = model(**test_sample)
y_pred = np.argmax(output.logits.detach().cpu().numpy(), axis=1)
print(normalize_text, "-->", d[y_pred[0]])
return y_pred[0]
示例调用:
is_offensive("@USER 愿他的归宿是天堂,致敬我们尊敬的律师,祝您有美好的一天")
is_offensive("终有一天我们会战斗到你们一个不剩!!我们要灭绝你们这些畜生!! #婴儿杀手库尔德工人党")
评估结果
测试集评估结果如下表所示,模型在测试集上达到89%的准确率。
模型性能指标
类别 |
精确率 |
召回率 |
F1值 |
准确率 |
类别0 |
0.92 |
0.94 |
0.93 |
0.89 |
类别1 |
0.73 |
0.67 |
0.70 |
|
宏观平均 |
0.83 |
0.80 |
0.81 |
|