趁着国庆假期,玩了一下深度学习(主要是LSTM这个网络),顺便做了一个中文多分类的情感分析。中文情感分析相对英文来说,难度太大,所以最后分析的结果,准确度也不是太高,但基本还是没啥问题的。
对应的api地址: https://blog.csdn.net/qq_40663357/article/details/103102396
数据
我的数据是来自github的一个项目:ChineseNlpCorpus 里面收集了蛮多用于自然语言处理的中文数据集/语料。
- 下载地址: 百度网盘
- 数据概览: 36 万多条,带情感标注 新浪微博,包含 4 种情感,其中喜悦约 20 万条,愤怒、厌恶、低落各约 5 万条
- 数据来源: 新浪微博
- 原数据集: 微博情感分析数据集,网上搜集,具体作者、来源不详
- 加工处理: 写了个脚本sampling,可以将数据集拆分更小一点,加快实验。
预处理
拆分数据集
由于原数据集比较大,所以为了加快测试调参的速度,这里写了一个对数据集进行拆分的脚本。
n1 = 0
n2 = 0
n3 = 0
n4 = 0
newLines = ""
with open("weibo_train.txt", "r", encoding="gbk",errors='ignore') as f:
lines = f.readlines()
f.close()
for line in lines:
label, sentence = line.strip().split("\t")
if int(label) == 0:
if n1 < 10000:
n1 += 1
newLines += label + "\t" + sentence + "\n"
if int(label) == 1:
if n2 < 10000:
n2 += 1
newLines += label + "\t" + sentence + "\n"
if int(label) == 2:
if n3 < 10000:
n3 += 1
newLines += label + "\t" + sentence + "\n"
if int(label) == 3:
if n4 < 10000:
n4 += 1
newLines += label + "\t" + sentence + "\n"
with open("small_train.txt", "w") as f2:
f2.write(newLines)
f2.close()
数据过滤
数据中的一些标点符号、特殊符号、英文字母、数字等对于我们的实验都是没有用处的,所以我们需要将他们过滤掉。
这里使用正则表达式进行过滤:
# 数据过滤
def regex_filter(s_line):
# 剔除英文、数字,以及空格
special_regex = re.compile(r"[a-zA-Z0-9\s]+")
# 剔除英文标点符号和特殊符号
en_regex = re.compile(r"[.…{|}#$%&\'()*+,!-_./:~^;<=>?@★●,。]+")
# 剔除中文标点符号
zn_rege