-
Notifications
You must be signed in to change notification settings - Fork 28
/
1_heterogeneous_data_1_with_exercises.Rmd
391 lines (293 loc) · 10.5 KB
/
1_heterogeneous_data_1_with_exercises.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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
116
117
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
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
---
title: "Working with a heterogeneous dataset (census income dataset)"
output:
html_notebook:
editor_options:
chunk_output_type: inline
---
```{r}
library(keras)
library(readr)
library(dplyr)
library(ggplot2)
library(purrr)
use_session_with_seed(7777, disable_gpu = FALSE, disable_parallel_cpu = FALSE)
```
## The dataset
Here, we're using the "Census Income" (a.k.a. "Adult") dataset available at the [UCI Machine Learning Repository](http://mlr.cs.umass.edu/ml/datasets/Census+Income).
We are going to predict binarized salary (< resp. > 50k).
In this and a subsequent exercise, we are going to explore different ways of handling the presence of continuous as well as categorical variables.
## Prepare the data
The data is available in the file `data/adult.data`.
Short descriptions are contained in `data/adult.names`.
```{r}
train_data <- read_csv("data/adult.data",
col_names = c("age",
"workclass",
"fnlwgt",
"education",
"education_num",
"marital_status",
"occupation",
"relationship",
"race",
"sex",
"capital_gain",
"capital_loss",
"hours_per_week",
"native_country",
"salary"),
col_types = "iciciccccciiicc",
na = "?")
```
```{r}
train_data %>% glimpse()
```
```{r}
nrow(train_data)
```
The dataset contains missing values. For our current purpose it's okay to just remove all incomplete rows.
```{r}
train_data <- na.omit(train_data)
nrow(train_data)
```
### Target variable
We transform the values to 0s resp. 1s.
```{r}
y_train <- train_data$salary %>% factor() %>% as.numeric() - 1
y_train
```
Check that the reported class imbalance (~ 1:3) really is present in the dataset.
```{r}
table(y_train)
```
### Predictor variables
First we remove the target variable from the dataset and convert the character variables into factors.
```{r}
x_train <- train_data %>%
select(-salary) %>%
mutate_if(is.character, factor)
```
# Sequential model
We first show a way to work with this dataset using the Sequential API. Your task will then be to transform the code to use the Functional API (and make some other changes).
### Isolate the continuous variables into a new dataset, e.g. `x_train_continuous`.
```{r}
x_train_continuous <- x_train %>% select_if(is.numeric)
x_train_continuous
```
### Scale the variables to a common scale so the NN can handle them well.
As `x_train_continuous` will be passed in to `fit` later, it should finally be converted to a matrix.
```{r}
x_train_continuous <- x_train_continuous %>% mutate_all(scale) %>% as.matrix()
x_train_continuous
```
### isolate the categorical variables into a subset, e.g., `x_train_categorical`.
```{r}
x_train_categorical <- x_train %>% select_if(is.factor)
x_train_categorical
```
# One-hot-encode all categorical variables
You can use keras `to_categorical` for that. Encode every variable separately.
```{r}
c(workclass, education, marital_status, occupation, relationship, race, sex, native_country) %<-%
map(x_train_categorical, compose(to_categorical, as.numeric))
```
```{r}
workclass[1:5, ]
```
### Bind all columns (continuous and one-hot-encoded categorical ones) together
```{r}
x_train_all <- cbind(x_train_continuous, workclass, education, marital_status, occupation, relationship, race, sex, native_country)
```
```{r}
dim(x_train_all)
```
```{r}
x_train_all[1:10, ]
```
### Create sequential model
```{r}
model <- keras_model_sequential() %>%
layer_dense(units = 64, activation = "relu", input_shape = 112) %>%
layer_dropout(rate = 0.5) %>%
layer_dense(units = 64, activation = "relu") %>%
layer_dropout(rate = 0.5) %>%
layer_dense(units = 64, activation = "relu") %>%
layer_dropout(rate = 0.5) %>%
layer_dense(units = 1, activation = "sigmoid")
```
```{r}
model %>% compile(loss = "binary_crossentropy", optimizer = "adam", metrics = "accuracy")
```
```{r}
model %>% fit(
x = x_train_all,
y = y_train,
epochs = 20,
validation_split = 0.2
)
```
Note the final accuracy we got on the validation set: 0.8535.
Now go to `1_structureddata_quizzes.rmd` where you will be asked to use the Functional API with these data.
# Quiz 1
On the same prediction task, now use the Keras Functional API.
Use all of the continuous variables and have them share a single input.
In addition, add a categorical variable of your choice (this will need to get its own input).
In the quiz, you'll be asked to indicate the variable you chose and the accuracy you obtained.
We've copied some common, reusable code for you from above so you don't have to copy-paste the individual chunks.
```{r}
library(keras)
library(readr)
library(dplyr)
library(ggplot2)
library(purrr)
use_session_with_seed(7777, disable_gpu = FALSE, disable_parallel_cpu = FALSE)
train_data <- read_csv("data/adult.data",
col_names = c("age",
"workclass",
"fnlwgt",
"education",
"education_num",
"marital_status",
"occupation",
"relationship",
"race",
"sex",
"capital_gain",
"capital_loss",
"hours_per_week",
"native_country",
"salary"),
col_types = "iciciccccciiicc",
na = "?")
train_data <- na.omit(train_data)
y_train <- train_data$salary %>% factor() %>% as.numeric() - 1
x_train <- train_data %>%
select(-salary) %>%
mutate_if(is.character, factor)
x_train_continuous <- x_train %>% select_if(is.numeric)
x_train_continuous <- x_train_continuous %>% mutate_all(scale) %>% as.matrix()
x_train_categorical <- x_train %>% select_if(is.factor)
c(workclass, education, marital_status, occupation, relationship, race, sex, native_country) %<-%
map(x_train_categorical, compose(to_categorical, as.numeric))
```
Now please continue from here.
```{r}
input_continuous <- layer_input(shape = 6)
input_workclass <- layer_input(shape = 8)
dense_continuous <- input_continuous %>% layer_dense(units = 64)
dense_workclass <- input_workclass %>% layer_dense(units = 64)
output <- layer_concatenate(
list(
dense_continuous,
dense_workclass)
) %>%
layer_dropout(rate = 0.5) %>%
layer_dense(units = 64, activation = "relu") %>%
layer_dropout(rate = 0.5) %>%
layer_dense(units = 64, activation = "relu") %>%
layer_dropout(rate = 0.5) %>%
layer_dense(units = 1, activation = "sigmoid")
model <- keras_model(
inputs = list(
input_continuous,
input_workclass
),
outputs = output
)
model %>% compile(loss = "binary_crossentropy", optimizer = "adam", metrics = "accuracy")
model %>% fit(
x = list(
x_train_continuous,
workclass
),
y = y_train,
epochs = 20,
validation_split = 0.2
)
```
# Quiz 2
Modify your model to also predict `age`.
That is, remove `age` from the predictors and use it as a second target, together with `salary`.
We've copied some reusable code for you from above so you don't have to copy-paste the individual chunks.
```{r}
library(keras)
library(readr)
library(dplyr)
library(ggplot2)
library(purrr)
use_session_with_seed(7777, disable_gpu = FALSE, disable_parallel_cpu = FALSE)
train_data <- read_csv("data/adult.data",
col_names = c("age",
"workclass",
"fnlwgt",
"education",
"education_num",
"marital_status",
"occupation",
"relationship",
"race",
"sex",
"capital_gain",
"capital_loss",
"hours_per_week",
"native_country",
"salary"),
col_types = "iciciccccciiicc",
na = "?")
train_data <- na.omit(train_data)
```
Now please continue from here.
```{r}
y_train_salary <- train_data$salary %>% factor() %>% as.numeric() - 1
y_train_age <- train_data$age %>% as.matrix()
x_train <- train_data %>%
select(-c(salary, age)) %>%
mutate_if(is.character, factor)
x_train_continuous <- x_train %>% select_if(is.numeric)
x_train_continuous <- x_train_continuous %>% mutate_all(scale) %>% as.matrix()
x_train_categorical <- x_train %>% select_if(is.factor)
c(workclass, education, marital_status, occupation, relationship, race, sex, native_country) %<-%
map(x_train_categorical, compose(to_categorical, as.numeric))
input_continuous <- layer_input(shape = 5)
input_workclass <- layer_input(shape = 8)
dense_continuous <- input_continuous %>% layer_dense(units = 64)
dense_workclass <- input_workclass %>% layer_dense(units = 64)
common <- layer_concatenate(
list(
dense_continuous,
dense_workclass
)
) %>%
layer_dropout(rate = 0.5) %>%
layer_dense(units = 64, activation = "relu") %>%
layer_dropout(rate = 0.5) %>%
layer_dense(units = 64, activation = "relu") %>%
layer_dropout(rate = 0.5)
output_salary <- common %>%
layer_dense(units = 1, activation = "sigmoid", name = "output_salary")
output_age <- common %>% layer_dense(units = 1, name = "output_age")
model <- keras_model(
inputs = list(
input_continuous,
input_workclass
),
outputs = list(
output_salary,
output_age
)
)
model %>% compile(
loss = list(output_salary = "binary_crossentropy", output_age = "mse"),
optimizer = "adam",
metrics = list(output_salary = "accuracy", output_age = "mse"))
model %>% fit(
x = list(
x_train_continuous,
workclass
),
y = list(y_train_salary, y_train_age),
epochs = 20,
validation_split = 0.2
)
```