|
1 | 1 | """
|
2 | 2 | Fully Connected Neural Network for MNIST Classification
|
3 | 3 |
|
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. |
7 | 9 |
|
8 | 10 | Objectives:
|
9 | 11 | - Normalize and preprocess MNIST data.
|
10 | 12 | - 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 | +
|
12 | 16 | """
|
13 | 17 |
|
| 18 | +import numpy as np |
14 | 19 | import tensorflow as tf
|
15 | 20 | from tensorflow.keras import layers, models
|
16 |
| -import numpy as np |
| 21 | + |
17 | 22 |
|
18 | 23 | # Load the MNIST dataset from Keras
|
19 | 24 | mnist = tf.keras.datasets.mnist
|
|
42 | 47 | # Second hidden layer with 64 neurons and ReLU activation
|
43 | 48 | model.add(layers.Dense(64, activation="relu"))
|
44 | 49 |
|
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 |
46 | 52 | model.add(layers.Dense(10, activation="softmax"))
|
47 | 53 |
|
48 | 54 | # Compile the model
|
49 | 55 | model.compile(
|
50 |
| - optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"] |
| 56 | + optimizer="adam", loss="sparse_categorical_crossentropy", |
| 57 | + metrics=["accuracy"] |
51 | 58 | )
|
52 | 59 |
|
53 | 60 | # Train the model on the MNIST training data
|
|
58 | 65 | print(f"\nTest accuracy: {test_acc}")
|
59 | 66 |
|
60 | 67 | # 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)) |
62 | 70 | random_image = np.expand_dims(X_test[random_index], axis=0)
|
63 | 71 | prediction = model.predict(random_image)
|
64 | 72 | predicted_digit = np.argmax(prediction)
|
|
0 commit comments