Skip to content

Commit 83e5295

Browse files
committed
fully_connected_mnist.py: For the basic fully connected neural network.
1 parent c004e54 commit 83e5295

File tree

1 file changed

+16
-8
lines changed

1 file changed

+16
-8
lines changed

machine_learning/neural_networks/fully_connected_mnist.py

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,24 @@
11
"""
22
Fully Connected Neural Network for MNIST Classification
33
4-
Goal: This script implements a fully connected feed-forward neural network using TensorFlow and Keras to classify the
5-
MNIST dataset (28x28 grayscale images of handwritten digits from 0 to 9). The network has two hidden layers with ReLU
6-
activations and dropout for regularization.
4+
Goal: This script implements a fully connected feed-forward neural network
5+
using TensorFlow and Keras to classify the MNIST dataset
6+
(28x28 grayscale images of handwritten digits from 0 to 9).
7+
The network has two hidden layers with ReLU activations and dropout
8+
for regularization.
79
810
Objectives:
911
- Normalize and preprocess MNIST data.
1012
- Build a basic neural network with dense layers.
11-
- Train the model, evaluate its accuracy and loss at each epoch, and predict sample outputs.
13+
- Train the model, evaluate its accuracy and loss at each epoch,
14+
and predict sample outputs.
15+
1216
"""
1317

18+
import numpy as np
1419
import tensorflow as tf
1520
from tensorflow.keras import layers, models
16-
import numpy as np
21+
1722

1823
# Load the MNIST dataset from Keras
1924
mnist = tf.keras.datasets.mnist
@@ -42,12 +47,14 @@
4247
# Second hidden layer with 64 neurons and ReLU activation
4348
model.add(layers.Dense(64, activation="relu"))
4449

45-
# Output layer with 10 neurons (one for each digit class 0-9), softmax for probabilities
50+
# Output layer with 10 neurons (one for each digit class 0-9),
51+
# softmax for probabilities
4652
model.add(layers.Dense(10, activation="softmax"))
4753

4854
# Compile the model
4955
model.compile(
50-
optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"]
56+
optimizer="adam", loss="sparse_categorical_crossentropy",
57+
metrics=["accuracy"]
5158
)
5259

5360
# Train the model on the MNIST training data
@@ -58,7 +65,8 @@
5865
print(f"\nTest accuracy: {test_acc}")
5966

6067
# Make a prediction on a random test image
61-
random_index = np.random.randint(0, len(X_test))
68+
rng = np.random.default_rng()
69+
random_index = rng.integers(0, len(X_test))
6270
random_image = np.expand_dims(X_test[random_index], axis=0)
6371
prediction = model.predict(random_image)
6472
predicted_digit = np.argmax(prediction)

0 commit comments

Comments
 (0)