Advertisement
Guest User

Untitled

a guest
Feb 24th, 2017
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. # Generate random values
  2. set.seed(11111)
  3. x <- rnorm(n = 50)
  4. y <- 10 * x + rnorm(n = 50)
  5.  
  6. # Add intercept
  7. x <- cbind(1,x)
  8.  
  9. # Assume random null parameters
  10. param <- c(0,0)
  11.  
  12. # Store count of observations
  13. m <- length(y)
  14.  
  15. # Calculate Mean Squared Error cost
  16. cost <- function(x, y, param) {mean(((x %*% param)- y) ^ 2)}
  17. grad <- function(x, y, param) {
  18. gradient <- rep(0, length(param))
  19. pre_sum <- ((x %*% param) - y)
  20. for (i in 1:length(param)) {
  21. # Squared Error = (x - y) ^ 2
  22. # Squared Error Gradient: 2 * (x - y)
  23. gradient[i] <- 2 * mean(pre_sum * x[, i])
  24. }
  25. return(gradient)
  26. }
  27.  
  28. # Set learning rate (eta)
  29. eta <- 0.20
  30.  
  31. # Set number of boosting iterations
  32. iters <- 20
  33.  
  34. # Perform boosting with real-time plotting
  35. plot(x[, ncol(x)], y, col = "blue", pch = 20, xlab = "x", ylab = "y")
  36. for(i in 1:iters) {
  37. abline(param[1], param[2], col = rgb(0.8, 0.0, 0.2, alpha = 0.25))
  38. #cat("[", sprintf("%02d", i), "] Cost: ", sprintf("%10.07f", cost(x, y, param)), "\n", sep = "")
  39. cat("[", sprintf("%02d", i), "] Cost: ", sprintf("%10.07f", cost(x, y, param)), ", params = ", paste(sprintf("%08.06f", param), collapse = ", "), "\n", sep = "")
  40. param <- param - eta * grad(x, y, param)
  41. }
  42. abline(param[1], param[2], col = "blue")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement