Advertisement
Guest User

Untitled

a guest
Nov 8th, 2013
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 1.62 KB | None | 0 0
  1. library(e1071)
  2.  
  3. #
  4. # Given a classifier (w, w0), visualizes the corresponding
  5. # linear functional using a filled contour plot.
  6. #
  7. plot.classifier = function(w, w0=0) {
  8.   x1s = seq(-5, 5, 0.2)
  9.   x2s = seq(-1, 1, 0.2)
  10.   fvals = outer(x1s, x2s,
  11.                 Vectorize(function(x1, x2) { x1*w[1] + x2*w[2] + w0 }))
  12.   image(x1s, x2s, fvals,
  13.         col=terrain.colors(40), breaks=-20:20, asp=1,
  14.         xlab=expression(X[1]), ylab=expression(X[2]))
  15.   contour(x1s, x2s, fvals, levels=-40:40, add=T)
  16.   arrows(0, 0, w[1], w[2], length=0.2, lwd=4)
  17.   if (w[2] == 0) abline(v = -w0/w[1], lwd=4)
  18.   else abline(-w0/w[2], -w[1]/w[2], lwd=4)
  19. }
  20.  
  21.  
  22. #
  23. # Plots the data created by the load.data function.
  24. # When add=T, the data is added to the current plot
  25. # cex specifies the size of the points.
  26. # Example:
  27. #   d = load.data()
  28. #   plot.classifier(w, w0)
  29. #   plot(d, add=T)
  30. #
  31. plot.data = function(data, add=F, cex=3) {
  32.   lbl = (data$y+1)/2    # {-1..1} -> {0..1}
  33.   if (add)
  34.     points(data$X[,1],data$X[,2], bg=lbl, pch=21+lbl, cex=cex)
  35.   else
  36.     plot(data$X[,1],  data$X[,2], bg=lbl, pch=21+lbl, cex=cex, asp=1)
  37.   text(data$X[,1],  data$X[,2], col=(1-lbl), cex=0.2*cex)
  38. }
  39.  
  40.  
  41. load.data = function() {
  42.   x1 = c(-1.5,-1,-0.5,3, 0.5,1,2,2,-3);
  43.   x2 = c(0, 0, 0, 0);
  44.   y  = c(-1,-1,-1,-1,1,1,1,1,1);
  45.   data = list(cbind(x1, x2), y)
  46.   names(data) = c("X", "y")
  47.   class(data) = "data"
  48.   data
  49. }
  50.  
  51. data = load.data()
  52. m = svm(data$X, data$y, scale=FALSE,
  53.         kernel="linear", type="C-classification", cost=1)
  54.  
  55. alphas = m$coefs
  56. w = t(m$SV)%*% alphas
  57. w0 = -m$rho
  58.  
  59. plot.classifier(w, w0)
  60. plot.data(data, T)
  61. w
  62. alphas
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement