我是靠谱客的博主 舒适季节,这篇文章主要介绍深度学习---情感分析(Rnn,LSTM),现在分享给大家,希望可以做个参考。

借鉴了苏建林大神的博客关于情感分析的三篇文章。并在此基础上 新加了停用词。停用词的下载链接:停用词

代码环境:

python2.7

tensorflow-gpu 1.0

jieba

试验后的准确率高达98%,结果如下:


代码如下:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# -*- coding:utf-8 -*- ''' 在GTX1070上,11s一轮 经过30轮迭代,训练集准确率为98.41% Dropout不能用太多,否则信息损失太严重 ''' import numpy as np import pandas as pd import jieba pd.set_option('display.max_columns',8) pd.set_option('display.max_rows',30) pd.set_option('display.max_colwidth',60) #不允许换行显示 pd.set_option('expand_frame_repr',False) #读取stop停用词 stopwords='哈工大停用词表.txt' stop_single_words=[] with open(stopwords,'r') as f: for line in f: content=line.strip() stop_single_words.append(content.decode('gbk')) print stop_single_words #读取情感正与负样本。 pos = pd.read_excel('pos.xls', header=None) pos['label'] = 1 neg = pd.read_excel('neg.xls', header=None) neg['label'] = 0 all_ = pos.append(neg, ignore_index=True) all_['words'] = all_[0].apply(lambda s: [i for i in list(jieba.cut(s)) if i not in stop_single_words]) #调用结巴分词 print all_[:5] maxlen = 100 #截断词数 min_count = 5 #出现次数少于该值的词扔掉。这是最简单的降维方法 content = [] for i in all_['words']: content.extend(i) abc = pd.Series(content).value_counts() abc = abc[abc >= min_count] abc[:] = range(1, len(abc)+1) abc[''] = 0 #添加空字符串用来补全 word_set = set(abc.index) def doc2num(s, maxlen): s = [i for i in s if i in word_set] s = s[:maxlen] + ['']*max(0, maxlen-len(s)) return list(abc[s]) all_['doc2num'] = all_['words'].apply(lambda s: doc2num(s, maxlen)) #手动打乱数据 idx = range(len(all_)) np.random.shuffle(idx) all_ = all_.loc[idx] #按keras的输入要求来生成数据 x = np.array(list(all_['doc2num'])) y = np.array(list(all_['label'])) y = y.reshape((-1,1)) #调整标签形状 from keras.models import Sequential from keras.layers import Dense, Activation, Dropout, Embedding from keras.layers import LSTM #建立模型 model = Sequential() model.add(Embedding(len(abc), 256, input_length=maxlen)) model.add(LSTM(128)) model.add(Dropout(0.5)) model.add(Dense(1)) model.add(Activation('sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) batch_size = 128 train_num = 15000 model.fit(x[:train_num], y[:train_num], batch_size = batch_size, nb_epoch=30) model.evaluate(x[train_num:], y[train_num:], batch_size = batch_size) def predict_one(s): #单个句子的预测函数 s = np.array(doc2num(list(jieba.cut(s)), maxlen)) s = s.reshape((1, s.shape[0])) return model.predict_classes(s, verbose=0)[0][0]

本打算在分词后,尝试Word2vec,但考虑到分词后,数据之间的联系变得很脆弱,就没尝试,如果有人弄了,记得告知哈。

最后

以上就是舒适季节最近收集整理的关于深度学习---情感分析(Rnn,LSTM)的全部内容,更多相关深度学习---情感分析(Rnn内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(74)

评论列表共有 0 条评论

立即
投稿
返回
顶部