0% found this document useful (0 votes)
22 views4 pages

Implement A Neural Network Using Python

This document outlines a simple implementation of a feed forward neural network using TensorFlow and Keras for classifying handwritten digits from the MNIST dataset. It covers steps including library installation, data loading and preprocessing, model building and compilation, training, evaluation, and making predictions. The process is demonstrated with Python code snippets for each step.

Uploaded by

Live Channel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views4 pages

Implement A Neural Network Using Python

This document outlines a simple implementation of a feed forward neural network using TensorFlow and Keras for classifying handwritten digits from the MNIST dataset. It covers steps including library installation, data loading and preprocessing, model building and compilation, training, evaluation, and making predictions. The process is demonstrated with Python code snippets for each step.

Uploaded by

Live Channel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Let’s walk through a simple implementation of a neural network using

Python with the help of the popular library TensorFlow and Keras.
This example will demonstrate a basic feed forward neural network for
a classification task using the well-known MNIST dataset of handwritten
digits.

Step 1: Install Required Libraries

If you haven't already, you'll need to install TensorFlow. You can do this
via pip:

Bash:
pip install tensorflow

Step 2: Import Libraries

Start by importing the necessary libraries:

Python Code:

import tensorflow as tf

from tensorflow import keras

from tensorflow.keras import layers

import numpy as np

import matplotlib.pyplot as plt

Step 3: Load the MNIST Dataset

The MNIST dataset is included in Keras, making it easy to load.

Python Code:

# Load the dataset

mnist = keras.datasets.mnist

# Split into training and testing sets


(x_train, y_train), (x_test, y_test) =

mnist.load_data() # Normalize the images to

values between 0 and 1 x_train =

x_train.astype("float32") / 255.0

x_test = x_test.astype("float32") / 255.0

Step 4: Preprocess the Data

You need to flatten the images and convert the labels to one-hot encoding.

Python Code:
# Flatten the images (28x28 to 784)
x_train = x_train.reshape((x_train.shape[0], 28 * 28))
x_test = x_test.reshape((x_test.shape[0], 28 * 28))

# Convert labels to one-hot encoding


y_train = keras.utils.to_categorical(y_train,
10) y_test =
keras.utils.to_categorical(y_test, 10)

Step 5: Build the Neural Network

Now, you can define your neural network architecture. Here, we’ll create a
simple model with one hidden layer.

Python Code:
# Define the model
model = keras.Sequential([
layers.Dense(128, activation='relu', input_shape=(784,)), # Hidden
layer layers.Dense(10, activation='softmax') # Output layer
])
Step 6: Compile the Model

Choose a loss function, optimizer, and metrics for evaluation.

Python Code:
model.compile(optimizer='adam',
loss='categorical_crossentro
py', metrics=['accuracy'])
Step 7: Train the Model

Train the model using the training data.

Python Code:
# Train the model
model.fit(x_train, y_train, epochs=5, batch_size=32,
validation_split=0.2)
Step 8: Evaluate the Model

After training, evaluate the model's performance on the test dataset.

Python Code:
# Evaluate the model
test_loss, test_acc = model.evaluate(x_test, y_test,
verbose=2) print(f'\nTest accuracy: {test_acc}')
Step 9: Make Predictions

It can also use the model to make predictions on new data.

Python Code:
# Make predictions
predictions = model.predict(x_test)

# Show the prediction for the first test image


print(f'Predicted label:
{np.argmax(predictions[0])}')
plt.imshow(x_test[0].reshape(28, 28),
cmap='gray') plt.title(f'Predicted:
{np.argmax(predictions[0])}') plt.show()
Summary:

This is a straightforward implementation of a neural network for classifying


handwritten digits using the MNIST dataset. Here’s a breakdown of the
steps:

1. Data Loading: The MNIST dataset is loaded and normalized.


2. Preprocessing: Images are flattened, and labels are converted to
one-hot encoding.
3. Model Building: A simple neural network with one hidden layer is
defined.
4. Model Compilation: The model is compiled with an optimizer and loss
function.
5. Training: The model is trained on the training dataset.
6. Evaluation: The model's accuracy is evaluated on the test dataset.
7. Prediction: Predictions are made on new data, and results are
visualized.

You might also like