-
Notifications
You must be signed in to change notification settings - Fork 55
/
单向rnn、双向rnn_embedding.py
169 lines (127 loc) · 5.01 KB
/
单向rnn、双向rnn_embedding.py
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# -*- 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上升,效果变好;但是仍然是过拟合的,可以看作模型强大"""