DEV Community

Cover image for Artificial Neural Networks (ANN): A Beginner’s Guide with Python
nuz14
nuz14

Posted on Edited on AI-assisted

Artificial Neural Networks (ANN): A Beginner’s Guide with Python

Artificial Intelligence is becoming an important part of our everyday lives. From voice assistants and recommendation systems to image recognition, many modern technologies use neural networks to perform intelligent tasks.

One of the fundamental concepts behind these technologies is the Artificial Neural Network (ANN).

In this article, we will understand what artificial neural networks are, how they work, their basic structure, and how to build a simple neural network using Python.

What is an Artificial Neural Network?

An Artificial Neural Network is a machine learning model inspired by the way the human brain processes information.

The human brain contains neurons that communicate with each other. Similarly, an artificial neural network contains interconnected units called artificial neurons.

These neurons receive information, process it, and pass the results to other neurons.

An ANN learns from data by adjusting the connections between its neurons. After training, it can use what it has learned to make predictions on new data.

For example, an ANN can be trained to identify whether an email is spam or not spam by learning patterns from previously labelled emails.

Structure of an Artificial Neural Network

An artificial neural network generally consists of three main layers.

1. Input Layer

The input layer receives information from the dataset.

For example, if we are predicting house prices, the input features could include:

  • House size
  • Number of bedrooms
  • Location
  • Age of the property

Each input feature is passed into the network.

2. Hidden Layer

The hidden layer processes the information received from the input layer.

It contains neurons that perform calculations using weights and biases. Activation functions are also applied to help the network learn complex patterns.

A neural network can have one or multiple hidden layers.

3. Output Layer

The output layer produces the final prediction.

For example:

  • Predicting house prices produces a numerical value.
  • Spam detection produces a category such as spam or not spam.
  • Image classification produces a predicted image category.

How Does an Artificial Neural Network Work?

An artificial neural network works through a series of steps.

  1. Input data is provided to the network.
  2. Each input is multiplied by a weight.
  3. A bias is added to the result.
  4. An activation function processes the calculated value.
  5. The information moves through the network to produce an output.
  6. The predicted output is compared with the actual result.
  7. The network adjusts its weights to reduce prediction errors.

This process is repeated during training until the network learns useful patterns from the data.

Important Concepts in ANN

Before implementing an artificial neural network, let's understand some important terms.

Weights: Weights determine the importance of different inputs. During training, the network adjusts these values.

Bias: Bias is an additional value that helps the network adjust its output.

Activation Function: An activation function helps a neuron decide what information to pass forward. Common activation functions include ReLU, Sigmoid, and Tanh.

Forward Propagation: The process of passing input data through the network to generate a prediction.

Backpropagation: The process of calculating prediction errors and using them to adjust the network's weights.

Epoch: One complete pass through the entire training dataset.

Building an Artificial Neural Network Using Python

Now let's build a simple Artificial Neural Network using Python.

For this example, we will use the Iris dataset. This dataset contains information about three types of flowers. Our goal is to train the neural network to identify the correct flower species.

We will use Scikit-learn, a Python library that provides tools for machine learning.

Step 1: Import the libraries

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import accuracy_score
Enter fullscreen mode Exit fullscreen mode

What are these libraries used for?

  • load_iris: Loads the flower dataset.
  • train_test_split: Divides the data into training and testing parts.
  • StandardScaler: Scales the input values.
  • MLPClassifier: Creates an artificial neural network.
  • accuracy_score: Calculates how many predictions are correct.

Step 2: Load the dataset

iris = load_iris()

X = iris.data
y = iris.target

print(X[:5])
print(y[:5])
Enter fullscreen mode Exit fullscreen mode

Understanding the code:

  • iris.data contains the flower measurements.
  • iris.target contains the actual flower categories.
  • X represents the input data.
  • y represents the answers we want the model to learn.

The dataset contains four measurements for each flower: sepal length, sepal width, petal length, and petal width.

Step 3: Divide the dataset

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)
Enter fullscreen mode Exit fullscreen mode

We divide the dataset into two parts:

  • Training data (80%): Used to teach the model.
  • Testing data (20%): Used to check how well the model performs on new data.

random_state=42 keeps the split consistent when we run the program again.

Step 4: Scale the data

scaler = StandardScaler()

X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
Enter fullscreen mode Exit fullscreen mode

Why do we scale the data?

The measurements in a dataset may have different ranges. Scaling brings them to a similar range so that the neural network can learn more effectively.

We use fit_transform() on the training data to calculate and apply scaling. We use transform() on the testing data to apply the same scaling.

Step 5: Create the neural network

model = MLPClassifier(
    hidden_layer_sizes=(10,),
    max_iter=1000,
    random_state=42
)
Enter fullscreen mode Exit fullscreen mode

Here, we create our artificial neural network.

  • MLPClassifier: Creates a neural network for classification.
  • hidden_layer_sizes=(10,): Creates one hidden layer containing 10 neurons.
  • max_iter=1000: Allows the model up to 1,000 training iterations.

Step 6: Train the model

model.fit(X_train, y_train)

print("Model training completed!")
Enter fullscreen mode Exit fullscreen mode

The fit() function trains the neural network using the training data.

During training, the model learns patterns from flower measurements and their corresponding categories.

Step 7: Make predictions

predictions = model.predict(X_test)

print("Predicted values:", predictions)
print("Actual values:", y_test)
Enter fullscreen mode Exit fullscreen mode

The predict() function uses the trained model to identify the flower categories in the testing data.

We print both predicted and actual values to compare the results.

Step 8: Check the accuracy

accuracy = accuracy_score(y_test, predictions)

print("Model Accuracy:", accuracy * 100, "%")
Enter fullscreen mode Exit fullscreen mode

Accuracy tells us how many predictions the model got correct out of all the test predictions.

For example, an accuracy of 95% means the model correctly predicted 95 out of every 100 test samples.

The actual result may vary depending on the model settings and dataset split.

Complete Python Code

Here is the complete program in one place:

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import accuracy_score

# Load dataset
iris = load_iris()
X = iris.data
y = iris.target

# Split dataset
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)

# Scale data
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

# Create neural network
model = MLPClassifier(
    hidden_layer_sizes=(10,),
    max_iter=1000,
    random_state=42
)

# Train model
model.fit(X_train, y_train)

# Make predictions
predictions = model.predict(X_test)

# Calculate accuracy
accuracy = accuracy_score(y_test, predictions)

print("Predictions:", predictions)
print("Actual values:", y_test)
print("Accuracy:", accuracy * 100, "%")
Enter fullscreen mode Exit fullscreen mode

This program demonstrates the basic working of an Artificial Neural Network, from loading data to training the model and evaluating its predictions.

Applications of Artificial Neural Networks

Artificial neural networks are used in many real-world applications.

  • Image Recognition: Identifying objects, faces, and patterns in images.
  • Healthcare: Supporting medical image analysis and disease prediction.
  • Finance: Detecting suspicious transactions and identifying unusual patterns.
  • Recommendation Systems: Suggesting products, movies, and other content.
  • Speech Recognition: Helping computers understand spoken language.

Advantages and Limitations of ANN

Advantages

  • Can learn complex patterns from data.
  • Useful for classification and prediction tasks.
  • Can work with large and complex datasets.
  • Can improve performance through training.

Limitations

  • Often requires a large amount of training data.
  • Training can be computationally expensive.
  • Choosing the right network structure can be challenging.
  • Its predictions can be difficult to interpret.

Conclusion

Artificial Neural Networks are an important part of modern machine learning. They learn patterns from data by using interconnected neurons, weights, biases, and activation functions.

In this article, we explored the structure and working of an ANN and built a basic classification model using Python and Scikit-learn.

Understanding artificial neural networks provides a strong foundation for learning more advanced deep learning concepts.

In the next article, we will explore Convolutional Neural Networks (CNNs) and understand how computers learn to recognize images.

Top comments (0)