This Python Script Implements A Single
This Python Script Implements A Single
1. Importing Libraries
import tensorflow as tf
from tensorflow.keras.datasets import mnist
import matplotlib.pyplot as plt
tensorflow: The main library for building and training neural networks.
mnist: A dataset of 28x28 grayscale images of handwritten digits (0–9),
included in TensorFlow’s Keras API.
matplotlib.pyplot: Used to visualize the training progress by plotting the
loss (cost) over epochs.
model = tf.keras.Sequential([
tf.keras.layers.Dense(10, activation='softmax', input_shape=(784,))
])
The model is a single-layer perceptron built using Keras’ Sequential API:
o tf.keras.layers.Dense: A fully connected layer with:
10 units (one for each digit class, 0–9).
activation='softmax': Applies the softmax function to output
probabilities for each class, summing to 1.
input_shape=(784,): Specifies that each input is a 784-
dimensional vector (flattened image).
This is a simple neural network with no hidden layers, directly mapping
the 784 input features to 10 output classes.
model.compile(optimizer=tf.keras.optimizers.SGD(learning_rate=learning_rate)
,
loss='categorical_crossentropy',
metrics=['accuracy'])
optimizer='SGD': Uses Stochastic Gradient Descent with the specified
learning_rate (0.01) to update weights.
loss='categorical_crossentropy': The loss function, suitable for multi-class
classification with one-hot encoded labels. It measures the difference
between predicted and actual class probabilities.
metrics=['accuracy']: Tracks classification accuracy during training and
evaluation.
avg_set = []
epoch_set = []
for epoch in range(training_epochs):
avg_cost = 0.
total_batch = int(x_train.shape[0] / batch_size)
dataset = tf.data.Dataset.from_tensor_slices((x_train,
y_train)).batch(batch_size)
if epoch % display_step == 0:
print(f"Epoch: {epoch+1:04d} cost={avg_cost:.9f}")
avg_set.append(avg_cost)
epoch_set.append(epoch+1)
Initialization:
o avg_set and epoch_set: Lists to store the average loss and epoch
numbers for plotting.
o total_batch: Calculates the number of batches (60,000 training
samples / 100 = 600 batches).
Creating a dataset:
o tf.data.Dataset.from_tensor_slices((x_train, y_train)): Creates a
TensorFlow dataset from the training data.
o .batch(batch_size): Groups the data into batches of 100 samples.
Training loop:
o Iterates over training_epochs (25 times).
o For each epoch:
Loops through batches using the dataset.
model.train_on_batch(batch_xs, batch_ys): Trains the
model on one batch, returning the loss.
Accumulates the average loss (avg_cost) by summing batch
losses and dividing by total_batch.
o Every display_step (1) epoch, prints the epoch number and
average loss, and stores them in epoch_set and avg_set.
Output:
o Prints progress like Epoch: 0001 cost=0.123456789 to show how
the loss decreases over epochs.