# This R environment comes with all of CRAN preinstalled, as well as many other helpful packages
# The environment is defined by the kaggle/rstats docker image: https://github.com/kaggle/docker-rstats
# For example, here's several helpful packages to load in 

library(ggplot2) # Data visualization
library(readr) # CSV file I/O, e.g. the read_csv function
library(keras)
library("imager")


# Input data files are available in the "../input/" directory.

# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory

system("ls ../input")


cats<- list.files(path = "../input/train", pattern = "cat.+")
dogs<- list.files(path = "../input/train", pattern = "dog.+")

size = 150
channels = 3

train <- c(cats[1:1000],dogs[1:1000])
train <- sample(train)
evaluation <- c(cats[1001:1500],dogs[1001:1500])
evaluation <- sample(evaluation)

train_prep <- function(images, size, channels, path){

  count<- length(images)
  master_array <- array(NA, dim=c(count,size, size, channels))
  
  for (i in seq(length(images))) {
    ### load jpeg into imageR
    img <- image_load(path = paste(path, images[i], sep=""), target_size = c(size,size))
    img_arr <- image_to_array(img)
#     img <- load.image(paste("../input/train/", images[i], sep=""))
#     img <-  resize(img,size_x = size, size_y = size, size_c = channels)
#     img_arr <- array_reshape(img, c(1, size, size, channels))
#     img_arr <- image_to_array(img)
    img_arr <- array_reshape(img_arr, c(1, size, size, channels))
    master_array[i,,,] <- img_arr
  }
  return(master_array)
}

x_train <- train_prep(train, size, channels, "../input/train/")
x_evaluation <- train_prep(evaluation, size, channels, "../input/train/")
y_train <- as.numeric(grepl("dog.", train, ignore.case = TRUE))
y_evaluation <- as.numeric(grepl("dog.", evaluation, ignore.case = TRUE))

train_datagen <- image_data_generator(rescale = 1/255,
  rotation_range = 40,
  width_shift_range = 0.2,
  height_shift_range = 0.2,
  shear_range = 0.2,
  zoom_range = 0.2,
  horizontal_flip = TRUE)           

validation_datagen <- image_data_generator(rescale = 1/255)   

train_generator <- flow_images_from_data(
  x = x_train, 
  y = y_train,
  generator = train_datagen,                                                                                       
  batch_size = 20
)

validation_generator <- flow_images_from_data(
  x = x_evaluation, 
  y = y_evaluation,
  generator = validation_datagen,                                                                                       
  batch_size = 20
)

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_dropout(0.5)  %>% 
  layer_dense(units = 512, activation = "relu") %>%
  layer_dense(units = 1, activation = "sigmoid")
  
  
  
 model %>% compile(
  loss = "binary_crossentropy",
  optimizer = optimizer_rmsprop(lr = 1e-3),
  metrics = c("accuracy")
)


model %>% fit_generator(
  train_generator,
  steps_per_epoch = 100,
  epochs = 22,
  validation_data = validation_generator,
  validation_steps = 50
)

x_test <- train_prep(list.files(path = "../input/test"), size, channels, "../input/test/")
print(dim(x_test))

id <- list.files(path = "../input/test")
id<- gsub("dog.|cat.|.jpg", "", id)
print(head(id))


test_generator <- flow_images_from_data(
  x = x_test, 
#   y = y_evaluation,
  generator = validation_datagen,                                                                                       
  batch_size = 100
)


print("Predict")
predictions <- model %>% predict_generator(test_generator, steps = ceiling(length(id)/100), verbose = 1)
# predictions <- model %>% predict(x_test)
submission = data.frame(id = as.numeric(id), label = predictions)
write.csv(submission, "submission.csv", row.names=FALSE)