机器学习的情感分析
这里从一个完整的项目流程介绍,包括数据来源、数据标记、数据处理、特征工程、模型构建、模型评估、模型部署这七方便:
一、数据来源:
爬取了新浪财经的新闻数据,大约30万篇文章(很遗憾全是未标记数据)
二、数据标记:
数据量太大,人工标注不太现实,所以调用了百度的情感分析接口,来做标注数据:(需要在百度平台注册申请)
# -*- coding: utf-8 -*-
from aip import AipNlp
import json
import time
import re
""" 你的 APPID AK SK """ #需要在百度平台申请自己的账号
APP_ID = 'you_APP_ID'
API_KEY = 'you_API_KEY'
SECRET_KEY = 'you_SECRET_KEY'
client = AipNlp(APP_ID, API_KEY, SECRET_KEY)
path = '../data/articles.txt' #需要处理的文件的路径,我这是json格式
file = json.load(open(path,'r',encoding='utf-8'))
def data_clear(text): #文本出预处理,因为是网上爬的数据,有许多标签
remove_list = ['&', '<p>', '</p>', '\\n', '\\t', '\\u3000', '<div>', '</div>', "['", "']", '<p/>', '\\xa0',
'\\:', '<strong>', '</storng>', '<span>', '</span>', '>', ' ']
dr = re.compile(r'<[^>]+>', re.S)
for rm in remove_list:
text = text.replace(rm, '')
text = dr.sub('', text)
return text
count = 0
with open('./baidu_output_title.txt','a',encoding='utf-8') as f: #调用api,打好标签,写入到指定位置
for line in file:
title = data_clear(line['title']) #这里只对title进行分析,因为content需要另外分析,涉及到层次情感分析
content = data_clear(line['content'])
if title:
try:
result = client.sentimentClassify(title)
time.sleep(0.3)
if 'error_code' not in str(result):
count = count + 1
string = str(result) + '\n'
f.write(string)
f.flush()
print(count)
except:
pass
三、数据处理:
1、由于百度标记后,0代表消极、1代表中性、2代表积极,所以做了转换;
2、(重点)选取confidence置信度大于0.8的数据,作为样本数据
import json
import jieba
jieba.load_userdict('./negative_dict.txt')
jieba.load_userdict('./positive_dict.txt')
input_file = open('./baidu_output_title.txt','r',encoding='utf-8')
mapping = {0: 'neg', 1: 'neu', 2: 'pos'}
temp_data = []
with open('./new_input.txt','a',encoding='utf-8') as f:
for item in input_file:
try:
line = eval(item)
excep