celestialgod

logistic reg.

Dec 5th, 2015
280
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 2.28 KB | None | 0 0
  1. df = read.table(textConnection('
  2. ID      admit   gre     gpa
  3. 1       0       380     3.61
  4. 2       1       660     3.67
  5. 3       1       800     4
  6. 4       1       640     3.19
  7. 5       0       520     2.93
  8. 6       1       760     3
  9. 7       1       560     2.98
  10. 8       0       400     3.08
  11. 9       1       540     3.39
  12. 10      0       700     3.92
  13. 11      0       800     4
  14. 12      0       440     3.22
  15. 13      1       760     4
  16. 14      0       700     3.08
  17. 15      1       700     4
  18. 16      0       480     3.44
  19. 17      0       780     3.87
  20. 18      0       360     2.56
  21. 19      0       800     3.75
  22. 20      1       540     3.81
  23. 21      0       500     3.17
  24. 22      1       660     3.63        
  25. 23      0       600     2.82
  26. 24      0       680     3.19
  27. 25      1       760     3.35
  28. 26      1       800     3.66
  29. 27      1       620     3.61
  30. 28      1       520     3.74
  31. 29      1       780     3.22
  32. 30      0       520     3.29
  33. 31      0       540     3.78
  34. 32      0       760     3.35
  35. 33      0       600     3.4
  36. 34      1       800     4
  37. 35      0       360     3.14
  38. 36      0       400     3.05
  39. 37      0       580     3.25
  40. 38      0       520     2.9
  41. 39      1       500     3.13
  42. 40      1       520     2.68
  43. 41      0       560     2.42
  44. 42      1       580     3.32
  45. 43      1       600     3.15
  46. 44      0       500     3.31
  47. 45      0       700     2.94
  48. 46      1       460     3.45
  49. 47      1       580     3.46
  50. 48      0       500     2.97
  51. 49      0       440     2.48
  52. 50      0       400     3.35'), header = TRUE)
  53. X = as.matrix(cbind(1, df[,3:4]))
  54. y = df[,2]
  55. f3<-function(beta){
  56.   xb = X %*% beta
  57.   pi_est = exp(xb)/(1+exp(xb))
  58.   ypi = y-pi_est
  59.   gradient = t(X) %*% ypi
  60.   hessian = -t(X) %*% diag(as.vector(pi_est * (1-pi_est))) %*% X
  61.   return(list(gradient, hessian))
  62. }
  63.  
  64. newton <- function(f3, x0, tol = 1e-9, n.max = 100) {
  65.   x <- x0
  66.   f3.x <- f3(x)
  67.   n <- 0
  68.   while ((max(abs(f3.x[[1]])) > tol) & (n < n.max)) {
  69.     x <- x - solve(f3.x[[2]]) %*% f3.x[[1]]
  70.     f3.x <- f3(x)
  71.     n <- n + 1
  72.   }
  73.   if (n == n.max) {
  74.     cat('newton failed to converge\n')
  75.   } else {
  76.     return(x)
  77.   }
  78. }
  79.  
  80. b1 = newton(f3,c(0, 0, 0),1e-6)
  81. b1
  82. coef(glm(admit ~ gre + gpa, df, family = 'binomial'))
  83. -solve(f3(b1)[[2]])
  84. vcov(glm(admit ~ gre + gpa, df, family = 'binomial'))
Advertisement
Add Comment
Please, Sign In to add comment