Feed Forward

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

4 .

IMPLEMENT A FEED FORWARD IN TENSOR FLOW KERAS

Aim:

To Write a python program to implement a perceptron in tensorflowkeras

Envionment.

Algorithm:

1.Import the necessary libraries for working with TensorFlow and Keras.

2.Load the MNIST dataset using the mnist.load_data() function. This gives you
two tuples: (x_train, y_train) and (x_test, y_test) containing the training and testing
data respectively.

3.Create a Sequential model using Sequential(). This means that you're building a
linear stack of layers.

4.using the compile() method. Specify the optimizer (e.g., 'adam'), the loss function
(e.g., 'categorical_crossentropy' for multi-class classification), and the evaluation
metrics (e.g., 'accuracy').

5.Train the model using the fit() method. Provide the training data (x_train and
y_train), set the number of epochs (e.g., 5), and specify the batch size (e.g., 32) for
each training iteration. You can also use the validation data (x_test and y_test) to
monitor the model's performance during training.

6.After training, you can use the trained model to make predictions on new data.

7.To get the predicted class for a test example, use the argmax() function to find
the index of the class with the highest predicted probability. Print the predicted
class.
8.You can experiment with different architectures, activation functions, optimizer
settings, and hyperparameters to improve the model's performance

Program:
import tensorflow as tf

from tensorflow.keras.models import Sequential

from tensorflow.keras.layers import Dense, Flatten

from tensorflow.keras.datasets import mnist

from tensorflow.keras.utils import to_categorical

# Load and preprocess the MNIST dataset

(x_train, y_train), (x_test, y_test) = mnist.load_data()

x_train, x_test = x_train / 255.0, x_test / 255.0

y_train = to_categorical(y_train, num_classes=10)

y_test = to_categorical(y_test, num_classes=10)

# Create a feed-forward neural network

model = Sequential([

Flatten(input_shape=(28, 28)),

Dense(128, activation='relu'),

Dense(64, activation='relu'),

Dense(10, activation='softmax')

])
# Compile the model

model.compile(optimizer='adam', loss='categorical_crossentropy',
metrics=['accuracy'])

# Train the model

model.fit(x_train, y_train, epochs=5, batch_size=32, validation_data=(x_test,


y_test))

# Make predictions

predictions = model.predict(x_test)

# Print the predicted class for the first test example

predicted_class = tf.argmax(predictions[0]).numpy()
OUTPUT:
print("Predicted class:", predicted_class)

You might also like