代码拉取完成,页面将自动刷新
# -*- coding: utf-8 -*-
"""单向RNN、双向RNN-embedding.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/18T6WUWX_fdG23ufTD6CkelZnQVYnaU3w
"""
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow import keras
import sklearn
import os
import sys
import time
print(tf.__version__)
print(sys.version_info)
for module in mpl,np,pd,sklearn,tf,keras:
print(module.__name__,module.__version__)
imdb=keras.datasets.imdb
vocab_size=10000
index_from=3
(train_data,train_labels),(test_data,test_labels)=imdb.load_data(num_words=vocab_size,index_from=index_from)
word_index=imdb.get_word_index()
print(len(word_index))
word_index={k:(v+3) for k,v in word_index.items()}
word_index['<PAD>']=0
word_index['<START>']=1
word_index['<UNK>']=2
word_index['<END>']=3
reverse_word_index=dict([
(value,key) for key,value in word_index.items()
])
def decode_review(text_ids):
return ' '.join([reverse_word_index.get(word_id,'<UNK>') for word_id in text_ids])
decode_review(train_data[0])
max_length=500
train_data=keras.preprocessing.sequence.pad_sequences(
train_data,value=word_index['<PAD>'],
padding='post',maxlen=max_length
)
test_data=keras.preprocessing.sequence.pad_sequences(
test_data,value=word_index['<PAD>'],
padding='post',maxlen=max_length
)
print(train_data[0])
embedding_dim=16
batch_size=512
# 把DNN的全局平均换成单向RNN,时间变长,不断修改效果变好
# return_sequences:Boolean. Whether to return the last output in the output sequence, or the full sequence 文本生成、机器翻译是要返回所有序列的True,只要最后一个序列False
single_rnn_model=keras.models.Sequential([
keras.layers.Embedding(vocab_size,embedding_dim,input_length=max_length),
keras.layers.SimpleRNN(units=64,return_sequences=False),
# w=64,b=64
keras.layers.Dense(64,activation='relu'),
keras.layers.Dense(1,activation='sigmoid'),
])
single_rnn_model.summary()
single_rnn_model.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])
# 全连接层参数是4160 wx+b:x是一维的64
single_rnn_model.variables
history_single_rnn=single_rnn_model.fit(
train_data,train_labels,
epochs=30,
batch_size=batch_size,
validation_split=0.2
)
def plot_learning_curves(history,label,epochs,min_value,max_value):
data={}
data[label]=history.history[label]
data['val_'+label]=history.history['val_'+label]
pd.DataFrame(data).plot(figsize=(8,5))
plt.grid(True)
plt.axis([0,epochs,min_value,max_value])
plt.show()
# 训练集、验证集上的准确率
plot_learning_curves(history_single_rnn,'accuracy',30,0,1)
# 训练集、验证集上的损失
plot_learning_curves(history_single_rnn,'loss',30,0,1)
single_rnn_model.evaluate(
test_data,test_labels,
batch_size=batch_size,
verbose=0
)
"""损失接近70%,准确率是50%—单向RNN没啥用"""
!nvidia-smi
# 改成双向RNN
embedding_dim=16
batch_size=512
model=keras.models.Sequential([
keras.layers.Embedding(vocab_size,embedding_dim,input_length=max_length),
# 增加数据,2层双向RNN
keras.layers.Bidirectional(keras.layers.SimpleRNN(units=64,return_sequences=True)),
keras.layers.Bidirectional(keras.layers.SimpleRNN(units=64,return_sequences=False)),
keras.layers.Dense(64,activation='relu'),
keras.layers.Dense(1,activation='sigmoid'),
])
model.summary()
model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy'])
history=model.fit(train_data,train_labels,epochs=30,batch_size=batch_size,validation_split=0.2)
"""在训练集上准确率能达到100%,就足够说明模型强大了"""
plot_learning_curves(history,'accuracy',30,0,1)
plot_learning_curves(history,'loss',30,0,4)
"""过拟合了,可能是模型太复杂,改为单层的RNN"""
# 改成双向RNN
embedding_dim=16
batch_size=512
model=keras.models.Sequential([
keras.layers.Embedding(vocab_size,embedding_dim,input_length=max_length),
# 增加数据,2层双向RNN
keras.layers.Bidirectional(keras.layers.SimpleRNN(units=64,return_sequences=True)),
# keras.layers.Bidirectional(keras.layers.SimpleRNN(units=64,return_sequences=False)),
keras.layers.Dense(64,activation='relu'),
keras.layers.Dense(1,activation='sigmoid'),
])
model.summary()
model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy'])
history=model.fit(train_data,train_labels,epochs=30,batch_size=batch_size,validation_split=0.2)
plot_learning_curves(history,'accuracy',30,0,1)
plot_learning_curves(history,'loss',30,0,4)
model.evaluate(test_data,test_labels,batch_size=batch_size,verbose=0)
"""与单向RNN相比loss减少,accuracy上升,效果变好;但是仍然是过拟合的,可以看作模型强大"""
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。