1 Star 0 Fork 0

吴hh/ML

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
单向rnn、双向rnn_embedding.py 5.01 KB
一键复制 编辑 原始数据 按行查看 历史
# -*- 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上升,效果变好;但是仍然是过拟合的,可以看作模型强大"""
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/wuhaohua1314/ML.git
git@gitee.com:wuhaohua1314/ML.git
wuhaohua1314
ML
ML
NLP实战

搜索帮助