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

主要使用了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. 2-3 Vue实例中的数据,事件和方法

    上节课模板是写在Vue的实例里面的,现在我们可以把它恢复出来.写在挂载点的内部,看起来会舒服一点.Vue的数据项,可以配置任意的数据名字. <!DOCTYPE html> <html ...

  2. bzoj 1657: [Usaco2006 Mar]Mooo 奶牛的歌声【单调栈】

    先考虑只能往一边传播,最后正反两边就行 一向右传播为例,一头牛能听到的嚎叫是他左边的牛中与高度严格小于他并且和他之间没有更高的牛,用单调递减的栈维护即可 #include<iostream> ...

  3. 清北考前刷题day2早安

    /* 做法一:按h sort一遍,对于一段区间[i,j],高度花费就是h[j]-h[i] 然后枚举区间,把区间内C排序,一个一个尽量选即可. n^3logn 标算:n^3 dp 高度排序,保证从前往后 ...

  4. [App Store Connect帮助]四、添加 App 图标、App 预览和屏幕快照(5)移除 App 预览或屏幕快照

    您可以随时移除 App 预览,但仅可在 App 状态为可编辑时才能移除屏幕快照.要了解可编辑的状态,请前往 App 状态. 必要职能:“帐户持有人”职能.“管理”职能.“App 管理”职能或“营销”职 ...

  5. 字符类型C++(ascll码表)

    ascll码: 序号 字符 序号 字符 序号 字符 序号 字符 序号 字符 序号 字符 32 空格 48 0 64 @ 80 P 96 ` 112 p 33 ! 49 1 65 A 81 Q 97 a ...

  6. window后台运行java jar文件

    第一种需要一直开着dos界面: java -jar jar文件路径 第二种无需一直开着dos界面: 1.新建my-service.bat文件,内容如下: @echo off START "m ...

  7. Visual Studio 相关

    基础配置: 背景色:豆沙绿(色调84 饱和度118 亮度205) 字体字号:Consolas 11号  离线下载方法: vs_enterprise.exe --layout c:\vs2017offl ...

  8. LN : leetcode 3 Longest Substring Without Repeating Characters

    lc 3 Longest Substring Without Repeating Characters 3 Longest Substring Without Repeating Characters ...

  9. Selenium基于Python web自动化测试框架 -- PO

    关于selenium测试框架首先想到的就是PO模型,简单说下PO模型 PO模型的概念和理解: PO就是一个设计思想,将代码以页面为单位进行组织,针对这个页面上的所有信息.相关操作都放到一个类中,从而使 ...

  10. SugarCRM安装过程——PHP文件上传限制问题

    找到D:\xampp\php目录下,php文件中的php.ini文件,用写字板打开: 1.查找post_max_size,指通过表单POST给PHP的所能接收的最大值,包括表单里的所有值,默认为8M, ...