R:训练有素的GLM模型的分类公式[提供的可重复的例子]

时间:2016-06-02 16:57:41

标签: r classification logistic-regression

问题

(1)以下示例代码中拟合模型的分类公式名为' model1 &#39 ;? (是公式A,B还是两者都没有?)

(2)' model1 '判断class == 1 vs. 2?

  • 公式A:
      

    class(Species {1:2})=( - 31.938998)+( - 7.501714 * [PetalLength])+(63.670583 * [PetalWidth])

  • B公式:
      

    class(Species {1:2})= 1.346075e-14 +(5.521371e-04 * [PetalLength])+(4.485211e + 27 * [PetalWidth])

使用案例

使用R来拟合/训练二进制分类模型,然后解释模型以便在Excel中手动计算分类,而不是R。

模型系数

>coef(model1)
#(Intercept) PetalLength  PetalWidth 
#-31.938998   -7.501714   63.670583 

>exp(coef(model1))
#(Intercept)  PetalLength   PetalWidth 
#1.346075e-14 5.521371e-04 4.485211e+27 

R代码示例

# Load data (using iris dataset from Google Drive because uci.edu link wasn't working for me today)
#iris <- read.csv(url("http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"), header = FALSE)
iris <- read.csv(url("https://docs.google.com/spreadsheets/d/1ovz31Y6PrV5OwpqFI_wvNHlMTf9IiPfVy1c3fiQJMcg/pub?gid=811038462&single=true&output=csv"), header = FALSE)
dataSet <- iris

#assign column names
names(dataSet) <- c("SepalLength", "SepalWidth", "PetalLength", "PetalWidth", "Species")

#col names
dsColNames <- as.character(names(dataSet))

#num of columns and rows
dsColCount <- as.integer(ncol(dataSet))
dsRowCount <- as.integer(nrow(dataSet))

#class ordinality and name
classColumn <- 5 
classColumnName <- dsColNames[classColumn]
y_col_pos <- classColumn

#features ordinality
x_col_start_pos <- 1
x_col_end_pos <- 4

# % of [dataset] reserved for training/test and validation  
set.seed(10)
sampleAmt <- 0.25
mainSplit <- sample(2, dsRowCount, replace=TRUE, prob=c(sampleAmt, 1-sampleAmt))

#split [dataSet] into two sets
dsTrainingTest <- dataSet[mainSplit==1, 1:5] 
dsValidation <- dataSet[mainSplit==2, 1:5]
nrow(dsTrainingTest);nrow(dsValidation);

# % of [dsTrainingTest] reserved for training
sampleAmt <- 0.5
secondarySplit <- sample(2, nrow(dsTrainingTest), replace=TRUE, prob=c(sampleAmt, 1-sampleAmt))

#split [dsTrainingTest] into two sets 
dsTraining <- dsTrainingTest[secondarySplit==1, 1:5]
dsTest <- dsTrainingTest[secondarySplit==2, 1:5]
nrow(dsTraining);nrow(dsTest);

nrow(dataSet) == nrow(dsTrainingTest)+nrow(dsValidation)
nrow(dsTrainingTest) == nrow(dsTraining)+nrow(dsTest)

library(randomGLM)

dataSetEnum <- dsTraining[,1:5]
dataSetEnum[,5] <- as.character(dataSetEnum[,5])
dataSetEnum[,5][dataSetEnum[,5]=="Iris-setosa"] <- 1 
dataSetEnum[,5][dataSetEnum[,5]=="Iris-versicolor"] <- 2 
dataSetEnum[,5][dataSetEnum[,5]=="Iris-virginica"] <- 2 
dataSetEnum[,5] <- as.integer(dataSetEnum[,5])

x <- as.matrix(dataSetEnum[,1:4])
y <- as.factor(dataSetEnum[,5:5])

# number of features
N <- ncol(x)

# define function misclassification.rate
if (exists("misclassification.rate") ) rm(misclassification.rate);
misclassification.rate<-function(tab){
  num1<-sum(diag(tab))
  denom1<-sum(tab)
  signif(1-num1/denom1,3)
}

#Fit randomGLM model - Ensemble predictor comprised of individual generalized linear model predictors
RGLM <- randomGLM(x, y, classify=TRUE, keepModels=TRUE,randomSeed=1002)

RGLM$thresholdClassProb

tab1 <- table(y, RGLM$predictedOOB)
tab1
# y  1  2
# 1  2  0
# 2  0 12

# accuracy
1-misclassification.rate(tab1)

# variable importance measure
varImp = RGLM$timesSelectedByForwardRegression
sum(varImp>=0)

table(varImp)

# select most important features
impF = colnames(x)[varImp>=5]
impF

# build single GLM model with most important features
model1 = glm(y~., data=as.data.frame(x[, impF]), family = binomial(link='logit'))

coef(model1)
#(Intercept) PetalLength  PetalWidth 
#-31.938998   -7.501714   63.670583 

exp(coef(model1))
#(Intercept)  PetalLength   PetalWidth 
#1.346075e-14 5.521371e-04 4.485211e+27 

confint.default(model1)
#                2.5 %   97.5 %
#(Intercept) -363922.5 363858.6
#PetalLength -360479.0 360464.0
#PetalWidth  -916432.0 916559.4

2 个答案:

答案 0 :(得分:1)

GLM模型具有链接功能和线性预测器。您尚未在上面指定链接功能。

设Y = {0,1},X为n×p矩阵。 (使用伪LaTeX)这导致\hat Y= \phi(X \hat B) = \eta

其中
  - \eta是线性预测器   - \phi()是链接功能

线性预测器仅为X %*% \hat B,分类返回P(Y=1|X) = \phi^{-1}(\eta) - 即反向链接函数。反向链接功能显然取决于链接的选择。对于logit,您有逆logit P(Y=1|X) = exp(eta) / (1+ exp(eta))

答案 1 :(得分:1)

您的模型定义为

model1 <- glm(y~., data=as.data.frame(x[, impF]), family=binomial(link='logit'))

family=binomial(link='logit'))位表示响应 y 是一系列伯努利试验,即取决于参数 p , p = exp( m )/(1 + exp( m )),其中 m 是数据的函数,称为线性预测器。

公式y~.表示 m = a + b PetalLength + c PetalWidth,其中 a b c 是模型系数。

因此 y = 1的概率为

> m <- model.matrix(model1) %*% coef(model1)
> exp(m) / (1+exp(m))
            [,1]
20  3.448852e-11
50  1.253983e-13
65  1.000000e+00
66  1.000000e+00
87  1.000000e+00
105 1.000000e+00
106 1.000000e+00
107 1.000000e+00
111 1.000000e+00
112 1.000000e+00
116 1.000000e+00
118 1.000000e+00
129 1.000000e+00
130 1.000000e+00

我们可以检查这与fitted.values

的输出相同
> fitted.values(model1)
          20           50           65           66           87          105 
3.448852e-11 1.253983e-13 1.000000e+00 1.000000e+00 1.000000e+00 1.000000e+00 
         106          107          111          112          116          118 
1.000000e+00 1.000000e+00 1.000000e+00 1.000000e+00 1.000000e+00 1.000000e+00 
         129          130 
1.000000e+00 1.000000e+00 

最后,根据P( Y = 1)是高于还是低于某个阈值,可以将响应分为两类。例如,

> ifelse(fitted.values(model1) > 0.5, 1, 0)
 20  50  65  66  87 105 106 107 111 112 116 118 129 130 
  0   0   1   1   1   1   1   1   1   1   1   1   1   1