Installing necessary libraries for nn creation
!pip install pydot graphviz tensorflow
Importing the libraries
import tensorflow as tf
from tensorflow.keras.utils import plot_model
Defining the nn
# define the input layer
input_layer = tf.keras.layers.Input(shape=(784,))
# define the hidden layer
hidden_layer = tf.keras.layers.Dense(units=128, activation='relu')(input_layer)
# define the output layer
output_layer = tf.keras.layers.Dense(units=10, activation='softmax')(hidden_layer)
Creating it
# create the model
model = tf.keras.Model(inputs=input_layer, outputs=output_layer)
# compile the model
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
Ploting the nn
plot_model(model,show_shapes=True, show_layer_names=True)
Training nn on MNIST dataset
# Load the MNIST dataset
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
# Reshape the input data to 784
x_train = x_train.reshape(-1, 784) / 255.0
x_test = x_test.reshape(-1, 784) / 255.0
# Convert the labels to one-hot encoding
y_train = tf.keras.utils.to_categorical(y_train)
y_test = tf.keras.utils.to_categorical(y_test)
# Train the model
model.fit(x_train, y_train, epochs=10, validation_data=(x_test, y_test))
Evaluating the nn on test dataset
import numpy as np
# Use the model to make predictions on test data
predictions = model.predict(x_test[:10])
# Get the predicted class labels for the first 10 images
predicted_labels = np.argmax(predictions, axis=1)
# Get the actual class labels for the first 10 images
actual_labels = np.argmax(y_test[:10], axis=1)
# Print the predicted and actual labels for the first 10 images
for i in range(10):
print("Image %d: Predicted label=%d, Actual label=%d" % (i+1, predicted_labels[i], actual_labels[i]))