中文情感分析 glove+LSTM
最近尝试了一下中文的情感分析。
主要使用了Glove和LSTM。语料数据集采用的是中文酒店评价语料
1、首先是训练Glove,获得词向量(这里是用的300d)。这一步使用的是jieba分词和中文维基。
2、将中文酒店评价语料进行清洗,并分词。分词后转化为词向量的表示形式。
3、使用LSTM网络进行训练。
最终的正确率在91%左右
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 30 13:52:23 2018 @author: xyli
处理酒店评价语料数据,
分词,并转化为Glove向量
"""
import sys
import os
import chardet
import jieba
import re
import gensim
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.utils.np_utils import to_categorical from keras.layers import Masking
from keras.layers import Dense, Input, Flatten, Activation
from keras.layers import Conv1D, GlobalMaxPooling1D, Embedding, Merge, Dropout, LSTM, GRU, Bidirectional,Reshape
from keras.models import Sequential, Model
from Attention_layer import Attention_layer from keras.layers import Convolution2D, MaxPooling2D
from keras.utils import np_utils def loadGLoveModel(filename):
embeddings_index = {}
f = open(filename)
for line in f:
values = line.split()
word = values[0]
coefs = np.asarray(values[1:], dtype='float32')
embeddings_index[word] = coefs
f.close()
return embeddings_index def word2Glovec(List,model):
vec=[]
insert = [float(0) for i in range(300)] #300表示vec的维度
insert = np.asarray(insert, dtype='float32')
for w in List:
v = model.get(w)
if v is None:
vec.append(insert)
else:
vec.append(v)
return vec def clean_str(string):
"""
Tokenization/string cleaning for dataset
Every dataset is lower cased except
"""
# string = string.decode('utf-8')
string = re.sub(r"\\", "", string)
string = re.sub(r"\'", "", string)
string = re.sub(r"\"", "", string)
string = re.sub(r"\r\n", "", string)
string = re.sub(r"\r", "", string)
string = re.sub(r"\,","",string)
string = re.sub(r"\.","",string)
string = re.sub(r"\,","",string)
string = re.sub(r"\。","",string)
string = re.sub(r"\(","",string)
string = re.sub(r"\)","",string)
string = re.sub(r"\(","",string)
string = re.sub(r"\)","",string)
string = re.sub(r"\“","",string)
string = re.sub(r"\”","",string)
return string.strip() def fitList(List,n):
L = len(List)
# insert = [0 for i in range(300)]
insert = '!'
if L < n:
d=n-L
appList=[insert for i in range(d)]
List+=appList
else:
if L>n:
List=List[0:n]
return List def readData(filename): with open(filename, 'rb') as f:
data = f.read()
data=data.decode('gb18030','ignore')
data=clean_str(data)
seg_list = jieba.cut(data) # 默认是精确模式
segList=[]
for s in seg_list:
s=clean_str(s)
segList.append(s)
return segList def loadData():
Corpus_DIR = "data/ChnSentiCorp_htl_unba_10000"
DIR=['/neg','/pos']
commentList=[]
rootdir = Corpus_DIR+DIR[0]
filelist = os.listdir(rootdir) #列出文件夹下所有的目录与文件
labelList=[[0.0,1.0] for i in range(0,len(filelist))]
for i in range(0,len(filelist)):
path = os.path.join(rootdir,filelist[i])
if os.path.isfile(path):
templist=readData(path)
commentList.append(templist) rootdir = Corpus_DIR+DIR[1]
filelist = os.listdir(rootdir) #列出文件夹下所有的目录与文件
labelList2=[[1.0,0.0] for i in range(0,len(filelist))]
for i in range(0,len(filelist)):
path = os.path.join(rootdir,filelist[i])
if os.path.isfile(path):
templist=readData(path)
commentList.append(templist)
labelList+=labelList2
return commentList,labelList if __name__=='__main__':
List,labelList=loadData() #加载语料数据
gloveModel=loadGLoveModel('model/zhs_wiki_glove.vectors.300d.txt') #加载glove模型数据
countList=[]
commentVecList=[]
n=100
for c in List:
countList.append(len(c))
glovec=word2Glovec(fitList(c,n),gloveModel)
commentVecList.append(glovec) VALIDATION_SPLIT = 0.2 commentVecList=np.array(commentVecList)
labelList=np.array(labelList)
indices = np.arange(commentVecList.shape[0])
np.random.shuffle(indices)
data = commentVecList[indices]
labels = labelList[indices] nb_validation_samples = int(VALIDATION_SPLIT * data.shape[0])
x_train = data[:-nb_validation_samples]
y_train = labels[:-nb_validation_samples]
x_val = data[-nb_validation_samples:]
y_val = labels[-nb_validation_samples:] model = Sequential()
model.add(LSTM(120, input_shape=(x_train.shape[1], x_train.shape[2]),return_sequences=True))
# model.add(Activation('relu')) #激活层
# model.add(Attention_layer())
model.add(Bidirectional(LSTM(60,return_sequences=True)))
# model.add(Attention_layer())
# model.add(Activation('relu')) #激活层
model.add(Dropout(0.3)) #神经元随机失活
model.add(Bidirectional(LSTM(30,return_sequences=False)))
model.add(Dropout(0.3)) #神经元随机失活
model.add(Dense(y_train.shape[1], activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.summary()
model.fit(x_train, y_train, validation_data=(x_val, y_val),
epochs=25, batch_size=200)
本文还在完善中。。。
中文情感分析 glove+LSTM的更多相关文章
- 中文情感分析——snownlp类库 源码注释及使用
最近发现了snownlp这个库,这个类库是专门针对中文文本进行文本挖掘的. 主要功能: 中文分词(Character-Based Generative Model) 词性标注(TnT 3-gram 隐 ...
- 使用Spark MLlib进行情感分析
使用Spark MLlib进行情感分析 使用Spark MLlib进行情感分析 一.实验说明 在当今这个互联网时代,人们对于各种事情的舆论观点都散布在各种社交网络平台或新闻提要 ...
- 情感分析snownlp包部分核心代码理解
snownlps是用Python写的个中文情感分析的包,自带了中文正负情感的训练集,主要是评论的语料库.使用的是朴素贝叶斯原理来训练和预测数据.主要看了一下这个包的几个主要的核心代码,看的过程作了一些 ...
- LSTM实现中文文本情感分析
1. 背景介绍 文本情感分析是在文本分析领域的典型任务,实用价值很高.本模型是第一个上手实现的深度学习模型,目的是对深度学习做一个初步的了解,并入门深度学习在文本分析领域的应用.在进行模型的上手实现之 ...
- 文本情感分析(二):基于word2vec、glove和fasttext词向量的文本表示
上一篇博客用词袋模型,包括词频矩阵.Tf-Idf矩阵.LSA和n-gram构造文本特征,做了Kaggle上的电影评论情感分类题. 这篇博客还是关于文本特征工程的,用词嵌入的方法来构造文本特征,也就是用 ...
- LSTM 文本情感分析/序列分类 Keras
LSTM 文本情感分析/序列分类 Keras 请参考 http://spaces.ac.cn/archives/3414/ neg.xls是这样的 pos.xls是这样的neg=pd.read_e ...
- NLP入门(十)使用LSTM进行文本情感分析
情感分析简介 文本情感分析(Sentiment Analysis)是自然语言处理(NLP)方法中常见的应用,也是一个有趣的基本任务,尤其是以提炼文本情绪内容为目的的分类.它是对带有情感色彩的主观性 ...
- NLP之中文自然语言处理工具库:SnowNLP(情感分析/分词/自动摘要)
一 安装与介绍 1.1 概述 SnowNLP是一个python写的类库,可以方便的处理中文文本内容,是受到了TextBlob的启发而写的,由于现在大部分的自然语言处理库基本都是针对英文的,于是写了一个 ...
- 机器学习 - LSTM应用之情感分析
1. 概述 在情感分析的应用领域,例如判断某一句话是positive或者是negative的案例中,咱们可以通过传统的standard neuro network来作为解决方案,但是传统的神经网络在应 ...
随机推荐
- JSP-Runoob:JSP开发环境搭建
ylbtech-JSP-Runoob:JSP开发环境搭建 1.返回顶部 1. JSP 开发环境搭建 JSP开发环境是您用来开发.测试和运行JSP程序的地方. 本节将会带您搭建JSP开发环境,具体包括以 ...
- bzoj 2878: [Noi2012]迷失游乐园【树上期望dp+基环树】
参考:https://blog.csdn.net/shiyukun1998/article/details/44684947 先看对于树的情况 设d[u]为点u向儿子走的期望长度和,du[u]为u点的 ...
- P4576 [CQOI2013]棋盘游戏
传送门 很显然,除非白子和黑子相邻,否则必然是黑子获胜虽然我并没有看出来 那么现在对黑子来说它要尽可能快的赢,对白子它要多苟一会儿 然后就是这个叫做对抗搜索的东西了 //minamoto #inclu ...
- Java多线程(二) synchronized 针对对象进行锁定
http://www.cnblogs.com/QQParadise/articles/5059824.html 1.方法内的变量为线程安全的 2.实例变量非线程安全的 public class Has ...
- Window对象与DOM
目前,前端插件数不胜数,比如有移动端滑动特效插件Swiper,下拉刷新的iScroll,弹出框插件layer,还有我们经常使用的JQuery,jquery.mobile等,这些插件能够满足我们日常的基 ...
- fiddler不同代理模式的区别
Fiddler有不同的代理模式,分为以下两种: 流模式(Streaming)和缓冲模式(Buffering). 流模式可以理解为一种实时通信的模式,有请求就有返回,也就是实时返回. 缓冲模式是等所有请 ...
- EasyUI系列学习(九)-Panel(面板)
一.加载方式 1.class加载 <div class="easyui-panel" title="面板一" style="width:500p ...
- MacOS 下安装 MySQL8.0 登陆 MySQL
按照 官方教程 ,下载安装包,点击安装后,如需在命令行启动,还需设置命令路径: 在命令行中,打开配置文件 .bash_profile: vim ~/.bash_profile 在最后一行加上: PAT ...
- 【转】rpm包和源码包安装的区别
转自:https://blog.csdn.net/junjie_6/article/details/59483785 建议在安装线上的生产服务器软件包时都用源码安装,这是因为源码安装可以自行调整编译参 ...
- LN : leetcode 690 Employee Importance
lc 690 Employee Importance 690 Employee Importance You are given a data structure of employee inform ...