08-logistic-regression.Rmd 6.22 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
---
title: "Regressão logística"
author: Prof. Walmes M. Zeviani & Prof. Eduardo V. Ferreira
date: 2017-11-14
#bibliography: ../config/Refs.bib
#csl: ../config/ABNT-UFPR-2011-Mendeley.csl
---

```{r, include = FALSE}
source("../config/setup.R")
opts_chunk$set(
    cache = FALSE,
    message = FALSE,
    warning = FALSE)
```

# Resposta dicotômica

  * <https://datascienceplus.com/perform-logistic-regression-in-r/>;
  * <http://dataaspirant.com/2017/03/14/multinomial-logistic-regression-model-works-machine-learning/>;
  * <https://machinelearningmastery.com/linear-classification-in-r/>;

```{r}
24
# Pacotes.
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
library(lattice)
library(latticeExtra)

# Carrega os dados.
url <- paste0("http://archive.ics.uci.edu/ml/machine-learning-databases",
              "/credit-screening/crx.data")
cre <- read.csv(url, header = FALSE, na.string = "?")
names(cre)[16] <- "y"

summary(cre)

# Visualiza a resposta contra as preditoras métricas.
n <- sapply(cre[, -16], is.numeric)
f <- sprintf("y ~ %s",
             paste(names(cre)[1:15][n],
                   collapse = " + "))
xyplot(as.formula(f),
       outer = TRUE,
       data = cre,
       as.table = TRUE,
       jitter.y = TRUE,
       amount = 0.025,
       scales = list(x = list(relation = "free", log = FALSE))) +
    latticeExtra::layer(panel.smoother(x, y, method = lm))

50
51
52
53
54
55
56
57
58
59
60
61
62
63
xyplot(as.formula(f),
       outer = TRUE,
       data = na.omit(cre),
       as.table = TRUE,
       jitter.y = TRUE,
       amount = 0.025,
       scales = list(x = list(relation = "free", log = FALSE))) +
    latticeExtra::layer({
        mod <- glm(y ~ x, family = binomial)
        xp <- seq(min(x), max(x), length.out = 101)
        yp <- predict(mod, newdata = list(x = xp), type = "response")
        panel.lines(x = xp, y = yp + 1)
    })

64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# Visualiza contra as preditoras categóricas.
v <- names(cre)[1:15][sapply(cre[, -16], is.factor)]
length(v)

keep <- logical(length(v))
names(keep) <- v

par(mfrow = c(3, 3))
for (i in v) {
    xt <- xtabs(as.formula(sprintf("~y + %s", i)), data = cre)
    # print(min(prop.table(xt)) > 0.1)
    if (min(prop.table(xt)) > 0.1) {
        keep[i] <- TRUE
    }
    mosaicplot(xt, main = NULL)
}
layout(1)

# Mantém só variáveis sem separação.
cre <- subset(cre,
              select = setdiff(names(cre),
                               names(which(!keep))))

# Casos completos.
cc <- complete.cases(cre)
table(cc)

# Elimina os casos perdidos.
cre <- cre[cc, ]

# # Ajusta o modelo.
# m0 <- glm(y ~ 1, data = cre, family = binomial)

# Ajusta o modelo.
m0 <- glm(y ~ ., data = cre, family = binomial)
summary(m0)

# Realiza seleção de preditoras com stepwise via BIC.
m1 <- step(m0, k = log(nrow(cre)))
summary(m1)

# Realiza predição.
yp <- predict(m1, type = "response")

# Erro de classificação.
tb <- table(round(yp), cre$y)
tb

# Percentual de acertos.
sum(diag(tb))/sum(tb)
```

116
117
## Usando o pacote `caret`

118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
  * <https://topepo.github.io/caret/available-models.html>

```{r, eval = FALSE}
library(caret)

# Criando as partições de treino e validação.
set.seed(789)
intrain <- createDataPartition(y = cre$y,
                               p = 0.75,
                               list = FALSE)
cre_train <- cre[intrain, ]
cre_test <- cre[-intrain, ]
list(train = nrow(cre_train),
     test = nrow(cre_test),
     ratio = nrow(cre_train)/nrow(cre))

# Parametriza a valiação cruzada.
trctrl <- trainControl(method = "repeatedcv", number = 10, repeats = 3)

# Boosted Logistic Regression e outras opções.
set.seed(159)
fit <- train(y ~ .,
             data = cre_train,
             method = c("LogitBoost", "regLogistic", "plr")[1],
             trControl = trctrl)
fit

fit$finalModel

# Predição e matriz de confusão.
yp <- predict(fit, newdata = cre_test)
confusionMatrix(yp, cre_test$y)
```

# Resposta politômica

## Usando o `VGAM`

  * <https://machinelearningmastery.com/linear-classification-in-r/>;

```{r}
# Carrega o pacote.
library(VGAM)

162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
#-----------------------------------------------------------------------
# Usando um par de preditoras para visualizar a fronteira.

# Ajuste do modelo.
fit <- vglm(Species ~ Sepal.Length + Sepal.Width,
            family = multinomial,
            data = iris)
summary(fit)

grid <- with(iris,
             expand.grid(
                 Sepal.Length = seq(min(Sepal.Length),
                                    max(Sepal.Length),
                                    length.out = 61),
                 Sepal.Width = seq(min(Sepal.Width),
                                   max(Sepal.Width),
                                   length.out = 61),
                 KEEP.OUT.ATTRS = FALSE))

prob <- predict(fit, newdata = grid, type = "response")
grid$pred <- apply(prob, MARGIN = 1, FUN = which.max)
grid$pred <- factor(grid$pred, labels = levels(iris$Species))

# Gráfico com pontos, classficações, fronteira e vetores de suporte.
plot(Sepal.Width ~ Sepal.Length,
     data = grid,
     col = as.integer(grid$pred),
     pch = 3)
points(Sepal.Width ~ Sepal.Length,
       data = iris,
       col = as.integer(iris$Species),
       pch = 19)

#-----------------------------------------------------------------------
# Usando todas as preditoras.

198
199
200
201
202
203
204
205
206
207
208
209
# Ajusta o modelo.
fit <- vglm(Species ~ ., family = multinomial, data = iris)

# Exibe o resumo do ajuste.
summary(fit)

# Obtém as predições.
prob <- predict(fit, newdata = iris, type = "response")
pred <- apply(prob, MARGIN = 1, FUN = which.max)
pred <- factor(pred, labels = levels(iris$Species))

# Acurácia.
210
caret::confusionMatrix(pred, iris$Species)
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
```

## Usando o `caret`

```{r}
library(caret)

# Criando as partições de treino e validação.
set.seed(987)
intrain <- createDataPartition(y = iris$Species,
                               p = 0.75,
                               list = FALSE)
data_train <- iris[intrain, ]
data_test <- iris[-intrain, ]

# Parametriza a valiação cruzada.
227
228
229
trctrl <- trainControl(method = "repeatedcv",
                       number = 10,
                       repeats = 3)
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244

# Penalized Multinomial Regression, usa a nnet::multinom().
set.seed(159)
fit <- train(Species ~ .,
             data = data_train,
             method = "multinom",
             trControl = trctrl)
fit

fit$finalModel

# Predição e matriz de confusão.
yp <- predict(fit, newdata = data_test)
confusionMatrix(yp, data_test$Species)
```