Advertisement
Guest User

Untitled

a guest
Oct 20th, 2019
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 1.91 KB | None | 0 0
  1. library(stats19)
  2. library(tidyverse)
  3. library(MASS)
  4. library(pixmap)
  5.  
  6. calibra <- function(dataset = grep("normal|happy|sad|sleepy|surprised|wink",
  7.                                    list.files("data_atividade2/"), value=TRUE)) {
  8.   set.seed(202227)
  9.   data <- matrix(ncol = 20691, nrow = 90)
  10.   c <- 1
  11.   for(i in dataset){#monta matriz do poligono geral de um rosto das pessoas
  12.     path <- paste("data_atividade2", i, sep="/")
  13.     img <- read.pnm(file=path, cellres=1)
  14.     vetor_rosto <- as.numeric(img@grey[40:210, 40:160])
  15.     data[c,] <- vetor_rosto
  16.     c <- c + 1
  17.   }
  18.   data <- as.data.frame(data)
  19.   data$resp <- as.factor(rep(c("happy", "normal", "sad", "sleepy", "surprised","wink"), 15))
  20.  
  21.   id <- c(1:nrow(data))
  22.   id_train <- sample(id, 0.8*nrow(data))
  23.   train <- data %>% slice(id_train)
  24.   test <- data %>% slice(-id_train)
  25.  
  26.   pc <- prcomp(train[-20692], scale=TRUE, retx=FALSE)
  27.   train.pc <- as.data.frame(predict(pc, train))
  28.   test.pc <- as.data.frame(predict(pc, test))
  29.   var.pc.prop <- (pc$sdev^2)/sum(pc$sdev^2)
  30.   cum.var <- cumsum(var.pc.prop)
  31.   ncomp <- which.max(cum.var > 0.95)
  32.  
  33.   train.pc <- train.pc[1:ncomp]
  34.   train.pc$resp <- train$resp
  35.   test.pc <- test.pc[1:ncomp]
  36.   test.pc$resp <- test$resp
  37.   lda.fit <- lda(resp ~ ., data = train.pc)
  38.  
  39.   final <- list(lda.fit, pc, ncomp)
  40.   return(final)
  41. }
  42.  
  43. prediz <- function(modelo=calibra()[[1]], teste){
  44.   img <- matrix(ncol=20691)
  45.   vetor_rosto <- as.numeric(teste[40:210, 40:160])
  46.   img <- rbind(img, vetor_rosto) %>% as.data.frame()
  47.   img <- img[2,]
  48.   teste_proc <- as.data.frame(predict(calibra()[[2]], img))
  49.   teste_proc <- teste_proc[1:calibra()[[3]]]
  50.   teste_pred <- predict(modelo, teste_proc)
  51.   return(teste_pred$class)
  52.  
  53.  
  54.  
  55.  
  56.  
  57.   #teste.pc <- as.data.frame(predict(calibra()[[2]], teste))
  58.   #teste.pc <- teste.pc[1:calibra()[[3]]]
  59.   #teste.pred <- predict(modelo, teste.pc)
  60.   #return(teste.pred$class)
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement