利用 Keras 下的 LSTM 进行情感分析

前言


                      我们用 Keras 提供的 LSTM 层构造和训练一个 many-to-one 的 RNN。 网络的输入是一句话,输出是一个情感值(积极或消极)。 所用数据来自 Kaggle 的情感分类比赛 (https://inclass.kaggle.com/c/si650winter11)。 该训练数据长这样:
1           I either LOVE Brokeback Mountain or think it’s great that homosexuality is becoming more acceptable!:
1           Anyway, thats why I love ” Brokeback Mountain.
1           Brokeback mountain was beautiful…
0           da vinci code was a terrible movie.
0           Then again, the Da Vinci code is super shitty movie, and it made like 700 million.
0           The Da Vinci Code comes out tomorrow, which sucks.
其中的每个句子都有个标签 1 或 0, 用来代表积极或消极。(下载数据)




             先把用到的包一次性全部导入

from keras.layers.core import Activation, Dense
from keras.layers.embeddings import Embedding
from keras.layers.recurrent import LSTM
from keras.models import Sequential
from keras.preprocessing import sequence
from sklearn.model_selection import train_test_split
import nltk  #用来分词
import collections  #用来统计词频
import numpy as np

数据准备


                在开始前,先对所用数据做个初步探索。特别地,我们需要知道数据中有多少个不同的单词,每句话由多少个单词组成。

maxlen = 0  #句子最大长度
word_freqs = collections.Counter()  #词频
num_recs = 0 # 样本数
with open('./train.txt','r+') as f:
    for line in f:
        label, sentence = line.strip().split("\t")
        words = nltk.word_tokenize(sentence.lower())
        if len(words) > maxlen:
            maxlen = len(words)
        for word in words:
            word_freqs[word] += 1
        num_recs += 1
print('max_len ',maxlen)
print('nb_words ', len(word_freqs))

             max_len 42
             nb_words 2324

                可见一共有 2324 个不同的单词,包括标点符号。每句话最多包含 42 个单词。
                根据不同单词的个数 (nb_words),我们可以把词汇表的大小设为一个定值,并且对于不在词汇表里的单词,把它们用伪单词 UNK 代替。 根据句子的最大长度 (max_lens),我们可以统一句子的长度,把短句用 0 填充。
                依前所述,我们把 VOCABULARY_SIZE 设为 2002。包含训练数据中按词频从大到小排序后的前 2000 个单词,外加一个伪单词 UNK 和填充单词 0。 最大句子长度 MAX_SENTENCE_LENGTH 设为40。

MAX_FEATURES = 2000
MAX_SENTENCE_LENGTH = 40

  • 28
    点赞
  • 104
    收藏
    觉得还不错? 一键收藏
  • 46
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 46
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值