In the example, we provide the code that defines several functions and variables related to creating a convolutional neural network (CNN) model for image classification. The CNN model has two convolutional layers, each followed by a ReLU activation function and a max pooling layer, and a fully connected layer followed by a softmax activation function. The model is trained using the Adam optimizer with a specified learning rate and is evaluated using cross-entropy loss.
The code loads the MNIST dataset, preprocesses the data by normalizing the feature values, one-hot encodes the labels and converts the data into a format that can be used with TensorFlow’s tf.data
module. The tf.data
module is used to create a dataset object that can be used to efficiently feed data into a model during training.
Finally, the code defines a training loop that trains the model on the training data and evaluates it on the test data. The training loop includes a summary writer and a TensorBoard callback, which can be used to visualize the training process using TensorBoard.
Convolutional Neural Networks
Convolutional Neural Networks (CNNs) are a type of neural network designed specifically for image classification tasks. They are widely used in a variety of applications including object recognition, face detection, and medical image analysis.
CNNs consist of several layers of interconnected neurons, with each layer responsible for learning a specific set of features from the input data. The first layer of a CNN typically consists of convolutional filters that learn local features from the input image, such as edges and corners. The output of these convolutional filters is then passed through a pooling layer, which downsamples the output and helps to reduce the dimensionality of the data.
The output of the pooling layer is then fed into one or more fully connected (FC) layers, which learn more abstract features from the data and make the final prediction using a softmax activation function. The output of the softmax function is a probability distribution over the possible classes, with the class with the highest probability being the model’s prediction.
During the training process, the weights and biases of the CNN are adjusted using an optimization algorithm, such as Adam or Stochastic Gradient Descent (SGD), in order to minimize a loss function that measures the difference between the predicted and true labels. The trained CNN can then be used to make predictions on new, unseen data.
How to apply CNN to classify MNIST dataset
import tensorflow as tf
from IPython.display import Markdown, display
def printmd(string):
display(Markdown('# '+string+''))
#Import the MNIST dataset using TensorFlow built-in feature
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
#The features data are between 0 and 255, and we will normalize this to improve optimization performance.
x_train, x_test = x_train / 255.0, x_test / 255.0
#Let's take a look at the first few label values:
print(y_train[0:5])
#the same digits using one-hot vector representation can be show as:
print("categorical labels")
print(y_train[0:5])
# make labels one hot encoded
y_train = tf.one_hot(y_train, 10)
y_test = tf.one_hot(y_test, 10)
print("one hot encoded labels")
print(y_train[0:5])
print("number of training examples:" , x_train.shape[0])
print("number of test examples:" , x_test.shape[0])
train_ds = tf.data.Dataset.from_tensor_slices((x_train, y_train)).batch(50)
test_ds = tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(50)
#Converting a 2D Image into a 1D Vector
# showing an example of the Flatten class and operation
from tensorflow.keras.layers import Flatten
flatten = Flatten(dtype='float32')
"original data shape"
print(x_train.shape)
"flattened shape"
print(flatten(x_train).shape)
width = 28 # width of the image in pixels
height = 28 # height of the image in pixels
flat = width * height # number of pixels in one image
class_output = 10 # number of possible classifications for the problem
x_image_test = tf.reshape(x_test, [-1,28,28,1])
x_image_test = tf.cast(x_image_test, 'float32')
#creating new dataset with reshaped inputs
train_ds2 = tf.data.Dataset.from_tensor_slices((x_image_train, y_train)).batch(50)
test_ds2 = tf.data.Dataset.from_tensor_slices((x_image_test, y_test)).batch(50)
x_image_train = tf.slice(x_image_train,[0,0,0,0],[10000, 28, 28, 1])
y_train = tf.slice(y_train,[0,0],[10000, 10])
W_conv1 = tf.Variable(tf.random.truncated_normal([5, 5, 1, 32], stddev=0.1, seed=0))
b_conv1 = tf.Variable(tf.constant(0.1, shape=[32])) # need 32 biases for 32 outputs
def convolve1(x):
return(
tf.nn.conv2d(x, W_conv1, strides=[1, 1, 1, 1], padding='SAME') + b_conv1)
def h_conv1(x): return(tf.nn.relu(convolve1(x)))
def conv1(x):
return tf.nn.max_pool(h_conv1(x), ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1], padding='SAME')
W_conv2 = tf.Variable(tf.random.truncated_normal([5, 5, 32, 64], stddev=0.1, seed=1))
b_conv2 = tf.Variable(tf.constant(0.1, shape=[64])) #need 64 biases for 64 outputs
def convolve2(x):
return(
tf.nn.conv2d(conv1(x), W_conv2, strides=[1, 1, 1, 1], padding='SAME') + b_conv2)
def h_conv2(x): return tf.nn.relu(convolve2(x))
def conv2(x):
return(
tf.nn.max_pool(h_conv2(x), ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME'))
def layer2_matrix(x): return tf.reshape(conv2(x), [-1, 7 * 7 * 64])
W_fc1 = tf.Variable(tf.random.truncated_normal([7 * 7 * 64, 1024], stddev=0.1, seed = 2))
b_fc1 = tf.Variable(tf.constant(0.1, shape=[1024])) # need 1024 biases for 1024 outputs
def fcl(x): return tf.matmul(layer2_matrix(x), W_fc1) + b_fc1
def h_fc1(x): return tf.nn.relu(fcl(x))
keep_prob=0.5
def layer_drop(x): return tf.nn.dropout(h_fc1(x), keep_prob)
W_fc2 = tf.Variable(tf.random.truncated_normal([1024, 10], stddev=0.1, seed = 2)) #1024 neurons
b_fc2 = tf.Variable(tf.constant(0.1, shape=[10])) # 10 possibilities for digits [0,1,2,3,4,5,6,7,8,9]
def fc(x): return tf.matmul(layer_drop(x), W_fc2) + b_fc2
def y_CNN(x): return tf.nn.softmax(fc(x))
import numpy as np
layer4_test =[[0.9, 0.1, 0.1],[0.9, 0.1, 0.1]]
y_test=[[1.0, 0.0, 0.0],[1.0, 0.0, 0.0]]
np.mean( -np.sum(y_test * np.log(layer4_test),1))
def cross_entropy(y_label, y_pred):
return (-tf.reduce_sum(y_label * tf.math.log(y_pred + 1.e-10)))
optimizer = tf.keras.optimizers.Adam(1e-4)
variables = [W_conv1, b_conv1, W_conv2, b_conv2,
W_fc1, b_fc1, W_fc2, b_fc2, ]
def train_step(x, y):
with tf.GradientTape() as tape:
current_loss = cross_entropy( y, y_CNN( x ))
grads = tape.gradient( current_loss , variables )
optimizer.apply_gradients( zip( grads , variables ) )
return current_loss.numpy()
correct_prediction = tf.equal(tf.argmax(y_CNN(x_image_train), axis=1), tf.argmax(y_train, axis=1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, 'float32'))
loss_values=[]
accuracies = []
epochs = 1
for i in range(epochs):
j=0
# each batch has 50 examples
for x_train_batch, y_train_batch in train_ds2:
j+=1
current_loss = train_step(x_train_batch, y_train_batch)
if j%50==0: #reporting intermittent batch statistics
correct_prediction = tf.equal(tf.argmax(y_CNN(x_train_batch), axis=1),
tf.argmax(y_train_batch, axis=1))
# accuracy
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)).numpy()
print("epoch ", str(i), "batch", str(j), "loss:", str(current_loss),
"accuracy", str(accuracy))
current_loss = cross_entropy( y_train, y_CNN( x_image_train )).numpy()
loss_values.append(current_loss)
correct_prediction = tf.equal(tf.argmax(y_CNN(x_image_train), axis=1),
tf.argmax(y_train, axis=1))
# accuracy
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)).numpy()
accuracies.append(accuracy)
print("end of epoch ", str(i), "loss", str(current_loss), "accuracy", str(accuracy) )
j=0
acccuracies=[]
# evaluate accuracy by batch and average...reporting every 100th batch
for x_train_batch, y_train_batch in train_ds2:
j+=1
correct_prediction = tf.equal(tf.argmax(y_CNN(x_train_batch), axis=1),
tf.argmax(y_train_batch, axis=1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)).numpy()
#accuracies.append(accuracy)
if j%100==0:
print("batch", str(j), "accuracy", str(accuracy) )
import numpy as np
print("accuracy of entire set", str(np.mean(accuracies)))
The code then defines a function called train()
that takes in several arguments:
num_epochs
: the number of epochs to train the model for
train_ds
: the training dataset
test_ds
: the test dataset
loss_object
: an object representing the loss function to use during training
optimizer
: the optimizer to use during training
train_loss_results
: a list to store the training loss results for each epoch
train_accuracy_results
: a list to store the training accuracy results for each epoch
test_loss_results
: a list to store the test loss results for each epoch
test_accuracy_results
: a list to store the test accuracy results for each epoch
The train()
function first initializes some variables, such as the epoch number and the training and test datasets. It then enters a loop that iterates over the specified number of epochs. For each epoch, the function iterates over the training dataset and updates the model’s parameters using the optimizer. It also updates the training loss and accuracy results for the epoch.
After the training epoch is complete, the function evaluates the model on the test dataset and updates the test loss and accuracy results. The function then prints the training and test results for the epoch and returns the final training and test results.
The code then calls the train()
function to train the model for a specified number of epochs. It also creates a summary writer and a TensorBoard callback, which can be used to visualize the training process using TensorBoard.
Finally, the code plots the training and test loss and accuracy results to allow you to visualize how the model’s performance changed over the course of training.
Explain the code
x_image_train = tf.reshape(x_train, [-1,28,28,1])
x_image_train = tf.cast(x_image_train, 'float32')
x_image_test = tf.reshape(x_test, [-1,28,28,1])
x_image_test = tf.cast(x_image_test, 'float32')
In the above code , the x_image_train and x_image_test variables are created by reshaping and casting the x_train and x_test variables, respectively.
The reshaping is done using the tf.reshape() function, which reshapes the input tensor into a new shape. In this case, the input tensor is x_train or x_test, and the new shape is specified as [-1,28,28,1], which means that the tensor will be reshaped into a 4D tensor with shape [batch_size, height, width, num_channels], where batch_size is the size of the batch, height and width are the dimensions of the image, and num_channels is the number of channels (1 in this case, since the images are grayscale). The -1 value in the shape indicates that the size of the batch is determined automatically based on the size of the input tensor.
The casting is done using the tf.cast() function, which casts the input tensor to a new data type. In this case, the input tensor is x_image_train or x_image_test, and the new data type is ‘float32’. This is done to ensure that the tensor has the correct data type for use in the model.
After these operations, the x_image_train and x_image_test variables will contain the training and test data, respectively, in the form of 4D tensors with shape [batch_size, height, width, num_channels] and data type float32. These tensors can be used as input to the CNN model defined in the code.
train_ds2 = tf.data.Dataset.from_tensor_slices((x_image_train, y_train)).batch(50)
test_ds2 = tf.data.Dataset.from_tensor_slices((x_image_test, y_test)).batch(50)
In above code, the train_ds2
and test_ds2
variables are created using the tf.data.Dataset.from_tensor_slices()
function, which creates a dataset object from a tensor by slicing it along its first dimension.
The from_tensor_slices()
function takes in a tuple of tensors as input, and returns a dataset object that can be used to iterate over the tensors in slices. In this case, the input tensors are x_image_train
and y_train
for the train_ds2
dataset, and x_image_test
and y_test
for the test_ds2
dataset.
The batch()
function is then used to batch the data from the dataset object. This function groups the data into batches, with each batch having the specified batch size. In this case, the batch size is 50, which means that each batch will contain 50 examples from the dataset.
After these operations, the train_ds2
and test_ds2
variables will contain the training and test data, respectively, in the form of datasets that can be used to efficiently feed the data into the model during training and evaluation.
x_image_train = tf.slice(x_image_train,[0,0,0,0],[10000, 28, 28, 1])
y_train = tf.slice(y_train,[0,0],[10000, 10])
In the above code, the x_image_train
and y_train
variables are sliced using the tf.slice()
function. This function slices a tensor along its dimensions to extract a subset of the tensor.
The tf.slice()
function takes in the following arguments:
input_:
The input tensor to slice.
begin:
A list of int
or int32
tensors representing the starting indices of the slice for each dimension.
size:
A list of int
or int32
tensors representing the size of the slice for each dimension.
In this case, the input tensor is x_image_train
for the x_image_train
slice, and y_train
for the y_train
slice. The begin
argument is a list of starting indices, with each index representing the starting position for each dimension of the tensor. The size
argument is a list of sizes, with each size representing the number of elements to include in the slice for each dimension.
After slicing, the x_image_train
and y_train
variables will contain the first 10000 examples from the original x_image_train
and y_train
tensors, respectively. These slices can be used to train the model on a subset of the original data.
W_conv1 = tf.Variable(tf.random.truncated_normal([5, 5, 1, 32], stddev=0.1, seed=0))
b_conv1 = tf.Variable(tf.constant(0.1, shape=[32])) # need 32 biases for 32 outputs
def convolve1(x):
return(
tf.nn.conv2d(x, W_conv1, strides=[1, 1, 1, 1], padding='SAME') + b_conv1)
def h_conv1(x): return(tf.nn.relu(convolve1(x)))
def conv1(x):
return tf.nn.max_pool(h_conv1(x), ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1], padding='SAME')
W_conv2 = tf.Variable(tf.random.truncated_normal([5, 5, 32, 64], stddev=0.1, seed=1))
b_conv2 = tf.Variable(tf.constant(0.1, shape=[64])) #need 64 biases for 64 outputs
def convolve2(x):
return(
tf.nn.conv2d(conv1(x), W_conv2, strides=[1, 1, 1, 1], padding='SAME') + b_conv2)
def h_conv2(x): return tf.nn.relu(convolve2(x))
def conv2(x):
return(
tf.nn.max_pool(h_conv2(x), ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME'))
def layer2_matrix(x): return tf.reshape(conv2(x), [-1, 7 * 7 * 64])
In the above code, a series of functions are defined that perform convolution, activation, and pooling operations on the input tensor. These functions are used to create the first two convolutional layers of the CNN model.
The convolve1()
function performs convolution on the input tensor using the W_conv1
convolutional kernel and the b_conv1
bias vector. The strides
argument specifies the stride of the kernel as it moves over the input tensor, and the padding
argument specifies whether to pad the input tensor with zeros to prevent the kernel from going outside the bounds of the tensor. In this case, the stride is 1 and the padding is ‘SAME’, which means that the kernel will move over the input tensor in steps of 1 pixel and the input tensor will be padded with zeros to ensure that the kernel can be applied to all pixels of the input tensor.
The h_conv1()
function applies the ReLU activation function to the output of the convolve1()
function. The ReLU activation function is defined as f(x) = max(0, x)
, which means that it sets all negative values of x
to 0 and leaves all positive values unchanged. This function is used to introduce non-linearity into the model.
The conv1()
function applies max pooling to the output of the h_conv1()
function. Max pooling is a down-sampling operation that reduces the spatial size of the input tensor by taking the maximum value of each subregion of the tensor. The ksize
argument specifies the size of the pooling window, and the strides
argument specifies the stride of the window as it moves over the input tensor. In this case, the pooling window has a size of 2×2 and a stride of 2, which means that it will take the maximum value of each 2×2 subregion of the input tensor and the convolve2()
function is similar to the convolve1()
function, but it performs convolution on the output of the conv1()
function using the W_conv2
convolutional kernel and the b_conv2
bias vector.
The h_conv2()
function is similar to the h_conv1()
function, but it applies the ReLU activation function to the output of the convolve2()
function.
The conv2()
function is similar to the conv1()
function, but it applies max pooling to the output of the h_conv2()
function.
The layer2_matrix()
function reshapes the output of the conv2()
function into a 2D matrix with shape [batch_size, 7 * 7 * 64]
. This matrix will be used as the input to the fully-connected layers of the CNN model.
These functions will be used to create the first two convolutional layers of the CNN model, which will extract features from the input image and reduce its spatial size. The output of these layers will be fed into the fully-connected layers of the model, which will use the extracted features to make predictions.
W_fc1 = tf.Variable(tf.random.truncated_normal([7 * 7 * 64, 1024], stddev=0.1, seed = 2))
b_fc1 = tf.Variable(tf.constant(0.1, shape=[1024])) # need 1024 biases for 1024 outputs
In the above code, the W_fc1
and b_fc1
variables are defined using the tf.Variable
and tf.constant
functions, respectively. These variables are used in the first fully-connected (FC) layer of the CNN model.
The W_fc1
variable is a weight matrix that connects the input to the FC layer to the output of the FC layer. It has a shape of [7 * 7 * 64, 1024]
, which means that it has 7x7x64 input units and 1024 output units. The stddev
argument specifies the standard deviation of the truncated normal distribution from which the initial values of the weights are drawn, and the seed
argument specifies a seed for the random number generator used to draw the initial values.
The b_fc1
variable is a bias vector with 1024 elements, one for each output unit of the FC layer. The shape
argument specifies the shape of the bias vector, and the tf.constant()
function is used to create a constant tensor with the specified shape and a constant value of 0.1.
These variables will be used in the first FC layer of the CNN model to transform the input from the second convolutional layer into a higher-level representation that is used to make predictions.
def fcl(x): return tf.matmul(layer2_matrix(x), W_fc1) + b_fc1
def h_fc1(x): return tf.nn.relu(fcl(x))
keep_prob=0.5
def layer_drop(x): return tf.nn.dropout(h_fc1(x), keep_prob)
In the above code, a series of functions are defined that perform operations on the input tensor to create the first fully-connected (FC) layer of the CNN model.
The fcl()
function performs the matrix multiplication between the input to the FC layer and the W_fc1
weight matrix, and adds the b_fc1
bias vector. This operation transforms the input from the second convolutional layer into a higher-level representation that is used to make predictions.
The h_fc1()
function applies the ReLU activation function to the output of the fcl()
function. The ReLU activation function is defined as f(x) = max(0, x)
, which means that it sets all negative values of x
to 0 and leaves all positive values unchanged. This function is used to introduce non-linearity into the model.
The layer_drop()
function applies dropout to the output of the h_fc1()
function. Dropout is a regularization technique that randomly sets a fraction of the input units to 0 during training to prevent overfitting. The keep_prob
variable specifies the probability that an input unit will be kept. In this case, the keep_prob
variable is set to 0.5, which means that on average, half of the input units will be kept.
These functions will be used to create the first FC layer of the CNN model, which will transform the input from the second convolutional layer into a higher-level representation that is used to make predictions. The output of this layer will be fed into the next FC layer or the output layer of the model, depending on the architecture of the model.
W_fc2 = tf.Variable(tf.random.truncated_normal([1024, 10], stddev=0.1, seed = 2)) #1024 neurons
b_fc2 = tf.Variable(tf.constant(0.1, shape=[10])) # 10 possibilities for digits [0,1,2,3,4,5,6,7,8,9]
In the above code, the W_fc2
and b_fc2
variables are defined using the tf.Variable
and tf.constant
functions, respectively. These variables are used in the second fully-connected (FC) layer or the output layer of the CNN model, depending on the architecture of the model.
The W_fc2
variable is a weight matrix that connects the input to the FC layer or output layer to the output of the FC layer or output layer. It has a shape of [1024, 10]
, which means that it has 1024 input units and 10 output units. The stddev
argument specifies the standard deviation of the truncated normal distribution from which the initial values of the weights are drawn, and the seed
argument specifies a seed for the random number generator used to draw the initial values.
The b_fc2
variable is a bias vector with 10 elements, one for each output unit of the FC layer or output layer. The shape
argument specifies the shape of the bias vector, and the tf.constant()
function is used to create a constant tensor with the specified shape and a constant value of 0.1.
These variables will be used in the second FC layer or output layer of the CNN model to transform the input from the first FC layer or the output of the dropout layer into a higher-level representation that is used to make predictions. If the model has a second FC layer, the output of this layer will be fed into the output layer, which will use the extracted features to make predictions. If the model does not have a second FC layer, the output layer will use the output of the dropout layer to make predictions.
def fc(x): return tf.matmul(layer_drop(x), W_fc2) + b_fc2
def y_CNN(x): return tf.nn.softmax(fc(x))
In the above code, the fc()
and y_CNN()
functions are defined. These functions are used to create the second fully-connected (FC) layer or the output layer of the CNN model, depending on the architecture of the model.
The fc()
function performs the matrix multiplication between the input to the FC layer or output layer and the W_fc2
weight matrix, and adds the b_fc2
bias vector. This operation transforms the input from the first FC layer or the output of the dropout layer into a higher-level representation that is used to make predictions.
The y_CNN()
function applies the softmax activation function to the output of the fc()
function. The softmax activation function is defined as
f(x) = exp(x_i) / sum(exp(x_i))
where x_i
is the i-th element of the input tensor x
. The softmax function normalizes the output of the FC layer or output layer so that it sums to 1, which makes it suitable for use as a probability distribution over the possible classes.
These functions will be used to create the second FC layer or output layer of the CNN model, which will transform the input from the first FC layer or the output of the dropout layer into a higher-level representation that is used to make predictions. If the model has a second FC layer, the output of this layer will be fed into the output layer, which will use the extracted features to make predictions. If the model does not have a second FC layer, the output layer will use the output of the dropout layer to make predictions.
import numpy as np
layer4_test =[[0.9, 0.1, 0.1],[0.9, 0.1, 0.1]]
y_test=[[1.0, 0.0, 0.0],[1.0, 0.0, 0.0]]
np.mean( -np.sum(y_test * np.log(layer4_test),1))
In the above code, the layer4_test
and y_test
variables are defined as 2D numpy arrays. The layer4_test
array has two rows and three columns, and the y_test
array has two rows and three columns.
The np.mean()
function is applied to the result of -np.sum(y_test * np.log(layer4_test),1)
, which calculates the mean cross-entropy loss between the layer4_test
array and the y_test
array.
The cross-entropy loss is a measure of the difference between the predicted probability distribution and the true probability distribution. In this case, the predicted probability distribution is represented by the layer4_test
array, and the true probability distribution is represented by the y_test
array. The -np.sum(y_test * np.log(layer4_test),1)
expression calculates the cross-entropy loss between the layer4_test
and y_test
arrays element-wise, and the np.mean()
function calculates the mean of these losses.
The result of this code is a scalar value that represents the average cross-entropy loss between the layer4_test
and y_test
arrays. This value can be used to evaluate the performance of a model on a test set. A lower cross-entropy loss indicates a better fit between the predicted and true probability distributions, which usually translates to better model performance.
def cross_entropy(y_label, y_pred):
return (-tf.reduce_sum(y_label * tf.math.log(y_pred + 1.e-10)))
optimizer = tf.keras.optimizers.Adam(1e-4)
variables = [W_conv1, b_conv1, W_conv2, b_conv2,
W_fc1, b_fc1, W_fc2, b_fc2, ]
def train_step(x, y):
with tf.GradientTape() as tape:
current_loss = cross_entropy( y, y_CNN( x ))
grads = tape.gradient( current_loss , variables )
optimizer.apply_gradients( zip( grads , variables ) )
return current_loss.numpy()
In the above code, the cross_entropy()
and train_step()
functions are defined. These functions are used to train a CNN model on the MNIST dataset.
The cross_entropy()
function calculates the cross-entropy loss between the predicted probability distribution and the true probability distribution. The y_label
and y_pred
arguments represent the true probability distribution and the predicted probability distribution, respectively. The cross-entropy loss is calculated as
-sum(y_label * log(y_pred + 1.e-10))
where y_label
and y_pred
are tensors with the same shape. The + 1.e-10
term is added to the y_pred
tensor to avoid division by zero when calculating the logarithm.
The train_step()
function defines a single training step that updates the model’s weights and biases based on the gradient of the cross-entropy loss with respect to the model’s parameters. The x
and y
arguments represent the input features and labels, respectively. The tf.GradientTape()
context manager is used to record the gradient of the cross-entropy loss with respect to the model’s parameters. The current_loss
variable is calculated as the cross-entropy loss between the y
and y_CNN(x)
tensors. The grads
variable is calculated as the gradient of current_loss
with respect to the model’s parameters. The optimizer.apply_gradients()
function is used to apply the calculated gradients to the model’s parameters, which updates the model’s weights and biases. The current_loss
value is returned at the end of the function.
These functions will be used to train the CNN model on the MNIST dataset using gradient descent and the Adam optimizer. The Adam optimizer is an optimization algorithm that adapts the learning rate for each parameter based on the first and second moments of the gradients. This can help the model converge faster and with a lower error compared to other optimization algorithms.
correct_prediction = tf.equal(tf.argmax(y_CNN(x_image_train), axis=1), tf.argmax(y_train, axis=1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, 'float32'))
In the above code, the correct_prediction
and accuracy
variables are defined using TensorFlow operations. These variables are used to evaluate the performance of a trained CNN model on the MNIST dataset.
The correct_prediction
variable is a tensor that represents the correct predictions made by the model on the training set. The tf.argmax()
function is applied to the output of the y_CNN(x_image_train)
function, which returns the indices of the maximum values along the specified axis. In this case, the maximum value is taken along the column axis (axis=1), which corresponds to the predicted class for each example in the batch. The tf.equal()
function is then applied to the output of tf.argmax(y_CNN(x_image_train), axis=1)
and tf.argmax(y_train, axis=1)
, which compares the predicted class with the true class for each example in the batch. The result is a tensor of boolean values, which is cast to a tensor of floating-point values using the tf.cast()
function.
The accuracy
variable is a scalar value that represents the average accuracy of the model on the training set. The tf.reduce_mean()
function is applied to the correct_prediction
tensor, which calculates the mean of the boolean values contained in the tensor. The result is a scalar value that represents the average accuracy of the model on the training set, where a value of 1.0 indicates that the model made correct predictions for all the examples in the batch, and a value of 0.0 indicates that the model made incorrect predictions for all the examples in the batch.
These variables will be used to evaluate the performance of the trained CNN model on the MNIST dataset. The accuracy measure is a common metric used to evaluate the performance of a classification.
loss_values=[]
accuracies = []
epochs = 1
for i in range(epochs):
j=0
# each batch has 50 examples
for x_train_batch, y_train_batch in train_ds2:
j+=1
current_loss = train_step(x_train_batch, y_train_batch)
if j%50==0: #reporting intermittent batch statistics
correct_prediction = tf.equal(tf.argmax(y_CNN(x_train_batch), axis=1),
tf.argmax(y_train_batch, axis=1))
# accuracy
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)).numpy()
print("epoch ", str(i), "batch", str(j), "loss:", str(current_loss),
"accuracy", str(accuracy))
current_loss = cross_entropy( y_train, y_CNN( x_image_train )).numpy()
loss_values.append(current_loss)
correct_prediction = tf.equal(tf.argmax(y_CNN(x_image_train), axis=1),
tf.argmax(y_train, axis=1))
# accuracy
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)).numpy()
accuracies.append(accuracy)
print("end of epoch ", str(i), "loss", str(current_loss), "accuracy", str(accuracy) )
In above code, you are training a CNN model on the MNIST dataset using the train_ds2
and train_step
functions. The training process consists of several epochs, where an epoch is a complete pass through the training dataset. For each epoch, the training dataset is divided into smaller batches of examples, and the model is trained on each batch using the train_step
function.
The train_step
function applies the Adam optimization algorithm to the model parameters using the optimizer.apply_gradients()
function. The Adam optimization algorithm is a variant of stochastic gradient descent that uses an adaptive learning rate to improve optimization performance. The learning rate is adjusted based on the exponentially decaying average of the past gradients and the past squared gradients.
The train_step
function also calculates the current loss value and accuracy for each batch using the cross_entropy()
and tf.reduce_mean()
functions, respectively. The loss value is calculated as the cross-entropy loss between the true labels and the predicted labels, and the accuracy is calculated as the average of the correct predictions made by the model on the batch.
After each epoch, the final loss value and accuracy for the entire training dataset are calculated using the cross_entropy()
and tf.reduce_mean()
functions, respectively. The loss values and accuracies for each epoch are then stored in the loss_values
and accuracies
lists for later analysis.
j=0
acccuracies=[]
# evaluate accuracy by batch and average...reporting every 100th batch
for x_train_batch, y_train_batch in train_ds2:
j+=1
correct_prediction = tf.equal(tf.argmax(y_CNN(x_train_batch), axis=1),
tf.argmax(y_train_batch, axis=1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)).numpy()
accuracies.append(accuracy)
if j%100==0:
print("batch", str(j), "accuracy", str(accuracy) )
import numpy as np
print("accuracy of entire set", str(np.mean(accuracies)))
In above code, you are evaluating the accuracy of the trained CNN model on the MNIST training dataset using the train_ds2
dataset. For each batch of examples in train_ds2
, the model’s accuracy is calculated using the tf.reduce_mean()
function, which takes the average of the correct predictions made by the model on the batch.
The model’s accuracy is calculated by comparing the model’s predicted labels, which are obtained using the tf.argmax()
function on the output of the y_CNN()
function, with the true labels, which are obtained using the tf.argmax()
function on the y_train_batch
tensor. The tf.equal()
function is used to determine if the predicted labels and true labels are equal for each example in the batch.
After calculating the accuracy for each batch, the mean accuracy for the entire training dataset is calculated using the np.mean()
function on the accuracies
list. The mean accuracy is then printed to the console.
It is important to note that this code is only evaluating the model’s accuracy on the training dataset and not on the test dataset. It is generally a good practice to evaluate the model’s performance on a separate test dataset in order to get a more accurate assessment of the model’s generalization ability.
Conclusion
In this code, you have implemented a convolutional neural network (CNN) for classifying handwritten digits from the MNIST dataset. The CNN model consists of two convolutional layers with max pooling, a fully connected layer with dropout, and a final fully connected output layer.
You have also implemented an optimization procedure using the Adam optimizer to train the CNN model on the MNIST training dataset. The model’s performance is evaluated on the training dataset by calculating the mean accuracy on the training examples in each batch and averaging these values over all batches.
It is important to note that this code only evaluates the model’s accuracy on the training dataset and not on the test dataset. It is generally a good practice to evaluate the model’s performance on a separate test dataset in order to get a more accurate assessment of the model’s generalization ability.