Advertisement
Guest User

SVM

a guest
Jan 31st, 2015
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 1.52 KB | None | 0 0
  1. # reading data and loading libraries
  2. setwd("~/R/wd/R_digits")
  3. data_all=read.csv("train.csv")
  4. library(parallel)
  5. library(e1071)
  6. library(caret)
  7. library(ROCR)
  8.  
  9.  
  10.  
  11. # pre-processing
  12.  
  13.   # binary : 8 --> TRUE, others --> FALSE
  14.   labels <- data_all[,1] == 8
  15.  
  16.   ## multiclass
  17.   # labels <- as.factor(data_all[,1])
  18.  
  19.   # data.frame
  20.   data_8 <- cbind(labels,data_all[,-1])
  21.  
  22.   # quantity (%) of observations to use
  23.   q_data <- 0.1
  24.   nb_pics <- nrow(data_8)
  25.   idx <- sample(1:nb_pics, floor(nb_pics*q_data), replace = FALSE)
  26.   data_8 <- data_8[idx,]
  27.  
  28.   #test/train full index
  29.   nb_pics <- nrow(data_8)
  30.   idx <- sample(1:nb_pics, floor(nb_pics*0.8), replace = FALSE)
  31.  
  32.   # test/train full sets
  33.   training <- data_8[idx,]
  34.   testing <- data_8[-idx,]
  35.  
  36.   # deleting empty cols
  37.   del_zeros <- function(matrice) {which(apply(matrice,2,max) !=0)}
  38.   nozeros <- del_zeros(training)
  39.   training <- training[,nozeros]
  40.  
  41.  
  42.  
  43. # svm
  44.  
  45.   # starting time
  46.   t <- Sys.time()
  47.  
  48.   model <- svm(labels ~ ., data = training, probability = TRUE, type = "C-classification",cost = 2, gamma = 1.4 * (1/(dim(training)[2]-1)))
  49.  
  50.   # total time
  51.   t <- Sys.time() - t
  52.   t
  53.  
  54.  
  55. # analysis
  56.  
  57.   # predict
  58.   pred <- predict(model, testing[,-1], probability = TRUE)
  59.  
  60.   # confusion matrix
  61.     CM <- confusionMatrix(pred, testing[,1])
  62.     acc <- CM$overall[1]  
  63.     conf <- CM$table
  64.     conf
  65.     acc
  66.  
  67.   # ROC curve using ROCR
  68.   plot(col = "red", performance(prediction(attr(pred, "probabilities")[,2], testing[,1]), 'tpr', 'fpr'))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement