UPDATE: 2022-09-14 18:33:51
数年前に書いたものをそのまま転記している。ポアソン回帰分析の誤差構造とリンク関数の視覚化するスクリプト。
<- 2
n <- cars$speed
X <- cars$dist
Y <- data.frame(X,Y)
df <- seq(min(X)-2, max(X)+2, length = n)
mat_x <- seq(min(Y), max(Y), length = n)
mat_y
#ベースとなる3次元空間
<- persp(x = mat_x,
mat y = mat_y,
z = matrix(0, n, n),
zlim = c(0, 0.2), #zの高さ
theta = 30, #アングル
phi = 15,
ticktype = "detailed",
box = FALSE)
#ポアソン回帰分析
<- glm(Y ~ X,
fit_poisson data = cars,
family = poisson(link = "log"))
<- seq(min(X), max(X), length = 50)
x
#予測値をプロット
#type = "response"はexp(y)を返す。
<- trans3d(x = x,
fit_line y = predict(fit_poisson,
newdata = data.frame(X = x),
type = "response"),
z = rep(0, length(x)),
mat)
#95%信頼区間
<- qpois(0.95,
upr predict(fit_poisson,
newdata = data.frame(X = x),
type="response"))
<- qpois(0.05,
lwr predict(fit_poisson,
newdata = data.frame(X = x),
type="response"))
<- trans3d(x, upr, rep(0, length(x)), mat)
upr_line <- trans3d(x, lwr, rep(0, length(x)), mat)
lwr_line
#信頼区間を塗りつぶす
<- trans3d(c(x, rev(x)),
conf_fill c(upr, rev(lwr)),
rep(0, 2*length(x)),
mat)
#散布図
<- trans3d(X, Y, rep(0, length(X)), mat)
scatter_plt
#予測値、信頼区間、散布図をプロット
polygon(conf_fill,
border = NA,
col = "#B2D6E7")
lines(fit_line, lwd = 1)
lines(upr_line, lty = 1)
lines(lwr_line, lty = 1)
points(scatter_plt, pch = 19, col = "#0070B9")
#ポアソン分布の個数
<- 10
n <- seq(min(X), max(X), length = n)
mat_x
#各x時点でのポアソン回帰分析の予測値
<- predict(fit_poisson,
lambda newdata = data.frame(X = mat_x),
type = "response")
for(j in n:1){
= 500
x_n = rep(mat_x[j], x_n)
x = seq(min(min(Y), qpois(0.05, predict(fit_poisson,newdata=data.frame(X=mat_x[j]),type="response"))),
y max(Y),
length = x_n)
= ceiling(y)
y = rep(0, x_n)
z0 = dpois(y, lambda[j])
z = trans3d(c(x, x), c(y, rev(y)), c(z, z0), mat)
fill_pois polygon(fill_pois, border = NA, col = "#B2D6E7", density = 40)
= trans3d(x,y,z0,mat)
x_line lines(x_line, lty = 1)
= trans3d(x, y, z, mat)
col_line lines(col_line, col = "#0070B9")
}