逻辑回归

  • 逻辑回归

a、逻辑回归是广义线性模型的一种,可根据一组数值变量预测二元输出,R中的基本函数glm()可用于拟合逻辑回归模型。git

b、glm()函数自动将预测变量 中的分类变量编码为相应的虚拟变量。由于此例的所有预测变量都是数值型的变量,所以没必要要对其编码dom

> fit.logit <- glm(class ~.,data=df.train,family = binomial()) #拟合逻辑回归,family = binomial()表示二项式
> summary(fit.logit)                                           #class是响应变量,其余的为预测变量

Call:
glm(formula = class ~ ., family = binomial(), data = df.train)

Deviance Residuals: 
     Min        1Q    Median        3Q       Max  
-2.75813  -0.10602  -0.05679   0.01237   2.64317  

Coefficients:
                          Estimate Std. Error z value Pr(>|z|)    
(Intercept)              -10.42758    1.47602  -7.065 1.61e-12 ***
clumpThickness             0.52434    0.15950   3.287  0.00101 ** 
sizeUniformity            -0.04805    0.25706  -0.187  0.85171    
shapeUniformity            0.42309    0.26775   1.580  0.11407    
maginalAdhesion            0.29245    0.14690   1.991  0.04650 *  
singleEpithelialCellSize   0.11053    0.17980   0.615  0.53871    
bareNuclei                 0.33570    0.10715   3.133  0.00173 ** 
blandChromatin             0.42353    0.20673   2.049  0.04049 *  
normalNucleoli             0.28888    0.13995   2.064  0.03900 *  
mitosis                    0.69057    0.39829   1.734  0.08295 .  
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 612.063  on 482  degrees of freedom
Residual deviance:  71.346  on 473  degrees of freedom
  (6 observations deleted due to missingness)
AIC: 91.346

Number of Fisher Scoring iterations: 8
  • 基于训练集对验证集进行验证

采用基于df.train 创建的模型来对 df.validate数据集中的样本单元分类,predict()函数默认输出肿瘤为恶性的几率,指定参数 type="response"函数

> prob <- predict(fit.logit,df.validate,type="response")
> logit.pred <- factor(prob > 0.5,levels = c(FALSE,TRUE),labels = c("bengin","maligant")) #样本单元中,几率大于0.5被分为恶性肿瘤,几率小于等于0.5的被分为良性肿瘤类

评估预测的准确性编码

> logit.perf <- table(df.validate$class,logit.pred,dnn = c("Actual","Predicted"))
> logit.perf
           Predicted
Actual      bengin maligant
  benign       118        2
  malignant      4       76
#给出预测与实际状况对比的交叉表(即混淆矩阵,confusionn matrix)。
#模型正确判别了118个类别为良性的患者和17个类别为恶性的患者,另外,di.validate数据集中有10个样本单元因包含缺失值数据没法判别
#验证集上,正确分类的模型(即准确率,acuracy)为(76+118)/200=97%
  • 移除模型中的噪声

在该案例中注意到三个预测变量(sizeUniformity,shapeUniformity,singleEpithelalCellSize)的系数未经过显著性检验(即 p 值大于0.1),从预测变量的角度来讲,通常不会将这些变量归入模型,当这类不包含相关信息的变量特别多时,能够直接将其都认为模型中的噪声spa

去除后再拟合,获得一个更小的 AIC 值code

logit.fit.reduced <- step(fit.logit)  #可利用这种方法获得一个移除上述三个变量的精简模型,这种模型在验证集上的偏差相对全变量模型更小
相关文章
相关标签/搜索
本站公众号
   欢迎关注本站公众号,获取更多信息