-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathRStudio-keras-02-imdb.R
490 lines (367 loc) · 12.7 KB
/
RStudio-keras-02-imdb.R
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
# RStudio-keras-01-imdb.R
# 1-2-2. IMDB movie review sentiment classification - https://keras.rstudio.com/articles/examples/imdb_cnn_lstm.html ####
# From:
# https://github.com/rstudio/keras/blob/master/vignettes/examples/imdb_cnn.R =
# https://keras.rstudio.com/articles/examples/imdb_cnn.html =
# https://tensorflow.rstudio.com/keras/articles/examples/imdb_cnn.html
#
#.################################################################################
# 1 > imdb_cnn.R ####
############################################################################### #
#' Use Convolution1D for text classification.
#'
#' Output after 2 epochs: ~0.89
#' Time per epoch on CPU (Intel i5 2.4Ghz): 90s
#' Time per epoch on GPU (Tesla K40): 10s
#'
library(keras)
# Set parameters:
max_features <- 5000
maxlen <- 400
batch_size <- 32
embedding_dims <- 50
filters <- 250
kernel_size <- 3
hidden_dims <- 250
epochs <- 2
# Data Preparation --------------------------------------------------------
# Keras load all data into a list with the following structure:
# List of 2
# $ train:List of 2
# ..$ x:List of 25000
# .. .. [list output truncated]
# .. ..- attr(*, "dim")= int 25000
# ..$ y: num [1:25000(1d)] 1 0 0 1 0 0 1 0 1 0 ...
# $ test :List of 2
# ..$ x:List of 25000
# .. .. [list output truncated]
# .. ..- attr(*, "dim")= int 25000
# ..$ y: num [1:25000(1d)] 1 1 1 1 1 0 0 0 1 1 ...
#
# The x data includes integer sequences, each integer is a word.
# The y data includes a set of integer labels (0 or 1).
# The num_words argument indicates that only the max_fetures most frequent
# words will be integerized. All other will be ignored.
# See help(dataset_imdb)
imdb <- dataset_imdb(num_words = max_features)
# Pad the sequences, so they have all the same length
# This will convert the dataset into a matrix: each line is a review
# and each column a word on the sequence.
# Pad the sequences with 0 to the left.
x_train <- imdb$train$x %>%
pad_sequences(maxlen = maxlen)
x_test <- imdb$test$x %>%
pad_sequences(maxlen = maxlen)
# Defining Model ------------------------------------------------------
#Initialize model
model <- keras_model_sequential()
model %>%
# Start off with an efficient embedding layer which maps
# the vocab indices into embedding_dims dimensions
layer_embedding(max_features, embedding_dims, input_length = maxlen) %>%
layer_dropout(0.2) %>%
# Add a Convolution1D, which will learn filters
# Word group filters of size filter_length:
layer_conv_1d(
filters, kernel_size,
padding = "valid", activation = "relu", strides = 1
) %>%
# Apply max pooling:
layer_global_max_pooling_1d() %>%
# Add a vanilla hidden layer:
layer_dense(hidden_dims) %>%
# Apply 20% layer dropout
layer_dropout(0.2) %>%
layer_activation("relu") %>%
# Project onto a single unit output layer, and squash it with a sigmoid
layer_dense(1) %>%
layer_activation("sigmoid")
# Compile model
model %>% compile(
loss = "binary_crossentropy",
optimizer = "adam",
metrics = "accuracy"
)
# Training ----------------------------------------------------------------
model %>%
fit(
x_train, imdb$train$y,
batch_size = batch_size,
epochs = epochs,
validation_data = list(x_test, imdb$test$y)
)
# . ################################################################################
# 2 > imdb_lstm.R ####
############################################################################### #
#' Trains a LSTM on the IMDB sentiment classification task.
#'
#' The dataset is actually too small for LSTM to be of any advantage compared to
#' simpler, much faster methods such as TF-IDF + LogReg.
#'
#' Notes:
#' - RNNs are tricky. Choice of batch size is important, choice of loss and
#' optimizer is critical, etc. Some configurations won't converge.
#' - LSTM loss decrease patterns during training can be quite different from
#' what you see with CNNs/MLPs/etc.
library(keras)
max_features <- 20000
batch_size <- 32
# Cut texts after this number of words (among top max_features most common words)
maxlen <- 80
cat('Loading data...\n')
imdb <- dataset_imdb(num_words = max_features)
x_train <- imdb$train$x
y_train <- imdb$train$y
x_test <- imdb$test$x
y_test <- imdb$test$y
cat(length(x_train), 'train sequences\n')
cat(length(x_test), 'test sequences\n')
cat('Pad sequences (samples x time)\n')
x_train <- pad_sequences(x_train, maxlen = maxlen)
x_test <- pad_sequences(x_test, maxlen = maxlen)
cat('x_train shape:', dim(x_train), '\n')
cat('x_test shape:', dim(x_test), '\n')
cat('Build model...\n')
model <- keras_model_sequential()
model %>%
layer_embedding(input_dim = max_features, output_dim = 128) %>%
layer_lstm(units = 64, dropout = 0.2, recurrent_dropout = 0.2) %>%
layer_dense(units = 1, activation = 'sigmoid')
# Try using different optimizers and different optimizer configs
model %>% compile(
loss = 'binary_crossentropy',
optimizer = 'adam',
metrics = c('accuracy')
)
cat('Train...\n')
model %>% fit(
x_train, y_train,
batch_size = batch_size,
epochs = 15,
validation_data = list(x_test, y_test)
)
scores <- model %>% evaluate(
x_test, y_test,
batch_size = batch_size
)
cat('Test score:', scores[[1]])
cat('Test accuracy', scores[[2]])
# . ################################################################################
# 3 > imdb_cnn_lstm.R ####
############################################################################### #
#' Train a recurrent convolutional network on the IMDB sentiment
#' classification task.
#'
#' Achieves 0.8498 test accuracy after 2 epochs. 41s/epoch on K520 GPU.
library(keras)
# Parameters --------------------------------------------------------------
# Embedding
max_features = 20000
maxlen = 100
embedding_size = 128
# Convolution
kernel_size = 5
filters = 64
pool_size = 4
# LSTM
lstm_output_size = 70
# Training
batch_size = 30
epochs = 2
# Data Preparation --------------------------------------------------------
# The x data includes integer sequences, each integer is a word
# The y data includes a set of integer labels (0 or 1)
# The num_words argument indicates that only the max_fetures most frequent
# words will be integerized. All other will be ignored.
# See help(dataset_imdb)
imdb <- dataset_imdb(num_words = max_features)
# Keras load all data into a list with the following structure:
str(imdb)
# Pad the sequences to the same length
# This will convert our dataset into a matrix: each line is a review
# and each column a word on the sequence
# We pad the sequences with 0s to the left
x_train <- imdb$train$x %>%
pad_sequences(maxlen = maxlen)
x_test <- imdb$test$x %>%
pad_sequences(maxlen = maxlen)
# Defining Model ------------------------------------------------------
model <- keras_model_sequential()
model %>%
layer_embedding(max_features, embedding_size, input_length = maxlen) %>%
layer_dropout(0.25) %>%
layer_conv_1d(
filters,
kernel_size,
padding = "valid",
activation = "relu",
strides = 1
) %>%
layer_max_pooling_1d(pool_size) %>%
layer_lstm(lstm_output_size) %>%
layer_dense(1) %>%
layer_activation("sigmoid")
model %>% compile(
loss = "binary_crossentropy",
optimizer = "adam",
metrics = "accuracy"
)
# Training ----------------------------------------------------------------
model %>% fit(
x_train, imdb$train$y,
batch_size = batch_size,
epochs = epochs,
validation_data = list(x_test, imdb$test$y)
)
# . ################################################################################
# 4 > imdb_bidirectional_lstm.R ####
############################################################################### #
#' Train a Bidirectional LSTM on the IMDB sentiment classification task.
#'
#' Output after 4 epochs on CPU: ~0.8146
#' Time per epoch on CPU (Core i7): ~150s.
library(keras)
# Define maximum number of input features
max_features <- 20000
# Cut texts after this number of words
# (among top max_features most common words)
maxlen <- 100
batch_size <- 32
# Load imdb dataset
cat('Loading data...\n')
imdb <- dataset_imdb(num_words = max_features)
# Define training and test sets
x_train <- imdb$train$x
y_train <- imdb$train$y
x_test <- imdb$test$x
y_test <- imdb$test$y
# Output lengths of testing and training sets
cat(length(x_train), 'train sequences\n')
cat(length(x_test), 'test sequences\n')
cat('Pad sequences (samples x time)\n')
# Pad training and test inputs
x_train <- pad_sequences(x_train, maxlen = maxlen)
x_test <- pad_sequences(x_test, maxlen = maxlen)
# Output dimensions of training and test inputs
cat('x_train shape:', dim(x_train), '\n')
cat('x_test shape:', dim(x_test), '\n')
# Initialize model
model <- keras_model_sequential()
model %>%
# Creates dense embedding layer; outputs 3D tensor
# with shape (batch_size, sequence_length, output_dim)
layer_embedding(input_dim = max_features,
output_dim = 128,
input_length = maxlen) %>%
bidirectional(layer_lstm(units = 64)) %>%
layer_dropout(rate = 0.5) %>%
layer_dense(units = 1, activation = 'sigmoid')
# Try using different optimizers and different optimizer configs
model %>% compile(
loss = 'binary_crossentropy',
optimizer = 'adam',
metrics = c('accuracy')
)
# Train model over four epochs
cat('Train...\n')
model %>% fit(
x_train, y_train,
batch_size = batch_size,
epochs = 4,
validation_data = list(x_test, y_test)
)
# . ################################################################################
# 5 > imdb_fasttext.R ####
############################################################################### #
#' This example demonstrates the use of fasttext for text classification
#'
#' Based on Joulin et al's paper:
#' "Bags of Tricks for Efficient Text Classification"
#' https://arxiv.org/abs/1607.01759
#'
#' Results on IMDB datasets with uni and bi-gram embeddings:
#' Uni-gram: 0.8813 test accuracy after 5 epochs. 8s/epoch on i7 CPU
#' Bi-gram : 0.9056 test accuracy after 5 epochs. 2s/epoch on GTx 980M GPU
#'
library(keras)
library(purrr)
# Function Definitions ----------------------------------------------------
create_ngram_set <- function(input_list, ngram_value = 2){
indices <- map(0:(length(input_list) - ngram_value), ~1:ngram_value + .x)
indices %>%
map_chr(~input_list[.x] %>% paste(collapse = "|")) %>%
unique()
}
add_ngram <- function(sequences, token_indice, ngram_range = 2){
ngrams <- map(
sequences,
create_ngram_set, ngram_value = ngram_range
)
seqs <- map2(sequences, ngrams, function(x, y){
tokens <- token_indice$token[token_indice$ngrams %in% y]
c(x, tokens)
})
seqs
}
# Parameters --------------------------------------------------------------
# ngram_range = 2 will add bi-grams features
ngram_range <- 2
max_features <- 20000
maxlen <- 400
batch_size <- 32
embedding_dims <- 50
epochs <- 5
# Data Preparation --------------------------------------------------------
# Load data
imdb_data <- dataset_imdb(num_words = max_features)
# Train sequences
print(length(imdb_data$train$x))
print(sprintf("Average train sequence length: %f", mean(map_int(imdb_data$train$x, length))))
# Test sequences
print(length(imdb_data$test$x))
print(sprintf("Average test sequence length: %f", mean(map_int(imdb_data$test$x, length))))
if(ngram_range > 1) {
# Create set of unique n-gram from the training set.
ngrams <- imdb_data$train$x %>%
map(create_ngram_set) %>%
unlist() %>%
unique()
# Dictionary mapping n-gram token to a unique integer
# Integer values are greater than max_features in order
# to avoid collision with existing features
token_indice <- data.frame(
ngrams = ngrams,
token = 1:length(ngrams) + (max_features),
stringsAsFactors = FALSE
)
# max_features is the highest integer that could be found in the dataset
max_features <- max(token_indice$token) + 1
# Augmenting x_train and x_test with n-grams features
imdb_data$train$x <- add_ngram(imdb_data$train$x, token_indice, ngram_range)
imdb_data$test$x <- add_ngram(imdb_data$test$x, token_indice, ngram_range)
}
# Pad sequences
imdb_data$train$x <- pad_sequences(imdb_data$train$x, maxlen = maxlen)
imdb_data$test$x <- pad_sequences(imdb_data$test$x, maxlen = maxlen)
# Model Definition --------------------------------------------------------
model <- keras_model_sequential()
model %>%
layer_embedding(
input_dim = max_features, output_dim = embedding_dims,
input_length = maxlen
) %>%
layer_global_average_pooling_1d() %>%
layer_dense(1, activation = "sigmoid")
model %>% compile(
loss = "binary_crossentropy",
optimizer = "adam",
metrics = "accuracy"
)
# Fitting -----------------------------------------------------------------
model %>% fit(
imdb_data$train$x, imdb_data$train$y,
batch_size = batch_size,
epochs = epochs,
validation_data = list(imdb_data$test$x, imdb_data$test$y)
)
# END. ####