KERAS学习(二):电影评级分类-二分类问题

1
2
3
#加载IMDB数据集
from keras.datasets import imdb
(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000)
1
Using TensorFlow backend.
1
train_data[0]
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
[1,
14,
22,
16,
43,
530,
973,
1622,
1385,
65,
458,
4468,
66,
3941,
4,
173,
36,
256,
5,
25,
100,
43,
838,
112,
50,
670,
2,
9,
35,
480,
284,
5,
150,
4,
172,
112,
167,
2,
336,
385,
39,
4,
172,
4536,
1111,
17,
546,
38,
13,
447,
4,
192,
50,
16,
6,
147,
2025,
19,
14,
22,
4,
1920,
4613,
469,
4,
22,
71,
87,
12,
16,
43,
530,
38,
76,
15,
13,
1247,
4,
22,
17,
515,
17,
12,
16,
626,
18,
2,
5,
62,
386,
12,
8,
316,
8,
106,
5,
4,
2223,
5244,
16,
480,
66,
3785,
33,
4,
130,
12,
16,
38,
619,
5,
25,
124,
51,
36,
135,
48,
25,
1415,
33,
6,
22,
12,
215,
28,
77,
52,
5,
14,
407,
16,
82,
2,
8,
4,
107,
117,
5952,
15,
256,
4,
2,
7,
3766,
5,
723,
36,
71,
43,
530,
476,
26,
400,
317,
46,
7,
4,
2,
1029,
13,
104,
88,
4,
381,
15,
297,
98,
32,
2071,
56,
26,
141,
6,
194,
7486,
18,
4,
226,
22,
21,
134,
476,
26,
480,
5,
144,
30,
5535,
18,
51,
36,
28,
224,
92,
25,
104,
4,
226,
65,
16,
38,
1334,
88,
12,
16,
283,
5,
16,
4472,
113,
103,
32,
15,
16,
5345,
19,
178,
32]
1
train_labels
1
array([1, 0, 0, ..., 0, 1, 0])
1
max([max(sequence) for sequence in train_data])
1
9999
1
2
3
4
5
6
#索引解码成单词
word_index = imdb.get_word_index()
reverse_word_index = dict(
[(value, key) for (key, value) in word_index.items()])
decoded_review = ' '.join(
[reverse_word_index.get(i - 3, '?') for i in train_data[0]]) #第一个评论
1
decoded_review
1
"? this film was just brilliant casting location scenery story direction everyone's really suited the part they played and you could just imagine being there robert ? is an amazing actor and now the same being director ? father came from the same scottish island as myself so i loved the fact there was a real connection with this film the witty remarks throughout the film were great it was just brilliant so much that i bought the film as soon as it was released for ? and would recommend it to everyone to watch and the fly fishing was amazing really cried at the end it was so sad and you know what they say if you cry at a film it must have been good and this definitely was also ? to the two little boy's that played the ? of norman and paul they were just brilliant children are often left out of the ? list i think because the stars that play them all grown up are such a big profile for the whole film but these children are amazing and should be praised for what they have done don't you think the whole story was so lovely because it was true and was someone's life after all that was shared with us all"
1
2
3
4
5
6
7
8
9
10
#数据向量化
import numpy as np
def vectorize_sequences(sequences, dimension=10000):
results= np.zeros((len(sequences), dimension))
for i, sequence in enumerate(sequences):
results[i, sequence] = 1.
return results

x_train = vectorize_sequences(train_data)
x_test = vectorize_sequences(test_data)
1
x_train[0]
1
array([0., 1., 1., ..., 0., 0., 0.])
1
2
3
#标签向量化
y_train = np.asarray(train_labels).astype('float32')
y_test = np.asarray(test_labels).astype('float32')
1
2
3
4
5
6
7
8
9
10
#构建网络 模型定义
#激活函数relu 所有负值归0
#任意值“压缩”到[0, 1]区间内
from keras import models
from keras import layers
model = models.Sequential()
model.add(layers.Dense(16, activation='relu', input_shape=(10000,)))
model.add(layers.Dense(16, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))
#relu 负值归零 sigmoid 任意值压缩到[0, 1]区间内
1
2
3
#损失函数 优化器 指标 编译模型
#
model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy'])
1
2
3
4
5
6
#从训练数据中留出验证集
x_val = x_train[:10000]
partial_x_train = x_train[10000:]

y_val = y_train[:10000]
partial_y_train = y_train[10000:]
1
2
3
#训练模型
model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['acc'])
history = model.fit(partial_x_train, partial_y_train, epochs=20, batch_size=512, validation_data=(x_val, y_val))
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
Train on 15000 samples, validate on 10000 samples
Epoch 1/20
15000/15000 [==============================] - 6s 421us/step - loss: 0.5083 - acc: 0.7819 - val_loss: 0.3788 - val_acc: 0.8690
Epoch 2/20
15000/15000 [==============================] - 5s 311us/step - loss: 0.3001 - acc: 0.9048 - val_loss: 0.3000 - val_acc: 0.8901
Epoch 3/20
15000/15000 [==============================] - 4s 257us/step - loss: 0.2178 - acc: 0.9284 - val_loss: 0.3082 - val_acc: 0.8715
Epoch 4/20
15000/15000 [==============================] - 3s 221us/step - loss: 0.1750 - acc: 0.9435 - val_loss: 0.2838 - val_acc: 0.8839
Epoch 5/20
15000/15000 [==============================] - 4s 241us/step - loss: 0.1425 - acc: 0.9543 - val_loss: 0.2850 - val_acc: 0.8865
Epoch 6/20
15000/15000 [==============================] - 3s 222us/step - loss: 0.1149 - acc: 0.9652 - val_loss: 0.3163 - val_acc: 0.8773
Epoch 7/20
15000/15000 [==============================] - 4s 265us/step - loss: 0.0978 - acc: 0.9710 - val_loss: 0.3130 - val_acc: 0.8847
Epoch 8/20
15000/15000 [==============================] - 3s 231us/step - loss: 0.0807 - acc: 0.9765 - val_loss: 0.3861 - val_acc: 0.8653
Epoch 9/20
15000/15000 [==============================] - 3s 215us/step - loss: 0.0660 - acc: 0.9820 - val_loss: 0.3636 - val_acc: 0.8782
Epoch 10/20
15000/15000 [==============================] - 4s 254us/step - loss: 0.0555 - acc: 0.9852 - val_loss: 0.3845 - val_acc: 0.8790
Epoch 11/20
15000/15000 [==============================] - 3s 194us/step - loss: 0.0449 - acc: 0.9888 - val_loss: 0.4167 - val_acc: 0.8766
Epoch 12/20
15000/15000 [==============================] - 4s 247us/step - loss: 0.0385 - acc: 0.9913 - val_loss: 0.4511 - val_acc: 0.8700
Epoch 13/20
15000/15000 [==============================] - 4s 251us/step - loss: 0.0298 - acc: 0.9927 - val_loss: 0.4705 - val_acc: 0.8727
Epoch 14/20
15000/15000 [==============================] - 4s 259us/step - loss: 0.0244 - acc: 0.9949 - val_loss: 0.5029 - val_acc: 0.8723
Epoch 15/20
15000/15000 [==============================] - 3s 233us/step - loss: 0.0177 - acc: 0.9979 - val_loss: 0.5375 - val_acc: 0.8692
Epoch 16/20
15000/15000 [==============================] - 4s 239us/step - loss: 0.0170 - acc: 0.9967 - val_loss: 0.5728 - val_acc: 0.8702
Epoch 17/20
15000/15000 [==============================] - 3s 196us/step - loss: 0.0093 - acc: 0.9995 - val_loss: 0.6176 - val_acc: 0.8654
Epoch 18/20
15000/15000 [==============================] - 3s 224us/step - loss: 0.0117 - acc: 0.9975 - val_loss: 0.6386 - val_acc: 0.8669
Epoch 19/20
15000/15000 [==============================] - 3s 211us/step - loss: 0.0069 - acc: 0.9992 - val_loss: 0.7420 - val_acc: 0.8559
Epoch 20/20
15000/15000 [==============================] - 4s 238us/step - loss: 0.0043 - acc: 0.9999 - val_loss: 0.6976 - val_acc: 0.8655
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#绘制训练损失和验证损失
import matplotlib.pyplot as plt

history_dict = history.history
loss_values = history_dict['loss']
val_loss_values = history_dict['val_loss']

epochs = range(1, len(loss_values) + 1)

plt.plot(epochs, loss_values, 'bo', label='Training loss')
plt.plot(epochs, val_loss_values, 'b', label='Valifation loss')
plt.title('Training and validation loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()

plt.show()
1
<Figure size 640x480 with 1 Axes>
1
history_dict.keys()
1
dict_keys(['val_loss', 'val_acc', 'loss', 'acc'])
1
2
3
4
5
6
7
8
9
10
11
12
13
#绘制训练精度和验证精度
plt.clf()
acc = history_dict['acc']
val_acc = history_dict['val_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.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend()

plt.show()

png

1
2
results = model.evaluate(x_test, y_test)
results
1
25000/25000 [==============================] - 7s 272us/step
1
[0.768154475197792, 0.85032]
1
2
#预测评价正面的可能性
model.predict(x_test)
1
2
3
4
5
6
7
array([[0.00997098],
[0.9999999 ],
[0.971289 ],
...,
[0.00219277],
[0.0054981 ],
[0.72482127]], dtype=float32)