|
| 1 | +# Learner: Nguyen Truong Thinh |
| 2 | +# Contact me: [email protected] || +84393280504 |
| 3 | +# |
| 4 | +# Topic: Deep Learning: Taming Deep Networks |
| 5 | +# MNIST classifier (10 epochs, Rectified linear unit, Batch Normalization, & Adam optimizer) |
| 6 | +# - a deep neural network written in Keras. |
| 7 | + |
| 8 | +import numpy as np |
| 9 | + |
| 10 | +from keras.datasets import mnist |
| 11 | +from keras.models import Sequential |
| 12 | +from keras.layers import Dense, BatchNormalization |
| 13 | +from keras.optimizers import Adam |
| 14 | +from keras.utils import to_categorical |
| 15 | + |
| 16 | +from ml.deep_learning.neural_network_keras.decision_boundaries import decision_boundary_2dimensional as boundary |
| 17 | + |
| 18 | +(X_train_raw, Y_train_raw), (X_test_raw, Y_test_raw) = mnist.load_data() |
| 19 | + |
| 20 | +X_train = X_train_raw.reshape(X_train_raw.shape[0], -1) / 255 |
| 21 | +X_test_all = X_test_raw.reshape(X_test_raw.shape[0], -1) / 255 |
| 22 | +X_validation, X_test = np.split(X_test_all, 2) |
| 23 | +Y_train_encoded = to_categorical(Y_train_raw) |
| 24 | +Y_validation_encoded, Y_test = np.split(to_categorical(Y_test_raw), 2) |
| 25 | + |
| 26 | +# Create a sequential model |
| 27 | +model = Sequential() |
| 28 | +model.add(Dense(1200, activation='relu')) |
| 29 | +model.add(BatchNormalization()) |
| 30 | +model.add(Dense(500, activation='relu')) |
| 31 | +model.add(BatchNormalization()) |
| 32 | +model.add(Dense(200, activation='relu')) |
| 33 | +model.add(BatchNormalization()) |
| 34 | +model.add(Dense(10, activation='softmax')) |
| 35 | + |
| 36 | +# Compile a model |
| 37 | +model.compile( |
| 38 | + loss='categorical_crossentropy', |
| 39 | + optimizer=Adam(), |
| 40 | + metrics=['accuracy'] |
| 41 | +) |
| 42 | + |
| 43 | +# Train a network |
| 44 | +history = model.fit( |
| 45 | + X_train, |
| 46 | + Y_train_encoded, |
| 47 | + validation_data=(X_validation, Y_validation_encoded), |
| 48 | + epochs=10, |
| 49 | + batch_size=32 |
| 50 | +) |
| 51 | +# Epoch 10/10 1875/1875 [==============================] - 10s 5ms/step - loss: 0.0293 - accuracy: 0.9898 - val_loss: |
| 52 | +# 0.1101 - val_accuracy: 0.9722 |
| 53 | + |
| 54 | +# Draw a decision boundary |
| 55 | +boundary.plot(history) |
0 commit comments