Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2017
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. updateWeights <- function(x, w, a, target){
  2. act <- x %*% w
  3. out <- ifelse(act > 0.5, 1, 0)
  4. e <- target - out
  5. update <- (t(t(w) + as.numeric(e*a)) * x)
  6. w <- ifelse(update == 0, w, update)
  7. return(w)
  8. }
  9.  
  10.  
  11. trainANN <- function(train, w, a, train_classes){
  12. ind <- sample(1:nrow(train), nrow(train), FALSE)
  13. for(i in ind){
  14. w <- updateWeights(train[i , ], w, a, train_classes[i, ])
  15. }
  16. return(w)
  17. }
  18.  
  19.  
  20.  
  21. testANN <- function(test, w, test_classes){
  22. r <- matrix(0, nrow(test))
  23.  
  24. for(i in 1:nrow(test)){
  25. x <- test[i, ]
  26. target <- test_classes[i, ]
  27. out <- ifelse(x %*% w > 0.5, 1, 0)
  28. r[i] <- ifelse(all(target == out), 1, 0)
  29. }
  30. return(sum(r) / length(r))
  31. }
  32.  
  33.  
  34. d <- matrix(c(runif(100, 0, 0.4), runif(100, 0.5, 1)), 100, 2, TRUE)
  35. plot(d, col = rep(c("blue", "green"), each = 50))
  36.  
  37.  
  38. classes <- matrix(rep(c(1,0,0,1), each = 50), 100, 2)
  39.  
  40. ind <- sample(1:nrow(d), nrow(d)*.9, FALSE)
  41. train <- d[ind, ]
  42. test <- d[-(ind), ]
  43. train_classes <- classes[ind, ]
  44. test_classes <- classes[-(ind), ]
  45.  
  46.  
  47.  
  48. nEpochs <- 500
  49. results <- rep(0, nEpochs)
  50. a <- 0.2
  51.  
  52. w <- matrix(runif(ncol(train)*ncol(classes), 0, 1), ncol(train), ncol(classes))
  53.  
  54. for(i in 1:nEpochs){
  55. w <- trainANN(train, w, a, train_classes)
  56. results[i] <- testANN(test, w, test_classes)
  57. }
  58.  
  59. plot(results)
  60. lines(results)
  61. mean(results)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement