Guest User

Untitled

a guest
May 21st, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. library(png)
  2. library(colorspace)
  3. library(abind)
  4. library(reticulate)
  5. library(keras)
  6.  
  7. setwd("~/E-books/Coding/Machine Learning with R/Neural Networks/four-shapes")
  8.  
  9. # Here I create a list of links to retrieve each image
  10. files <- list.files(pattern = ".png$", recursive = TRUE)
  11. filePathFunction <- function(x){
  12. a <- matrix(nrow=length(x))
  13. for(i in 1:length(x)){
  14. conc <- c("~/E-books/Coding/Machine Learning with R/Neural Networks/four-shapes",x[i])
  15. a[i] <- paste(conc, collapse="/")
  16. }
  17. return(a)
  18. }
  19. filePaths <- filePathFunction(files)
  20. image(readPNG(filePaths[1]), useRaster=TRUE, axes=FALSE)
  21.  
  22.  
  23. #circle is 0
  24. #square is 1
  25. #star is 2
  26. #triangle is 3
  27.  
  28. circle <- rep(0,3720)
  29. circle_array <- array(circle, dim=c(3720,1))
  30. square <- rep(1,3765)
  31. square_array <- array(square, dim=c(3765,1))
  32. star <- rep(2,3765)
  33. star_array <- array(star, dim=c(3765,1))
  34. triangle <- rep(3,3720)
  35. triangle_array <- array(triangle, dim=c(3720,1))
  36. labels <- rbind(circle_array,square_array,star_array, triangle_array)
  37.  
  38.  
  39.  
  40. set.seed(101)
  41. ind <- sample(nrow(filePaths),round(0.75*nrow(filePaths)),replace=F)
  42. train_data <- filePaths[ind,]
  43. test_data <- filePaths[-ind,]
  44.  
  45. train_labels <- labels[ind,]
  46. test_labels <- labels[-ind,]
  47.  
  48. train_labels <- to_categorical(train_labels)
  49. test_labels <- to_categorical(test_labels)
  50.  
  51. #trainPathArray and testPathArray reshape each pixel matrix into a 11228x200*200 array and
  52. #3742x200*200 array matrix
  53.  
  54. trainPathArray <- matrix(ncol=200*200, nrow= length(train_data))
  55. for(i in 1:length(train_data)){
  56. trainPathArray[i,] <- array_reshape(readPNG(train_data[i]), dim= c(1,200*200))
  57. }
  58. testPathArray <- matrix(ncol=200*200, nrow= length(test_data))
  59. for(i in 1:length(test_data)){
  60. testPathArray[i,] <- array_reshape(readPNG(test_data[i]), dim= c(1,200*200))
  61. }
  62.  
  63.  
  64. network <- keras_model_sequential() %>%
  65. layer_dense(units = 1000, activation = "relu", input_shape = c(200*200)) %>%
  66. layer_dense(units = 1000, activation = "relu") %>%
  67. layer_dense(units = 4, activation = "softmax")
  68.  
  69. network %>% compile(
  70. optimizer = "rmsprop",
  71. loss = "categorical_crossentropy",
  72. metrics = c("accuracy")
  73. )
  74. network %>% fit(trainPathArray, train_labels, epochs = 5, batch_size = 12smilie
  75. metrics <- network %>% evaluate(testPathArray, test_labels)
Add Comment
Please, Sign In to add comment