VIDHYAI
HomeBlogTutorialsNewsAboutContact
VIDHYAI

Your Gateway to AI Knowledge

CONTENT

  • Blog
  • Tutorials
  • News

COMPANY

  • About
  • Contact

LEGAL

  • Privacy Policy
  • Terms of Service
  • Disclaimer
Home
Tutorials
Machine Learning
Introduction to Neural Networks
Introduction to Neural Networks and Deep Learning
Back to Introduction to Neural Networks
Lesson 1Beginner

Introduction to Neural Networks and Deep Learning

Explore how artificial neural networks work from scratch: neurons, weights, biases, activation functions, forward and backward propagation, and simple Python implementation.

October 17, 202622 min read31 views

Prerequisites

Before starting this lesson, make sure you've completed:

  • Gradient Descent – The Heart of ML Optimization
  • Logistic Regression for Binary Classification

What You'll Learn

  • Understand how biological brain neurons inspired artificial neurons (Perceptrons)
  • Break down the anatomy of a neural network: Input Layer, Hidden Layers, and Output Layer
  • Understand the role of Weights, Biases, and Activation Functions (ReLU, Sigmoid, Softmax)
  • Follow the complete learning cycle: Forward Propagation, Loss Computation, and Backpropagation
  • Understand Gradient Descent and how learning rate influences training
  • Build and train a simple neural network classifier in Python using scikit-learn and TensorFlow/Keras

The Magic of the Human Brain

When you look at a photograph of a cute golden retriever puppy, your eyes take in photons of light, send electrical signals into your brain, and in less than 0.2 seconds, you effortlessly recognize: "That's a dog!"

Yet for decades, even the world's most powerful supercomputers couldn't tell the difference between a dog and a cat with certainty. Why?

Traditional computer programs follow rigid, hand-coded rules:

if ears == pointy and whiskers == true:
    return "Cat"

In real life, however, a cat might be curled up in a ball, partially hidden under a blanket, or viewed from behind. Hand-crafted rules fail instantly.

To solve this, computer scientists asked a bold question:

What if, instead of writing millions of rules, we built a digital computer program structured like the human brain?

That breakthrough concept is the Artificial Neural Network (ANN)—the foundation of modern Deep Learning and modern Artificial Intelligence (including ChatGPT, self-driving cars, and facial recognition).


1. The Biological vs. Digital Neuron

Your brain contains roughly 86 billion biological neurons connected into a massive electrical network.

Biological Neuron:
Dendrites (Receive signals) ──> Cell Body / Soma (Processes) ──> Axon (Transmits output)

Artificial Neuron (Perceptron):
Input Features (x1, x2, x3) ──> Weighted Sum + Bias (Σ)  ──> Activation Function (f) ──> Output (y)
Biological Component Artificial Equivalent Role
Dendrites Inputs ($x_1, x_2, \dots$) Receive incoming data signals (e.g., pixel brightness, house age)
Synapses Weights ($w_1, w_2, \dots$) Control how important each incoming signal is
Cell Body (Soma) Summation ($\sum w_i x_i + b$) Combines all incoming signals and adds a baseline threshold (bias)
Action Potential Activation Function ($f$) Decides whether the neuron "fires" or stays quiet
Axon Output ($y$) Passes the processed signal to the next layer of neurons

2. A Day-in-the-Life Analogy: The Concert Decision

To understand the math of a single artificial neuron, let's look at a decision you might make on a Friday evening:

Question: "Should I go to the music concert tonight?"

You consider three input factors ($x$):

  1. $x_1$: Will the weather be good? (1 = Sunny, 0 = Heavy rain)
  2. $x_2$: Are my best friends going? (1 = Yes, 0 = No)
  3. $x_3$: Do I have an exam tomorrow morning? (1 = Yes, 0 = No)

Not all factors matter equally to you! Each factor gets an importance weight ($w$):

  • Suppose you care intensely about your grades: $w_3 = -5$ (huge negative impact!).
  • You enjoy hanging out with friends: $w_2 = +3$.
  • Weather doesn't bother you much: $w_1 = +1$.

The Math Inside the Neuron:

$$\text{Linear Combination } (z) = (x_1 \cdot w_1) + (x_2 \cdot w_2) + (x_3 \cdot w_3) + b$$

Where $b$ (Bias) represents your baseline tendency. If you are naturally a stay-at-home person, you might have a bias of $b = -2$. You need overwhelming positive reasons to go out!

If the sum $z$ exceeds 0, you go to the concert ($y = 1$). If $z \le 0$, you stay home ($y = 0$).

That simple equation: $$z = \sum_{i=1}^n w_i x_i + b$$ is the heartbeat of every single neuron inside every artificial neural network!


3. Architecture of an Artificial Neural Network

A single neuron can only solve simple, linear decisions. But when you connect hundreds or thousands of neurons into layers, magic happens!

 INPUT LAYER                HIDDEN LAYERS                  OUTPUT LAYER
 (Raw Data)              (Feature Extraction)              (Prediction)
 
   [ x1 ] ───────────────> ( Neuron 1 ) ──┐
             ╲         ╱                   ╲
              ╲       ╱                     ╲
   [ x2 ] ─────╳─────╳───> ( Neuron 2 ) ─────╳─────────────> [ Output: "Dog" (92%) ]
              ╱       ╲                     ╱
             ╱         ╲                   ╱
   [ x3 ] ───────────────> ( Neuron 3 ) ──┘
  1. Input Layer: Receives raw data (e.g., values of pixels in a $28 \times 28$ image). Does no computation.
  2. Hidden Layers: The "thinking core" of the network. Early hidden layers detect low-level details (edges, color gradients, lines). Deeper hidden layers combine those lines into complex shapes (eyes, noses, paws).
  3. Output Layer: Produces the final prediction (e.g., probabilities of classes like "Dog" vs. "Cat", or a predicted price).

What does "Deep Learning" mean?
"Deep" simply means having more than one hidden layer! A network with 3, 50, or 100 hidden layers is a Deep Neural Network.


4. Activation Functions: Adding the Spark of Non-Linearity

Why can't a neural network just multiply inputs by weights and add them up?

Because without an activation function, multiplying numbers and adding them together is purely linear algebra. Stacking 100 linear layers together is mathematically equivalent to just one single linear equation ($y = mx + c$)!

Linear equations can only draw straight lines or flat planes. Real-world data (faces, speech, language, tumors) is intensely curved and complex. Activation functions provide the curves.

The Most Important Activation Functions

1. ReLU (Rectified Linear Unit) — The Industry King 👑

$$f(z) = \max(0, z)$$

  • How it works: If the input is negative, output 0. If positive, leave it alone.
  • Why it's #1: It is blisteringly fast to compute on graphics cards (GPUs) and completely solves the vanishing gradient problem in deep networks. Used in almost all hidden layers today.

2. Sigmoid — The Probability Squeezer

$$f(z) = \frac{1}{1 + e^{-z}}$$

  • How it works: Takes any real number (from $-\infty$ to $+\infty$) and squashes it smoothly into a range between 0.0 and 1.0.
  • Best for: The output layer of binary classification models (e.g., predicting the probability of cancer).

3. Softmax — The Multi-Class Distributor

  • Takes a vector of raw scores from the output layer and turns them into clean probabilities that add up to exactly 1.0 (100%).
  • Best for: Multi-class classification (e.g., Dog: 80%, Cat: 15%, Bird: 5%).

5. How Neural Networks Learn: The 4-Step Cycle

When you create a brand-new neural network, all its weights ($w$) and biases ($b$) are initialized with random numbers. Naturally, its first guesses will be completely wrong!

How does it transform from a random guesser into a master predictor? Through an iterative 4-step loop:

┌────────────────────────────────────────────────────────────────────────┐
│                        THE TRAINING CYCLE                              │
│                                                                        │
│   1. FORWARD PROPAGATION                                               │
│      Input data travels forward through layers ──> Makes a Guess       │
│                                                                        │
│   2. LOSS COMPUTATION                                                  │
│      Calculate the error (Loss = Difference between Truth and Guess)   │
│                                                                        │
│   3. BACKPROPAGATION                                                   │
│      Send error backwards using Calculus (Chain Rule)                  │
│      Determine which weights caused the mistake                        │
│                                                                        │
│   4. GRADIENT DESCENT & OPTIMIZATION                                   │
│      Nudge all weights by a small step (Learning Rate) to reduce error │
│                                                                        │
│   RECYCLE for thousands of iterations (Epochs) until error is minimized│
└────────────────────────────────────────────────────────────────────────┘

Key Training Terminology Demystified

  • Loss Function: The mathematical ruler that measures how bad a guess was. For regression: Mean Squared Error (MSE). For classification: Binary Cross-Entropy.
  • Learning Rate ($\alpha$): How big of an adjustment you make to the weights after each mistake:
    • Too big ($\alpha = 0.5$): The model overshoots wildly and never converges.
    • Too small ($\alpha = 0.000001$): The model takes weeks to learn.
    • Typical sweet spot: $\alpha = 0.001$.
  • Epoch: One complete pass of the entire training dataset through the network.
  • Batch Size: The number of training examples processed at once before updating the weights (e.g., 32 or 64 samples).

Hands-On Python Implementation

Let's build, train, and test an Artificial Neural Network in Python.

First, using scikit-learn's built-in Multi-Layer Perceptron (MLPClassifier), which requires zero external heavy libraries:

import numpy as np
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import accuracy_score, classification_report

# Step 1: Create a non-linear "Two Moons" classification dataset
# Linear models fail on this dataset because the boundary is curved!
X, y = make_moons(n_samples=1000, noise=0.2, random_state=42)

# Step 2: Split into 80% Train and 20% Test sets
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)

# Step 3: Define the Neural Network Architecture
# - 2 Hidden Layers: First layer with 16 neurons, Second layer with 8 neurons
# - Activation: 'relu'
# - Optimizer: 'adam' (adaptive gradient descent)
# - max_iter: 500 epochs
nn_model = MLPClassifier(
    hidden_layer_sizes=(16, 8),
    activation='relu',
    solver='adam',
    learning_rate_init=0.01,
    max_iter=500,
    random_state=42
)

# Step 4: Train the Neural Network (Forward Prop + Backprop)
print("Training the Neural Network...")
nn_model.fit(X_train, y_train)

# Step 5: Evaluate Performance on Unseen Test Data
y_pred = nn_model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)

print(f"\nTest Accuracy: {accuracy * 100:.2f}%\n")
print("=== Classification Report ===")
print(classification_report(y_test, y_pred, target_names=["Moon A", "Moon B"]))

Output:

Training the Neural Network...

Test Accuracy: 97.50%

=== Classification Report ===
              precision    recall  f1-score   support

      Moon A       0.98      0.97      0.97        98
      Moon B       0.97      0.98      0.98       102

    accuracy                           0.97       200
   macro avg       0.98      0.98      0.97       200
weighted avg       0.98      0.98      0.97       200

The Equivalent Modern Deep Learning Architecture (Keras / TensorFlow)

In modern industry environments, you will frequently see the same structure written with tf.keras:

# Keras equivalent architecture:
import tensorflow as tf
from tensorflow.keras import layers, models

model = models.Sequential([
    layers.Dense(16, activation='relu', input_shape=(2,)),  # Hidden Layer 1
    layers.Dense(8, activation='relu'),                     # Hidden Layer 2
    layers.Dense(1, activation='sigmoid')                   # Output Layer (Binary probability)
])

model.compile(
    optimizer=tf.keras.optimizers.Adam(learning_rate=0.01),
    loss='binary_crossentropy',
    metrics=['accuracy']
)

# model.fit(X_train, y_train, epochs=100, batch_size=32)

When to Use Neural Networks vs. Traditional Machine Learning

Neural networks are remarkably capable, but they are not always the right tool for every job:

Scenario Choose Traditional ML (Random Forest, XGBoost) Choose Deep Neural Networks
Data Type Tabular, Excel sheets, SQL databases Images, Video, Audio, Raw Text (NLP)
Dataset Size Small to Medium (< 50,000 rows) Huge (100,000+ to millions of rows)
Compute Power Runs in seconds on a regular laptop CPU Requires dedicated GPUs / TPUs
Interpretability High (can inspect tree rules & feature importances) Low ("Black Box", difficult to inspect internal weights)
Feature Engineering Manual feature engineering needed Automatically learns features from raw data

Key Takeaways

  • An Artificial Neural Network is an array of interconnected mathematical nodes organized in layers, inspired by the biological architecture of the human brain.
  • A Perceptron computes a weighted sum of inputs, adds a bias threshold ($z = \sum w_i x_i + b$), and applies an activation function.
  • Activation Functions (especially ReLU) introduce non-linearity, allowing the network to capture complex, curved decision boundaries.
  • Networks learn through an elegant 2-step dance: Forward Propagation (making predictions) followed by Backpropagation (using gradient descent to adjust weights and minimize error).
  • While Deep Neural Networks reign supreme for vision, language, and audio, traditional models like Random Forest and XGBoost remain the champions for structured tabular datasets.
neural-networksdeep-learningartificial-intelligenceperceptronbackpropagationactivation-functionskerasmachine-learning
Back to Introduction to Neural Networks

Frequently Asked Questions

Related Lessons

1

Ensemble Methods in Machine Learning

Learn how ensemble methods combine multiple machine learning models to build super-predictors. Explore Bagging, Random Forest, Boosting, AdaBoost, XGBoost, and Stacking with intuitive real-world examples and Python code.

18 minIntermediate
2

Model Evaluation and Optimization in Machine Learning

Master the art of evaluating and fine-tuning machine learning models. Learn Train/Test splits, K-Fold Cross-Validation, Confusion Matrices, Precision, Recall, F1-Score, ROC-AUC, and Hyperparameter Tuning with Grid and Random Search.

20 minIntermediate

Prerequisites

Before starting this lesson, make sure you've completed:

  • Gradient Descent – The Heart of ML Optimization
  • Logistic Regression for Binary Classification

What You'll Learn

  • Understand how biological brain neurons inspired artificial neurons (Perceptrons)
  • Break down the anatomy of a neural network: Input Layer, Hidden Layers, and Output Layer
  • Understand the role of Weights, Biases, and Activation Functions (ReLU, Sigmoid, Softmax)
  • Follow the complete learning cycle: Forward Propagation, Loss Computation, and Backpropagation
  • Understand Gradient Descent and how learning rate influences training
  • Build and train a simple neural network classifier in Python using scikit-learn and TensorFlow/Keras