簡體   English   中英

如何通過 R 中的熱圖可視化邏輯回歸

[英]How to visualize logistic regression by heatmap in R

我有二元觀測值 y (0,1) 和兩個自變量(x1 和 x2)的邏輯回歸。 我想通過熱圖(二維預測值矩陣)可視化 model 預測。 我能夠部分得到我想要的(參見下面的 plot),但是如何添加:

  • 色階到預測值
  • x1 和 x2 的適當軸(水平和垂直)
  • 我怎么知道矩陣的適當旋轉? x1(或 x2)在水平軸還是垂直軸上?

...

# data simulation
set.seed(16)
x_sample.lr <- seq(1,100, by = 0.5)
# data.frame creation
lr.df <- data.frame(y = sample(c(0,1), 50, replace = TRUE),
                    x1 = sample(x_sample.lr, 50, replace = TRUE),
                    x2 = sample(x_sample.lr, 50, replace = TRUE))

# model creation
lr.mod <- glm(y ~ x1*x2, data = lr.df, family = "binomial")
anova(lr.mod, test = "Chi")
summary(lr.mod)

# ...calculating prediction
lr.pred <- expand.grid(x1 = x_sample.lr, x2 = x_sample.lr)
lr.pred$predicted <- predict(lr.mod, newdata = lr.pred)
head(lr.pred)
#    x1 x2 predicted
# 1 1.0  1  2.306825
# 2 1.5  1  2.279347
# 3 2.0  1  2.251869

# ...plot visualization
pl.pred.mtrx <- matrix(lr.pred$predicted, ncol = sqrt(nrow(lr.pred)))
image(pl.pred.mtrx)

在此處輸入圖像描述

當您使用 matrix() 時,它按列填充矩陣,因此檢查您的前 199 個值,全部使用 x2 == 1,

all(lr.pred$predicted[1:199] == pl.pred.mtrx[,1])

當你用 image() plot 這個矩陣時,你實際上轉置了矩陣和 plot 顏色,你可以試試這個:

image(matrix(1:18,ncol=2))

所以在你的 plot 中,xaxis 是 x1,yaxis 是 x2,我們可以添加軸標簽,抑制刻度。

# we place it at 1,10,20..100
TICKS = c(1,10*(1:10))

image(pl.pred.mtrx,xlab="x1",ylab="x2",xaxt="n",yaxt="n")
# position of your ticks is the num over the length
axis(side = 1, at = which(x_sample.lr %in% TICKS)/nrow(pl.pred.mtrx),labels = TICKS)
axis(side = 2, at = which(x_sample.lr %in% TICKS)/ncol(pl.pred.mtrx),labels = TICKS)

在此處輸入圖像描述

我不知道添加顏色圖例的簡單方法。 所以我的建議是使用字段:

library(fields)
# in this case we know how x and y will run.. with respect to matrix z
# in other situations, this will depend on how you construct z
DA = list(x=x_sample.lr,y=x_sample.lr,z=pl.pred.mtrx)
image.plot(DA,col=hcl.colors(12, "YlOrRd", rev = TRUE))

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM