Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- library(png)
- library(colorspace)
- library(abind)
- library(reticulate)
- library(keras)
- setwd("~/E-books/Coding/Machine Learning with R/Neural Networks/four-shapes")
- # Here I create a list of links to retrieve each image
- files <- list.files(pattern = ".png$", recursive = TRUE)
- filePathFunction <- function(x){
- a <- matrix(nrow=length(x))
- for(i in 1:length(x)){
- conc <- c("~/E-books/Coding/Machine Learning with R/Neural Networks/four-shapes",x[i])
- a[i] <- paste(conc, collapse="/")
- }
- return(a)
- }
- filePaths <- filePathFunction(files)
- image(readPNG(filePaths[1]), useRaster=TRUE, axes=FALSE)
- #circle is 0
- #square is 1
- #star is 2
- #triangle is 3
- circle <- rep(0,3720)
- circle_array <- array(circle, dim=c(3720,1))
- square <- rep(1,3765)
- square_array <- array(square, dim=c(3765,1))
- star <- rep(2,3765)
- star_array <- array(star, dim=c(3765,1))
- triangle <- rep(3,3720)
- triangle_array <- array(triangle, dim=c(3720,1))
- labels <- rbind(circle_array,square_array,star_array, triangle_array)
- set.seed(101)
- ind <- sample(nrow(filePaths),round(0.75*nrow(filePaths)),replace=F)
- train_data <- filePaths[ind,]
- test_data <- filePaths[-ind,]
- train_labels <- labels[ind,]
- test_labels <- labels[-ind,]
- train_labels <- to_categorical(train_labels)
- test_labels <- to_categorical(test_labels)
- #trainPathArray and testPathArray reshape each pixel matrix into a 11228x200*200 array and
- #3742x200*200 array matrix
- trainPathArray <- matrix(ncol=200*200, nrow= length(train_data))
- for(i in 1:length(train_data)){
- trainPathArray[i,] <- array_reshape(readPNG(train_data[i]), dim= c(1,200*200))
- }
- testPathArray <- matrix(ncol=200*200, nrow= length(test_data))
- for(i in 1:length(test_data)){
- testPathArray[i,] <- array_reshape(readPNG(test_data[i]), dim= c(1,200*200))
- }
- network <- keras_model_sequential() %>%
- layer_dense(units = 1000, activation = "relu", input_shape = c(200*200)) %>%
- layer_dense(units = 1000, activation = "relu") %>%
- layer_dense(units = 4, activation = "softmax")
- network %>% compile(
- optimizer = "rmsprop",
- loss = "categorical_crossentropy",
- metrics = c("accuracy")
- )
- network %>% fit(trainPathArray, train_labels, epochs = 5, batch_size = 12smilie
- metrics <- network %>% evaluate(testPathArray, test_labels)
Add Comment
Please, Sign In to add comment