Implement A Neural Network Using Python
Implement A Neural Network Using Python
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.
If you haven't already, you'll need to install TensorFlow. You can do this
via pip:
Bash:
pip install tensorflow
Python Code:
import tensorflow as tf
import numpy as np
Python Code:
mnist = keras.datasets.mnist
x_train.astype("float32") / 255.0
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))
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
Python Code:
model.compile(optimizer='adam',
loss='categorical_crossentro
py', metrics=['accuracy'])
Step 7: Train the Model
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
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
Python Code:
# Make predictions
predictions = model.predict(x_test)