Python 深度学习--学习笔记(十二)

用simpleRNN对imdb评论进行判断

任何一门语言都有逻辑。人类阅读文本,要靠上下文理解全篇大意,那机器能否也能学习人类语言呢?基于这个思想,开发出了一种处理语言的学习层——循环神经网络(RNN).

我们说的每一个字都对接下来要说的话有影响,用机器理解,就是将上一个单词的处理传入下一次单词的处理中去,它处理序列的方式是,遍历所有序列元素,并保存一个状态(state),其中包含与已查看内容相关的信息。实际上,RNN 是一类具有内部环的神经网络(见下图)。在处理两个不同的独立序列(比如两条不同的 IMDB 评论)之间,RNN 状态(state)会被重置,因此,你仍可以将一个序列看作单个数据点,即网络的单个输入。真正改变的是,数据点不再是在单个步骤中进行处理,相反,网络内部会对序列元素进行遍历。
1
为了方便理解,这里贴上书163页的RNN 伪代码:
(input_sequence.shape == (timesteps,input_features)
可以简单理解timesteps就是每则评论需要处理的单词,input_features理解为每个单词的词向量)
2
这里再贴出详细用代码操作的过程:
3

今天,我们介绍在Keras中简单实现RNN学习——SimpleRNN.
它接收形状为 (batch_size, timesteps,input_features) 的输入。
Keras 中的所有循环层一样,SimpleRNN 可以在两种不同的模式下运行:一种是返回每个时间步
连续输出的完整序列
,即形状为 (batch_size, timesteps, output_features)的三维张量;
另一种是只返回每个输入序列的
最终输出
,即形状为 (batch_size, output_features) 的二维张量。
这两种模式由 return_sequences 这个构造函数参数来控制。
这里用代码看看区别:
4
5


6
7
在多个循环层逐个堆叠时,需要在除最后一次循环层的其他所有堆叠循环层上加上 return_sequences=True,因为循环层需要传入的时一个三维数组。

8
介绍到最后,让我们用一个实际的例子来体现SimpleRNN.

  • 准备数据
# 准备 IMDB 数据
from keras.datasets import imdb
from keras.preprocessing import sequence

max_features = 10000
maxlen = 500
batch_size = 32

print('Loading data...')
(input_train,y_train),(input_test,y_test) = imdb.load_data(num_words=max_features)

print(len(input_train),'train sequence')
print(len(input_test),'test sequence')

print('Pad sequences (sample x time)')
input_train = sequence.pad_sequences(input_train,maxlen=maxlen)
input_test = sequence.pad_sequences(input_test,maxlen=maxlen)
print('input_train shape:',input_train.shape)
print('input_test shape:',input_test.shape)
  • 构建,编译,训练模型
from keras.layers import Dense

model = Sequential()
model.add(Embedding(max_features,32,input_length=maxlen))
model.add(SimpleRNN(32))
model.add(Dense(1,activation='sigmoid'))

model.compile(optimizer='rmsprop',
              loss='binary_crossentropy',
              metrics=['acc'])

history = model.fit(input_train,y_train,
                    epochs=10,
                    batch_size=128,
                    validation_split=0.2)

9

  • 绘图
import matplotlib.pyplot as plt

acc = history.history['acc']
val_acc = history.history['val_acc']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(1,len(acc)+1)


plt.figure('loss')
plt.plot(epochs,loss,'bo',label="Training loss")
plt.plot(epochs,val_loss,'b',label="Validation loss")
plt.title("Training and validation loss")
plt.legend()

plt.figure('acc')
plt.plot(epochs, acc, 'bo', label='Training acc')
plt.plot(epochs, val_acc, 'b', label='Validation acc')
plt.title('Training and validation accuracy')
plt.legend()

plt.show()

10
可以看出,模型已严重过拟合,还需要重新调整模型结构。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值