-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path08-deep-learning.Rmd
385 lines (276 loc) · 8.54 KB
/
08-deep-learning.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
# Deep Learning
## Artificial Neural Network
### Importing the libraries
**Python**
```{python}
import numpy as np
import pandas as pd
import tensorflow as tf
tf.__version__
```
### Part 1 - Data Preprocessing {.unnumbered}
### Importing the dataset
**Python**
```{python}
dataset = pd.read_csv('Churn_Modelling.csv')
X = dataset.iloc[:, 3:-1].values
y = dataset.iloc[:, -1].values
print(X)
print(y)
```
**R**
```{r}
dataset = read.csv('Churn_Modelling.csv')
dataset = dataset[4:14]
```
### Encoding categorical data
**Python**
```{python}
# Label Encoding the "Gender" column
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
X[:, 2] = le.fit_transform(X[:, 2])
print(X)
# One Hot Encoding the "Geography" column
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder
ct = ColumnTransformer(transformers=[('encoder', OneHotEncoder(), [1])], remainder='passthrough')
X = np.array(ct.fit_transform(X))
print(X)
```
**R**
```{r}
dataset$Geography = as.numeric(factor(dataset$Geography,
levels = c('France', 'Spain', 'Germany'),
labels = c(1, 2, 3)))
dataset$Gender = as.numeric(factor(dataset$Gender,
levels = c('Female', 'Male'),
labels = c(1, 2)))
```
### Splitting the dataset into the Training set and Test set
**Python**
```{python}
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)
```
**R**
```{r}
# install.packages('caTools')
library(caTools)
set.seed(123)
split = sample.split(dataset$Exited, SplitRatio = 0.8)
training_set = subset(dataset, split == TRUE)
test_set = subset(dataset, split == FALSE)
```
### Feature Scaling
**Python**
```{python}
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
```
**R**
```{r}
training_set[-11] = scale(training_set[-11])
test_set[-11] = scale(test_set[-11])
```
### Part 2 - Building the ANN {.unnumbered}
### Initializing the ANN
**Python**
```{python}
# ann = tf.keras.models.Sequential()
from tensorflow.keras.models import Sequential
ann = Sequential()
```
### Adding the input layer and the first hidden layer
**Python**
```{python}
ann.add(tf.keras.layers.Dense(units=6, activation='relu'))
```
### Adding the second hidden layer
**Python**
```{python}
ann.add(tf.keras.layers.Dense(units=6, activation='relu'))
```
### Adding the output layer
**Python**
```{python}
ann.add(tf.keras.layers.Dense(units=1, activation='sigmoid'))
```
### Part 3 - Training the ANN {.unnumbered}
### Compiling the ANN
**Python**
```{python}
ann.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
```
### Training the ANN on the Training set
**Python**
```{python, cache = TRUE}
ann.fit(X_train, y_train, batch_size = 32, epochs = 100)
```
**R**
```{r}
# install.packages('h2o')
library(h2o)
h2o.init(nthreads = -1)
model = h2o.deeplearning(y = 'Exited',
training_frame = as.h2o(training_set),
activation = 'Rectifier',
hidden = c(5,5),
epochs = 100,
train_samples_per_iteration = -2)
```
### Part 4 - Making the predictions and evaluating the model {.unnumbered}
### Predicting the result of a single observation
**Python**
```{python}
"""
Homework:
Use our ANN model to predict if the customer with the following informations will leave the bank:
Geography: France
Credit Score: 600
Gender: Male
Age: 40 years old
Tenure: 3 years
Balance: $ 60000
Number of Products: 2
Does this customer have a credit card? Yes
Is this customer an Active Member: Yes
Estimated Salary: $ 50000
So, should we say goodbye to that customer?
Solution:
"""
print(ann.predict(sc.transform([[1, 0, 0, 600, 1, 40, 3, 60000, 2, 1, 1, 50000]])) > 0.5)
"""
Therefore, our ANN model predicts that this customer stays in the bank!
Important note 1: Notice that the values of the features were all input in a double pair of square brackets. That's because the "predict" method always expects a 2D array as the format of its inputs. And putting our values into a double pair of square brackets makes the input exactly a 2D array.
Important note 2: Notice also that the "France" country was not input as a string in the last column but as "1, 0, 0" in the first three columns. That's because of course the predict method expects the one-hot-encoded values of the state, and as we see in the first row of the matrix of features X, "France" was encoded as "1, 0, 0". And be careful to include these values in the first three columns, because the dummy variables are always created in the first columns.
"""
```
### Predicting the Test set results
**Python**
```{python}
y_pred = ann.predict(X_test)
y_pred = (y_pred > 0.5)
print(np.concatenate((y_pred.reshape(len(y_pred),1), y_test.reshape(len(y_test),1)),1))
```
**R**
```{r}
y_pred = h2o.predict(model, newdata = as.h2o(test_set[-11]))
y_pred = (y_pred > 0.5)
y_pred = as.vector(y_pred)
```
### Making the Confusion Matrix
**Python**
```{python}
from sklearn.metrics import confusion_matrix, accuracy_score
cm = confusion_matrix(y_test, y_pred)
print(cm)
accuracy_score(y_test, y_pred)
```
**R**
```{r}
cm = table(test_set[, 11], y_pred)
```
```{r}
# h2o.shutdown()
```
## Convolutional Neural Network
### Importing the libraries
**Python**
```{python}
import tensorflow as tf
# from keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.preprocessing.image import ImageDataGenerator
tf.__version__
```
### Part 1 - Data Preprocessing {.unnumbered}
### Preprocessing the Training set
**Python**
```{python}
train_datagen = ImageDataGenerator(rescale = 1./255,
shear_range = 0.2,
zoom_range = 0.2,
horizontal_flip = True)
training_set = train_datagen.flow_from_directory('dataset/training_set',
target_size = (64, 64),
batch_size = 32,
class_mode = 'binary')
```
### Preprocessing the Test set
**Python**
```{python}
test_datagen = ImageDataGenerator(rescale = 1./255)
test_set = test_datagen.flow_from_directory('dataset/test_set',
target_size = (64, 64),
batch_size = 32,
class_mode = 'binary')
```
### Part 2 - Building the CNN {.unnumbered}
### Initialising the CNN
**Python**
```{python}
cnn = tf.keras.models.Sequential()
# from tensorflow.keras.models import Sequential
# cnn = Sequential()
```
#### Step 1 - Convolution {.unnumbered}
**Python**
```{python}
cnn.add(tf.keras.layers.Conv2D(filters=32, kernel_size=3, activation='relu', input_shape=[64, 64, 3]))
```
#### Step 2 - Pooling
**Python**
```{python}
cnn.add(tf.keras.layers.MaxPool2D(pool_size=2, strides=2))
```
### Adding a second convolutional layer
**Python**
```{python}
cnn.add(tf.keras.layers.Conv2D(filters=32, kernel_size=3, activation='relu'))
cnn.add(tf.keras.layers.MaxPool2D(pool_size=2, strides=2))
```
#### Step 3 - Flattening {.unnumbered}
**Python**
```{python}
cnn.add(tf.keras.layers.Flatten())
```
#### Step 4 - Full Connection {.unnumbered}
**Python**
```{python}
cnn.add(tf.keras.layers.Dense(units=128, activation='relu'))
```
#### Step 5 - Output Layer {.unnumbered}
**Python**
```{python}
cnn.add(tf.keras.layers.Dense(units=1, activation='sigmoid'))
```
### Part 3 - Training the CNN {.unnumbered}
### Compiling the CNN
**Python**
```{python}
cnn.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
```
### Training the CNN on the Training set and evaluating it on the Test set
**Python**
```{python, cache = TRUE}
cnn.fit(x = training_set, validation_data = test_set, epochs = 25)
```
### Part 4 - Making a single prediction {.unnumbered}
**Python**
```{python}
import numpy as np
# from keras.preprocessing import image
from tensorflow.keras.preprocessing import image
test_image = image.load_img('dataset/single_prediction/cat_or_dog_1.jpg', target_size = (64, 64))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis = 0)
result = cnn.predict(test_image)
training_set.class_indices
if result[0][0] == 1:
prediction = 'dog'
else:
prediction = 'cat'
print(prediction)
```