L1 and L2 regularization using keras pack in R? - r

library(keras)
build_model <- function() {
model <- keras_model_sequential() %>%
layer_dense(units = 64, activation = "relu",
input_shape = dim(train_data)[[2]]) %>%
regularizer_l1_l2(l1 = 0.01, l2 = 0.01) %>%
layer_dense(units = 64, activation = "relu") %>%
regularizer_l1_l2(l1 = 0.01, l2 = 0.01) %>%
layer_dense(units = 1)
model %>% compile(
optimizer = "rmsprop",
loss = "mse",
metrics = c("mae")
)
}
model <- build_model()
I am trying to apply L1 and L2 regularization using keras in R. However, I am getting an error:
Error in regularizer_l1_l2(., l1 = 0.01, l2 = 0.01) : unused argument (.)
The syntax for regularization that I have used is same as mentioned in the link.
https://keras.rstudio.com/reference/regularizer_l1.html
Can anyone tell me what am I doing wrong?

This would be the correct syntax for L1 and L2 regularization using keras in R:
library(keras)
build_model <- function() {
model <- keras_model_sequential() %>%
layer_dense(units = 64,
activation = "relu",
kernel_regularizer = regularizer_l1_l2(l1 = 0.01, l2 = 0.01),
input_shape = dim(train_data)[[2]]) %>%
layer_dense(units = 64,
activation = "relu",
kernel_regularizer = regularizer_l1_l2(l1 = 0.01, l2 = 0.01)) %>%
layer_dense(units = 1)
model %>% compile(
optimizer = "rmsprop",
loss = "mse",
metrics = c("mae")
)
}
reproducible example:
library(keras)
mnist <- dataset_mnist()
train_images <- mnist$train$x
train_labels <- mnist$train$y
test_images <- mnist$test$x
test_labels <- mnist$test$y
train_images <- array_reshape(train_images, c(60000, 28*28))
train_images <- train_images / 255
test_images <- array_reshape(test_images, c(10000, 28*28))
test_images <- test_images / 255
train_labels <- to_categorical(train_labels)
test_labels <- to_categorical(test_labels)
network <- keras_model_sequential() %>%
layer_dense(units = 512,
activation = "relu",
kernel_regularizer = regularizer_l1_l2(l1 = 0.001, l2 = 0.001),
input_shape = c(28 * 28)) %>%
layer_dense(units = 10, activation = "softmax")
network %>% compile(
optimizer = "rmsprop",
loss = "categorical_crossentropy",
metrics = c("accuracy")
)
network %>% fit(train_images,
train_labels,
epochs = 5,
batch_size = 128)
metrics <- network %>% evaluate(test_images, test_labels)
> metrics
#output
$`loss`
[1] 0.6863746
$acc
[1] 0.921

Related

Parameter adjustment using kerastuneR packet deep neural network

What is the cause of the following code error?
library(magrittr)
x_data <- matrix(data = runif(500,0,1),nrow = 50,ncol = 5)
y_data <- ifelse(runif(50,0,1) > 0.6, 1L,0L) %>% as.matrix()
x_data2 <- matrix(data = runif(500,0,1),nrow = 50,ncol = 5)
y_data2 <- ifelse(runif(50,0,1) > 0.6, 1L,0L) %>% as.matrix()
library(keras)
library(tensorflow)
library(kerastuneR)
build_model = function(hp) {
model = keras_model_sequential()
model %>% layer_dense(units = hp$Int('units',
min_value = 32,
max_value = 512,
step= 32),input_shape = ncol(x_data),
activation = 'relu') %>%
layer_dense(units = 1, activation = 'softmax') %>%
compile(
optimizer = tf$keras$optimizers$Adam(
hp$Choice('learning_rate',
values=c(1e-2, 1e-3, 1e-4))),
loss = 'binary_crossentropy',
metrics = 'accuracy')
return(model)
}
tuner = RandomSearch(
build_model,
objective = 'val_accuracy',
max_trials = 5,
executions_per_trial = 3,
directory = 'my_dir',
project_name = 'helloworld')
tuner %>% search_summary()
tuner %>% fit_tuner(x_data,y_data,
epochs = 5,
validation_data = list(x_data2,y_data2))
result = kerastuneR::plot_tuner(tuner)
best_5_models = tuner %>% get_best_models(5)
best_5_models[[1]] %>% plot_keras_model()
Error in py_call_impl(callable, dots$args, dots$keywords) :
ValueError: Objective value missing in metrics reported to the Oracle, expected: ['val_accuracy'], found: dict_keys(['loss', 'acc', 'val_loss', 'val_acc'])

R keras says array doesnt have the right dimensions for a conv_2d, but it drops a value from the array that was correct

When making a conv neral network keras takes the imput_shape of c(28, 28, 1), but when I run it to be trained it then tells me the input it got was (6000, 28, 28). I understand keras inputs the data size it's self, but why it is dropping the one, then causing it to brake?
Problem line (I think):
model %>%
layer_conv_2d(filters = 32, kernel_size = c(3, 3), padding = 'same', input_shape = c(28, 28, 1)) %>%
Error:
Error in py_call_impl(callable, dots$args, dots$keywords) :
ValueError: Error when checking input: expected conv2d_5_input to have 4 dimensions, but got array with shape (60000, 28, 28)
Code:
library(keras)
install_keras(tensorflow = "gpu")
mnist <- dataset_mnist()
x_train <- mnist$train$x
y_train <- mnist$train$y
x_test <- mnist$test$x
y_test <- mnist$test$y
# # reshape
#x_train <- array_reshape(x_train, c(nrow(x_train), 784))
#x_test <- array_reshape(x_test, c(nrow(x_test), 784))
# # rescale
# x_train <- x_train / 255
# x_test <- x_test / 255
y_train <- to_categorical(y_train, 10)
y_test <- to_categorical(y_test, 10)
model <- keras_model_sequential()
model %>%
layer_conv_2d(filters = 32, kernel_size = c(3, 3), padding = 'same', input_shape = c(28, 28, 1)) %>%
layer_activation('relu') %>%
# layer_max_pooling_2d(pool_size=c(2, 2), strides=c(2, 2)) %>%
layer_conv_2d(filters = 16, kernel_size = c(2, 2), dilation_rate = 1, activation = 'softplus', padding = 'same') %>%
layer_max_pooling_2d(pool_size=c(2, 2)) %>%
layer_flatten() %>%
layer_dense(1000, activation = 'relu') %>%
layer_dropout(0.5) %>%
layer_dense(10, activation = 'softmax')
# Stock test model functions
# layer_dense(units = 256, activation = 'relu', input_shape = c(784)) %>%
# layer_dropout(rate = 0.4) %>%
# layer_dense(units = 128, activation = 'relu') %>%
# layer_dropout(rate = 0.3) %>%
# layer_dense(units = 10, activation = 'softmax') %>%
summary(model)
model %>% compile(
loss = 'categorical_crossentropy',
optimizer = optimizer_rmsprop(lr = 0.0001, decay = 1e-6),
metrics = c('accuracy')
)
history <- model %>% fit(
x_train, y_train,
epochs = 10
)
plot(history)
model %>% evaluate(x_test, y_test)
model %>% predict_classes(x_test)
From the documentation of layer_conv_2d :
input_shape :- Dimensionality of the input (integer) not including the samples axis. This argument is required when using this layer as the first layer in a model.
So the input shape (28, 28, 1) means 28 rows by 28 columns by 1 channel. There is only one channel in this dataset since the images are black and white. RGB images would have 3 channels.
You are getting this error because the input shape is (60000, 28, 28) that is the 4th dimension (channel) is missing. You can fix this by doing this :-
x_train <- array_reshape(x_train, dim = c(n_train, 28, 28, 1))
x_test <- array_reshape(x_test, dim = c(n_test, 28, 28, 1))
Full code :-
library(keras)
mnist <- dataset_mnist()
x_train <- mnist$train$x
y_train <- mnist$train$y
x_test <- mnist$test$x
y_test <- mnist$test$y
n_train <- dim(x_train)[1]
n_test <- dim(x_test)[1]
x_train <- array_reshape(x_train, dim = c(n_train, 28, 28, 1))
x_test <- array_reshape(x_test, dim = c(n_test, 28, 28, 1))
y_train <- to_categorical(y_train, 10)
y_test <- to_categorical(y_test, 10)
model <- keras_model_sequential()
model %>%
layer_conv_2d(filters = 32, kernel_size = c(3, 3), padding = 'same', input_shape = c(28, 28, 1)) %>%
layer_activation('relu') %>%
# layer_max_pooling_2d(pool_size=c(2, 2), strides=c(2, 2)) %>%
layer_conv_2d(filters = 16, kernel_size = c(2, 2),
dilation_rate = c(1,1), activation = 'softplus', padding = 'same') %>%
layer_max_pooling_2d(pool_size=c(2, 2)) %>%
layer_flatten() %>%
layer_dense(1000, activation = 'relu') %>%
layer_dropout(0.5) %>%
layer_dense(10, activation = 'softmax')
summary(model)
model %>% compile(
loss = 'categorical_crossentropy',
optimizer = optimizer_rmsprop(lr = 0.0001, decay = 1e-6),
metrics = c('accuracy')
)
history <- model %>% fit(
x_train, y_train,
epochs = 1
)
plot(history)
model %>% evaluate(x_test, y_test)
model %>% predict_classes(x_test)

Layer conv2d_1 was called with an input that isn't a symbolic tensor / Keras / Cloudml / R

I am using the R interface to Keras version 2.14, and version 1.5 for Tensorflow.
When I run the following code at my local machine, it runs without any issues. When I run it on cloudml, I get the error message given below.
I have checked the forums, but with my limited knowledge of python, unable to translate the solutions given so far to R.
Thank you for your help.
Error message:
"Error: ValueError: Layer conv2d_1 was called with an input that isn't a symbolic tensor. Received type: . Full input: []. All inputs to the layer should be tensors. Detailed traceback: File "/usr/local/lib/python2.7/dist-packages/keras/engine/base_layer.py", line 414, in call self.assert_input_compatibility(inputs) File "/usr/local/lib/python2.7/dist-packages/keras/engine/base_layer.py", line 285, in assert_input_compatibility str(inputs) + '. All inputs to the layer"
Here is the complete code:
original_dataset_dir <- "./train"
base_dir <- "./cats_and_dogs_small"
train_dir <- file.path(base_dir, "train")
validation_dir <- file.path(base_dir, "validation")
test_dir <- file.path(base_dir, "test")
train_cats_dir <- file.path(train_dir, "cats")
train_dogs_dir <- file.path(train_dir, "dogs")
validation_cats_dir <- file.path(validation_dir, "cats")
validation_dogs_dir <- file.path(validation_dir, "dogs")
test_cats_dir <- file.path(test_dir, "cats")
test_dogs_dir <- file.path(test_dir, "dogs")
cat("total training cat images:", length(list.files(train_cats_dir)), "\n")
cat("total training dog images:", length(list.files(train_dogs_dir)), "\n")
cat("total validation cat images:", length(list.files(validation_cats_dir)), "\n")
cat("total validation dog images:", length(list.files(validation_dogs_dir)), "\n")
cat("total test cat images:", length(list.files(test_cats_dir)), "\n")
cat("total test dog images:", length(list.files(test_dogs_dir)), "\n")
list.files(test_dogs_dir)
# now create the model
library(keras)
model <- keras_model_sequential() %>%
layer_conv_2d(filters = 32, kernel_size = c(3, 3), activation = "relu",
input_shape = c(150, 150, 3)) %>%
layer_max_pooling_2d(pool_size = c(2, 2)) %>%
layer_conv_2d(filters = 64, kernel_size = c(3, 3), activation = "relu") %>%
layer_max_pooling_2d(pool_size = c(2, 2)) %>%
layer_conv_2d(filters = 128, kernel_size = c(3, 3), activation = "relu") %>%
layer_max_pooling_2d(pool_size = c(2, 2)) %>%
layer_conv_2d(filters = 128, kernel_size = c(3, 3), activation = "relu") %>%
layer_max_pooling_2d(pool_size = c(2, 2)) %>%
layer_flatten() %>%
layer_dense(units = 512, activation = "relu") %>%
layer_dense(units = 1, activation = "sigmoid")
# look at the model
summary(model)
model %>% compile(
loss = "binary_crossentropy",
optimizer = optimizer_rmsprop(lr = 1e-4),
metrics = c("acc")
)
# All images will be rescaled by 1/255
train_datagen <- image_data_generator(rescale = 1/255)
validation_datagen <- image_data_generator(rescale = 1/255)
train_generator <- flow_images_from_directory(
# This is the target directory
train_dir,
# This is the data generator
train_datagen,
# All images will be resized to 150x150
target_size = c(150, 150),
batch_size = 20,
# Since we use binary_crossentropy loss, we need binary labels
class_mode = "binary"
)
validation_generator <- flow_images_from_directory(
validation_dir,
validation_datagen,
target_size = c(150, 150),
batch_size = 20,
class_mode = "binary"
)
batch <- generator_next(train_generator)
str(batch)
history <- model %>% fit_generator(
train_generator,
steps_per_epoch = 100,
epochs = 5,
validation_data = validation_generator,
validation_steps = 50
)
model %>% save_model_hdf5("cats_and_dogs_small_1.h5")
plot(history)
cml1.R
library(cloudml)
#gcloud_init()
cloudml_train("cats-and-dogs.R")

R-Keras - How come val_loss is not plotting

My first time playing with Keras. I tried to run the model and see the loss and accuracy. For some reason, its not plotting the loss for val_loss.
My code:
model <- keras_model_sequential() %>%
layer_dense(units = 256, activation = "relu", input_shape = dim(train.X)[[2]]) %>%
layer_dropout(rate = 0.4) %>%
layer_dense(units = 128, activation = "relu") %>%
layer_dropout(rate = 0.3) %>%
layer_dense(units = 1, activation = "sigmoid")
model %>% compile (
optimizer = "rmsprop", #configuring optimizer = optimizer_rmsprop(lr = 0.001)
loss = "binary_crossentropy", #custom loss -> loss_binary_crossentropy
metrics = c("accuracy") #metric_binary_accuracy
)
history <- model %>% fit(
train.X,
train.Y,
epochs = 100,
batch_size = 64,
validation_data = list(x_val, y_val)
)
My results:
I would really appreciate if someone can explain to me why the val_loss function is not plotting.

Check whether the R package keras has compiled a model

When I run the following R script I get summary information about a keras model and its added layers, but no confirmation that the model has been compiled. How do I check whether the compile step has been completed?
library(keras)
model <- keras_model_sequential()
model %>%
layer_dense(units = 64, activation = 'relu', input_shape = c(20)) %>%
layer_dropout(rate = 0.5) %>%
layer_dense(units = 64, activation = 'relu') %>%
layer_dropout(rate = 0.5) %>%
layer_dense(units = 10, activation = 'softmax') %>%
compile(
loss = 'categorical_crossentropy',
optimizer = optimizer_sgd(lr = 0.01, decay = 1e-6,
momentum = 0.9, nesterov = TRUE),
metrics = c('accuracy')
)
summary(model)
Check the built flag ?
library(keras)
model <- keras_model_sequential()
model$built # False
model %>%
layer_dense(units = 64, activation = 'relu', input_shape = c(20)) %>%
layer_dropout(rate = 0.5) %>%
layer_dense(units = 64, activation = 'relu') %>%
layer_dropout(rate = 0.5) %>%
layer_activation(activation = 'relu') %>%
layer_dense(units = 10) %>%
layer_activation(activation = 'softmax')
model$built # False
model %>%
compile(
loss = 'categorical_crossentropy',
optimizer = optimizer_sgd(lr = 0.01, decay = 1e-6,
momentum = 0.9, nesterov = TRUE),
metrics = c('accuracy')
)
model$built # True

Resources