2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ポアソン回帰

Posted at

余所のサイトで勉強させて頂きました。


# pois regression

library(dplyr)

Y <- c( 6,  9, 11, 11,
       21, 14, 13, 20,
       38, 36, 23, 29,
       30, 33, 46, 40,
       61, 48, 54, 44)

X <- cbind(rep(1, length(Y)),
       c(1, 1, 1, 1,
         2, 2, 2, 2,
         3, 3, 3, 3,
         4, 4, 4, 4, 
         5, 5, 5, 5)
       )

beta <- matrix(0, ncol = 2, nrow = 100)

beta[1, ] <- c(1, 10)

for(m in 2:100){
  lambda <- exp(X %*% beta[m - 1, ])
  W <- diag(lambda[, 1])
  XtWX <- t(X) %*% W %*% X
  U <- t(Y - lambda) %*% X
  beta[m, ] <- beta[m - 1, ] + solve(XtWX) %*% t(U)
}

params=beta[nrow(beta),]

predict=exp(X%*%params)

plot(c(1:length(Y)),(Y),type="p",col=2,xlab="num",ylab="values",ylim=c(min((Y)),max((Y))))

par(new=T)

plot(c(1:length(Y)),predict,type="p",col=3,xlab="num",ylab="values",ylim=c(min((Y)),max((Y))))




data=read.csv("~/診療サンプル.csv")

library(dplyr)

Y <- as.numeric(data$発生件数)

X <- cbind(rep(1, length(Y)),
as.numeric(data$診療科),as.numeric(data$処方薬剤数)
       )

beta <- matrix(0, ncol = ncol(X), nrow = 100)

beta[1, ] <- rep(10,ncol(X))

for(m in 2:100){
  lambda <- exp(X %*% beta[m - 1, ])
  W <- diag(lambda[, 1])
  XtWX <- t(X) %*% W %*% X
  U <- t(Y - lambda) %*% X
  beta[m, ] <- beta[m - 1, ] + solve(XtWX) %*% t(U)
}

params=beta[nrow(beta),]

predict=exp(X%*%params)

plot(c(1:length(Y)),(Y),type="p",col=2,xlab="num",ylab="values",ylim=c(min((Y)),max((Y))))

par(new=T)

plot(c(1:length(Y)),predict,type="p",col=3,xlab="num",ylab="values",ylim=c(min((Y)),max((Y))))

データ:
image.png

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?