{"cells":[{"metadata":{"_uuid":"051d70d956493feee0c6d64651c6a088724dca2a","_execution_state":"idle","trusted":true},"cell_type":"code","source":"# This R environment comes with many helpful analytics packages installed\n# It is defined by the kaggle/rstats Docker image: https://github.com/kaggle/docker-rstats\n# For example, here's a helpful package to load\n\nlibrary(tidyverse) # metapackage of all tidyverse packages\nlibrary(keras)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nlist.files(path = \"../input\")\nlist.files(path = \"../input/dogs-cats-images\")\n\ncats <- list.files(path = \"../input/dogs-cats-images/dataset/training_set/cats\", pattern = \".+\")\ndogs <- list.files(path = \"../input/dogs-cats-images/dataset/training_set/dogs\", pattern = \".+\")\n\ntest_cats <- list.files(path = \"../input/dogs-cats-images/dataset/test_set/cats\", pattern = \".+\")\ntest_dogs <- list.files(path = \"../input/dogs-cats-images/dataset/test_set/dogs\", pattern = \".+\")\n\nnCats <- length(cats)\nnDogs <- length(dogs)\nN <- nCats + nDogs\n\nnTestCats <- length(test_cats)\nnTestDogs <- length(test_dogs)\nNtest <- nTestCats + nTestDogs\n\nnCats\nnDogs\nnTestCats\nnTestDogs\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Fonction qui donne le vecteur de caractéristiques d'une image,\n# calculé par un modèle donné.\nimage_to_features <- function(img_path, target_size, model) {\n  # charge l'image en la mettant à la bonne taille\n  img <- image_load(img_path, target_size = target_size)\n  # transforme l'image en tableau utilisable par le modèle\n  x <- image_to_array(img)\n  x <- array_reshape(x, c(1, dim(x)))\n  # preprocessing : images -> tenseur\n  x <- imagenet_preprocess_input(x)\n  # donne les données au modèle et récupère les caractéristiques\n  as.numeric(model %>% predict(x))\n}\n\n# Fonction qui construit une matrice Nx2048 remplie\n# des caractéristiques calculées par le modèle donné.\n# target_size est la taille des images souhaitée en entrée du modèle, elle dépend du modèle (voir doc keras)\nmake_features <- function(set, cats, dogs, target_size, model) {\n  total <- length(cats) + length(dogs)\n  feat <- matrix(NA, nrow = total, ncol = 2048)\n  j <- 0\n  print(paste(\"Processing\", length(cats), \"cats and\", length(dogs), \"dogs\"))\n  # Le traitement prend du temps, on affiche une barre de progression.\n  # Nous avons découvert ce module avec sur StackOverflow :\n  # https://stackoverflow.com/questions/26919787/r-text-progress-bar-in-for-loop\n  pbar <- txtProgressBar(min=0, max=total, initial=0, style=3)\n  for (i in cats) {\n    img_path <- paste(\"../input/dogs-cats-images/dataset/\", set, \"/cats/\", i, sep = \"\")\n    f <- image_to_features(img_path, target_size, model)\n    j <- j + 1\n    feat[j,] <- f\n    setTxtProgressBar(pbar, j)\n  }\n  for (i in dogs) {\n    img_path <- paste(\"../input/dogs-cats-images/dataset/\", set, \"/dogs/\", i, sep = \"\")\n    f <- image_to_features(img_path, target_size, model)\n    j <- j + 1\n    feat[j,] <- f\n    setTxtProgressBar(pbar, j)\n  }\n  cat(\"\\n\") # saute une ligne pour terminer la barre de progression\n  feat\n}\n\nmodel_rn50 <- application_resnet50(weights = 'imagenet',\n                                   include_top = FALSE,\n                                   pooling = 'max')\nfeatures_train <- make_features(\"training_set\", cats, dogs, c(224,224), model_rn50)\nfeatures_test <- make_features(\"test_set\", test_cats, test_dogs, c(224,224), model_rn50)","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":false,"trusted":true},"cell_type":"code","source":"# Lit une image de chien ou de chat et la convertit au format vectoriel.\n# load_cat_dog <- function(category, image_name) {\n#   dimension <- c(64, 64)\n#   img_path <- paste(\"../input/dogs-cats-images/dataset/test_set/\", category, \"/\", image_name, sep =\"\")\n#   img <- image_load(img_path, grayscale = FALSE, target_size = dimension)\n#   x <- image_to_array(img)\n\n#   # reshape\n#   # on somme le RGB pour avoir du noir et blanc\n#   array_reshape(x[,,1]+x[,,2]+x[,,3], dim=c(1,4096))\n# }\n\n# x_test <- matrix(NA, nrow = Ntest, ncol = 4096)\n# y_test <- c(rep(0, nTestCats), rep(1, nTestDogs))\n# j <- 0\n# for (im in test_cats) {\n#   j <- j + 1\n#   x_test[j,] <- load_cat_dog(\"cats\", im)\n# }\n# for (im in test_dogs) {\n#   j <- j + 1\n#   x_test[j,] <- load_cat_dog(\"dogs\", im)\n# }","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_test <- features_test\ny_test <- c(rep(0, nTestCats), rep(1, nTestDogs))\n\nx_train <- features_train\ny_train <- c(rep(0, nCats), rep(1, nDogs))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"m <- keras_model_sequential()\nm %>% layer_dense(units = 256, activation = 'relu', input_shape = c(2048)) %>%\n    layer_dropout(rate = 0.5) %>%\n    layer_dense(units = 1, activation = 'sigmoid')\nm %>% compile(loss='binary_crossentropy', optimizer=optimizer_adam(lr=0.001), metrics=c('accuracy'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history <- m %>% fit(x_train, y_train, epochs=30, batch_size=256, validation_data=list(x_test,y_test),verbose=TRUE,shuffle=TRUE)\nplot(history)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"m %>% evaluate(x_train, y_train)\nm %>% evaluate(x_test, y_test)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"On obtient plus de 98% de précision sur ces données."}],"metadata":{"kernelspec":{"name":"ir","display_name":"R","language":"R"},"language_info":{"name":"R","codemirror_mode":"r","pygments_lexer":"r","mimetype":"text/x-r-source","file_extension":".r","version":"3.6.3"}},"nbformat":4,"nbformat_minor":4}