-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMLP_mnist_tf.py
More file actions
71 lines (59 loc) · 2.08 KB
/
MLP_mnist_tf.py
File metadata and controls
71 lines (59 loc) · 2.08 KB
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
'''
ML Algorithm: Multilayer Perceptron
Deep Learning Framework: Tensorflow
Dataset: MNIST
Steps:
# Import Libraries
# Get dataset - train, validation data
# Define the model (Layers, activation)
# Compile the model (Optimizer, Loss function)
# Fit the model (trained data, epochs)
# Calculate the accuracy for train data, test data
# Predict the model output (test data)
'''
## Import the libraries
import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt
## Get the dataset - MNIST
mnist = keras.datasets.mnist
(train_images, train_labels),(test_images, test_labels) = mnist.load_data()
'''
A tuple of 2 tuples, each tuple containing 2 NumPy arrays
'''
## Define the model
model = keras.Sequential(
[
keras.layers.Flatten(input_shape = (28,28)),
keras.layers.Dense(128, activation = tf.nn.relu),
keras.layers.Dense(128, activation = tf.nn.relu),
keras.layers.Dense(10, activation = tf.nn.softmax)
]
)
model.summary()
## Compile the model
model.compile(optimizer = "adam", loss = "sparse_categorical_crossentropy", metrics = ["accuracy"])
'''
Losses: https://www.tensorflow.org/api_docs/python/tf/keras/losses
Optimizers: https://www.tensorflow.org/api_docs/python/tf/keras/optimizers
'''
## Model fitting
model.fit(train_images, train_labels, epochs = 5)
## Evaluate the model
# Calculate the accuracy of trained data
train_acc, train_loss = model.evaluate(train_images, train_labels)
print(f"Training Accuracy: {train_acc}")
# Calculate the accuracy of test data
test_acc, test_loss = model.evaluate(test_images, test_labels)
print(f"Test Accuracy: {test_acc}")
## Predict the test data
predict_labels = model.predict(test_images)
fig = plt.figure(figsize=(10,10))
for i in range(min(16, len(test_images))):
predict_label = predict_labels[i].argmax()
ax = fig.add_subplot(4, 4, i+1, xticks=[], yticks=[])
ax.imshow(test_images[i], cmap = plt.cm.binary)
color = "green" if predict_label == test_labels[i] else "red"
ax.set_title(f"Predict: {predict_label}, Actual: {test_labels[i]}", color=color)
plt.tight_layout()
plt.show()