Building a simple feedforward neural network using TensorFlow: Introduction to basic neural networks

Posted by

Basic Neural Networks with TensorFlow: Building a simple feedforward neural network

Neural networks are a fundamental aspect of machine learning and artificial intelligence. In this article, we will explore how to build a basic feedforward neural network using TensorFlow, a popular machine learning library developed by Google.

What is a feedforward neural network?

A feedforward neural network is one of the simplest types of neural networks. It consists of layers of neurons that are connected in such a way that the output from one neuron serves as the input to the next. The network is “feedforward” because the input flows through the network in one direction without any cycles or loops.

Building a simple feedforward neural network with TensorFlow

Let’s start by importing the TensorFlow library:

“`html


<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@3.9.0/dist/tf.min.js"></script>

“`

Next, we can define our neural network model. In this example, we will create a simple model with three layers: an input layer with 784 nodes (corresponding to a 28×28 pixel image), a hidden layer with 128 nodes, and an output layer with 10 nodes (corresponding to the 10 possible digits in the MNIST dataset).

“`html


<script>
    const model = tf.sequential();
    
    model.add(tf.layers.dense({units: 128, activation: 'relu', inputShape: [784]}));
    model.add(tf.layers.dense({units: 10, activation: 'softmax'}));
</script>

“`

Now we can compile the model, specifying the loss function, optimizer, and evaluation metric:

“`html


<script>
    model.compile({
        loss: 'categoricalCrossentropy',
        optimizer: 'adam',
        metrics: ['accuracy']
    });
</script>

“`

Finally, we can train the model on our data. For this example, we will use the MNIST dataset, which consists of 60,000 training images and 10,000 test images of handwritten digits. We will load the dataset using TensorFlow’s built-in data loader:

“`html


<script>
    const mnist = tf.data.mnist;
    const {images, labels} = tf.dataset.imagesDataset();
    
    model.fit(images, labels, {epochs: 10});
</script>

“`

And that’s it! We have successfully built a simple feedforward neural network using TensorFlow. This is just a basic example, but neural networks can be customized and optimized in many ways to solve a wide range of machine learning problems. Experiment with different architectures, activation functions, and optimization algorithms to see how they affect the model’s performance.

Happy coding!