最近尝试了一下中文的情感分析。

主要使用了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的更多相关文章

  1. 中文情感分析——snownlp类库 源码注释及使用

    最近发现了snownlp这个库,这个类库是专门针对中文文本进行文本挖掘的. 主要功能: 中文分词(Character-Based Generative Model) 词性标注(TnT 3-gram 隐 ...

  2. 使用Spark MLlib进行情感分析

    使用Spark MLlib进行情感分析             使用Spark MLlib进行情感分析 一.实验说明 在当今这个互联网时代,人们对于各种事情的舆论观点都散布在各种社交网络平台或新闻提要 ...

  3. 情感分析snownlp包部分核心代码理解

    snownlps是用Python写的个中文情感分析的包,自带了中文正负情感的训练集,主要是评论的语料库.使用的是朴素贝叶斯原理来训练和预测数据.主要看了一下这个包的几个主要的核心代码,看的过程作了一些 ...

  4. LSTM实现中文文本情感分析

    1. 背景介绍 文本情感分析是在文本分析领域的典型任务,实用价值很高.本模型是第一个上手实现的深度学习模型,目的是对深度学习做一个初步的了解,并入门深度学习在文本分析领域的应用.在进行模型的上手实现之 ...

  5. 文本情感分析(二):基于word2vec、glove和fasttext词向量的文本表示

    上一篇博客用词袋模型,包括词频矩阵.Tf-Idf矩阵.LSA和n-gram构造文本特征,做了Kaggle上的电影评论情感分类题. 这篇博客还是关于文本特征工程的,用词嵌入的方法来构造文本特征,也就是用 ...

  6. LSTM 文本情感分析/序列分类 Keras

    LSTM 文本情感分析/序列分类 Keras 请参考 http://spaces.ac.cn/archives/3414/   neg.xls是这样的 pos.xls是这样的neg=pd.read_e ...

  7. NLP入门(十)使用LSTM进行文本情感分析

    情感分析简介   文本情感分析(Sentiment Analysis)是自然语言处理(NLP)方法中常见的应用,也是一个有趣的基本任务,尤其是以提炼文本情绪内容为目的的分类.它是对带有情感色彩的主观性 ...

  8. NLP之中文自然语言处理工具库:SnowNLP(情感分析/分词/自动摘要)

    一 安装与介绍 1.1 概述 SnowNLP是一个python写的类库,可以方便的处理中文文本内容,是受到了TextBlob的启发而写的,由于现在大部分的自然语言处理库基本都是针对英文的,于是写了一个 ...

  9. 机器学习 - LSTM应用之情感分析

    1. 概述 在情感分析的应用领域,例如判断某一句话是positive或者是negative的案例中,咱们可以通过传统的standard neuro network来作为解决方案,但是传统的神经网络在应 ...

随机推荐

  1. 8. Ext文本输入框:Ext.form.TextField属性汇总

    转自:https://blog.csdn.net/ryuudenne/article/details/8834650 Ext.form.TextField主要配置表: allowBlank       ...

  2. Rails5 Model Document

    创建: 2017/06/09 更新: 2017/06/21 更新: 2017/06/23 对待未完成的追加# TODO: 更新: 2017/06/29 修正文件名db/seed.rb ---> ...

  3. bzoj 1999: [Noip2007]Core树网的核【树的直径+单调队列】

    我要懒死了,所以依然是lyd的课件截图 注意是min{max(max(d[uk]),dis(u1,ui),dis(uj,un))},每次都从这三个的max里取min #include<iostr ...

  4. [App Store Connect帮助]六、测试 Beta 版本(4.3) 管理 Beta 版构建版本:为 Beta 版构建版本提供出口合规证明

    如果您没有完成出口合规证明,则该 Beta 版构建版本的状态为“缺少合规证明”.您可以在 TestFlight 部分中回答必需的出口合规证明问题. 必要职能:“帐户持有人”职能.“管理”职能或“App ...

  5. [App Store Connect帮助]三、管理 App 和版本(6.3)转让 App:发起 App 转让

    在发起前,您需要接收者组织中“帐户持有人”的 Apple ID,并且满足 App 转让的条件.请前往 App 转让条件. 注:App 转让完成后,该 App 会从您的帐户中移除,因此,您应当备份该 A ...

  6. Django之序列化

    关于Django中的序列化主要应用在将数据库中检索的数据返回给客户端用户,特别的Ajax请求一般返回的为Json格式. 1.serializers           from django.core ...

  7. DataGridView 动态绑定 CheckBox

    下面演示如何在 DataGridView 中动态绑定 CheckBox: public class Test { /// <summary> /// 构造器 /// </summar ...

  8. [转]iOS WebKit browsers and auto-zooming form controls

    问题描述:https://github.com/jquery/jquery-mobile/issues/2581 本文转自:http://www.456bereastreet.com/archive/ ...

  9. 6.13---example

    example如何使用?简单查询这个例子展示了如何用生成后的Example类去生成一个简单的where子句: TestTableExample example = new TestTableExamp ...

  10. 你的宽带ip地址被100.64了吗?

    你的宽带ip地址被100.64了吗?   最近需要用外网的时候发现,宿舍路由wan口的ip变成了100.64.X.X,本以为是一个外网的ip,可事实上并不是,并且从外网无法直接访问.   首先,我们都 ...