Advertisement
R3v4n

SVM classifier in R

May 12th, 2013
377
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 1.32 KB | None | 0 0
  1. library('quadprog')
  2.  
  3. # load the dataset and shuffles it
  4. datafilename <- "data/iris.data"
  5. dataset      <- read.table(datafilename,header=FALSE,sep=",")
  6.  
  7. dataset <- data.frame(dataset[,1:(length(dataset)-1)],unclass(dataset[,length(dataset)]))
  8.  
  9. #convert to two class classification problem
  10. #keep the selected class and merge all the others to a single one
  11. selectedClass <- 1
  12. dataset[dataset[,length(dataset)]==selectedClass,][length(dataset)]  <- -1
  13. dataset[dataset[,length(dataset)]!=-1,][length(dataset)]  <- 1
  14.  
  15. #attributes to use for training/testing and plotting
  16. xIndex <- 3
  17. yIndex <- 4
  18.  
  19. #select only two attributes to use for learning,
  20. #so that the results can be easily visualized
  21. train.data <- data.frame(dataset[,xIndex],dataset[,yIndex],dataset[,dim(dataset)[2]])
  22.  
  23. # Z is a diagonal matrix created from the class column vector z
  24. Z <- as.matrix(diag(dataset[,dim(dataset)[2]]))
  25. z <- diag(Z)
  26.  
  27. # matrix Y = (1, Y_x)
  28. ones <- rep(1,dim(dataset)[1])
  29. Y_x  <- as.matrix(train.data[,-dim(train.data)[2]])
  30. Y    <- cbind(ones,Y_x)
  31.  
  32. # preparation of the variables for quadprog library
  33. D <- Z %*% Y_x %*% t(Y_x) %*% Z
  34. d <- ones
  35.  
  36. I  <- diag(ones) # Identity matrix
  37. At <- rbind(I,t(z))
  38. A  <- t(At)
  39.  
  40. # solve the optimization problem and get the alpha values
  41. alpha <- solve.QP(D,d,A, factorized=TRUE)$solution
  42.  
  43. print(alpha)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement