使用Smarket数据集绘制R中的逻辑回归

时间:2015-03-12 19:27:24

标签: r model visualization regression logistic-regression

我试图在S中为Smarket数据集(在“MASS”库中)绘制一个简单的逻辑回归。我已经成功完成了glm.fit过程来计算偏差残差和系数,但我真的很想看到逻辑回归,但找不到一个简单的方法来做到这一点。

有关更多背景信息,我正在使用“统计学习简介”。这是第156-160页练习的延伸(顺便说一下,这不是学校的要求,只是我想弄清楚)。我想这是一个相对容易的问题,但我是R的新手,似乎无法得到它。

感谢。

我使用的代码如下:

glm.fit=glm(Direction~Lag1+Lag2+Lag3+Lag4+Lag5+Volume , data = Smarket, family=binomial)
summary(glm.fit)
coef(glm.fit)

有没有办法创建逻辑回归的可视化? 我没有包含代码来包含库,如果需要,请告诉我,我会添加它。

谢谢!

1 个答案:

答案 0 :(得分:0)

以下是一些可视化逻辑回归结果的方法,其中第一,第三和第四种都是根据Gelman& 5的第5章code改编而来的。 Hill,使用回归的数据分析&多级/分层模型。下面的代码使用arm包中的一些函数(随本书一起提供):

library(arm)

1)在Lag 1值的范围和3个不同的Volume值的范围内绘制Direction =“Up”的概率(其他Lag值设置为零,但如果您愿意,可以将它们设置为其他值))< / p>

# Function to jitter class category values
jitter.binary <- function(a, jitt=.05){
  ifelse (a-1==0, runif(length(a), 0, jitt), runif(length(a), 1-jitt, 1))
}

# Sequence of Lag1 values for plotting
x = seq(-5,5.7,length.out=100)

# Plot jittered Direction vs. Lag 1. This shows the actual distribution of the data.
with(Smarket, plot(Lag1, jitter.binary(as.numeric(Direction)), pch=16,cex=0.7,
                   ylab="Pr(Up)", xlab="Lag 1"))

# Add model prediction curves. These show the probability of Direction="Up" vs. Lag 1 
# for three different fixed values of Volume.
curve(expr=invlogit(cbind(1, x,0,0,0,0,1.48) %*% coef(glm.fit)), 
      from=-5, to=5.7, lwd=.5, add=TRUE)
curve(expr=invlogit(cbind(1, x, 0,0,0,0, 0.36) %*% coef(glm.fit)), 
      from=-5, to=5.7, lwd=.5, add=TRUE, col="red", lty=2)
curve(expr=invlogit(cbind(1, x, 0,0,0,0, 3.15) %*% coef(glm.fit)), 
      from=-5, to=5.7, lwd=.5, add=TRUE, col="blue", lty=2)

enter image description here

2)绘制滞后1对比体积,用点的值对点进行着色,并添加决策边界。为了概念上的简单,我做了一个新的回归,只有两个预测因子,因为决策边界是一个五维超平面,用于实际的回归。 (对于具有许多预测变量的模型,您仍然可以通过在多维预测变量空间中采用2D切片来在二维中绘制决策边界图。)

# New regression model
glm.fit2 = glm(Direction ~ Lag1 + Volume , data = Smarket, family=binomial)

# Probability of Direction="Up" for this model
Smarket$Pred2 = predict(glm.fit2, type="response")

# Set Prediction to "Up" for probability > 0.5; "Down" otherwise.
Smarket$PredCat2 = cut(Smarket$Pred2, c(0,0.5,1), include.lowest=TRUE, labels=c("Down","Up"))

# Graph Lag1 vs. Volume with coloring and point-style based on value
# of Direction
with(Smarket, plot(Lag1, Volume, pch=ifelse(Direction=="Down", 3, 1), 
                   col=ifelse(Direction=="Down", "red", "blue"), cex=0.6))

# Add the decision boundary
curve(expr= -(cbind(1, x) %*% coef(glm.fit2)[1:2])/coef(glm.fit2)[3],
      from=-5,to=5.7, add=TRUE)

enter image description here

3)分箱残差的平均值与“Up”的预测概率的关系图:

x = predict(glm.fit, type="response")
y = resid(glm.fit)
binnedplot(x,y, xlab="Pr(Up)")

4)用置信区间绘制系数值。这不是分类的具体内容;只是一种可视化模型系数的快速方法。

coefplot(glm.fit)