Advertisement
Ritajen

Untitled

Dec 6th, 2015
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. seizure<- read.csv('C:/Users/UX303LB/Desktop/class/R/seizure.csv')
  2. head(seizure)
  3. glm(seizure$y~seizure$trt+seizure$age,offset=seizure$ltime,family=poisson)
  4.  
  5. #第一題
  6. y<-(seizure$y)
  7. X<-cbind(1,seizure$trt,seizure$age)
  8. head(X)
  9. time<-exp(seizure$ltime)
  10.  
  11. f3<-function(beta){
  12. mu<-exp(X%*%beta)*time
  13. ymu<-y-mu
  14. gradient<-t(X)%*%ymu
  15. hessian<--t(X)%*%diag(as.vector(mu))%*%X
  16. return(list(gradient, hessian))
  17. }
  18.  
  19. newton <- function(f3, x0, tol = 1e-9, n.max = 100) {
  20. x <- x0
  21. f3.x <- f3(x)
  22. n <- 0
  23. while ((max(abs(f3.x[[1]])) > tol) & (n < n.max)) {
  24. x <- x - solve.default(f3.x[[2]], tol= 1e-19)%*% f3.x[[1]]
  25. f3.x <- f3(x)
  26. n <- n + 1
  27.  
  28.  
  29. }
  30. if (n == n.max) {
  31. cat('newton failed to converge\n')
  32. } else {
  33. return(x)
  34. }
  35. }
  36.  
  37. newton(f3,c(0, 0, 0),1e-9)
  38.  
  39. #第二題
  40. result<-glm(seizure$y~seizure$trt+seizure$age,offset=seizure$ltime,family=poisson)
  41. b<-newton(f3,c(0, 0, 0),1e-9)
  42. vcov(result)
  43. solve(-hessian)
  44. solve(-f3(b)[[2]], tol= 1e-19)
  45.  
  46.  
  47. #第三題
  48. beta<-newton(f3,c(0, 0, 0),1e-9)
  49. result<-glm(seizure$y~seizure$trt+seizure$age,offset=seizure$ltime,family=poisson)
  50. logLik(result)
  51. loglike<-sum((-exp(X%*%beta)%*%time)+(y%*%X%*%beta)+(y%*%(seizure$ltime))-(log(factorial(y))))
  52.  
  53. a<--exp(X%*%beta)%*%time
  54. b<-y%*%X%*%beta
  55. c<-y%*%(seizure$ltime)
  56. d<--log(factorial(y))
  57. loglike<-sum(a+diag(b)+diag(c)+d)
  58.  
  59. loglike<-sum(-mu+diag(y%*%log(mu))-log(factorial(y)))
  60. loglike<-sum(-mu+diag(y%*%log(mu))-log(factorial(y)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement