Implementing a FeedForward Neural Network with TensorFlow and Keras

Posted by


In this tutorial, we will learn about how to build a feedforward neural network using TensorFlow and Keras. A feedforward neural network is a basic type of artificial neural network, where the information flows in only one direction, from the input nodes through the hidden layers to the output nodes.

Step 1: Install TensorFlow and Keras
First, you need to install TensorFlow and Keras. Open your terminal and run the following command:

pip install tensorflow
pip install keras

Step 2: Import the necessary libraries
Create a new Python script and import the necessary libraries:

import numpy as np
from keras.models import Sequential
from keras.layers import Dense

Step 3: Prepare the dataset
Next, let’s create a dataset for training our neural network. We will use a simple classification dataset where each input has two features (X1, X2) and the output is a binary label (0 or 1).

X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([0, 1, 1, 0])

Step 4: Build the neural network model
Now, let’s build a feedforward neural network with one hidden layer. We will use the Sequential model in Keras to do this.

model = Sequential()
model.add(Dense(4, input_dim=2, activation='relu'))
model.add(Dense(1, activation='sigmoid'))

In the above code, we added a Dense layer with 4 neurons and ‘relu’ activation function as the input layer, and another Dense layer with 1 neuron and ‘sigmoid’ activation function as the output layer.

Step 5: Compile the model
Next, we need to compile our model by specifying the loss function, optimizer, and metric to use during training.

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

Step 6: Train the model
Now, we can train our model on the dataset we prepared earlier.

model.fit(X, y, epochs=100, batch_size=2)

In the above code, we are training the model for 100 epochs with a batch size of 2.

Step 7: Evaluate the model
Finally, let’s evaluate the performance of our model on the dataset.

scores = model.evaluate(X, y)
print("n%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))

Step 8: Make predictions
You can use the trained model to make predictions on new data.

predictions = model.predict(X)

Congratulations! You have successfully built a feedforward neural network using TensorFlow and Keras. Feel free to experiment with different architectures, datasets, and hyperparameters to improve the performance of your neural network.

0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x