Home Topics Neural Networks

Neural Networks

The foundation of Deep Learning

10 hours 20 examples Intermediate
Beginner

What is a Neural Network?

A Neural Network is a computing system inspired by the human brain. It consists of interconnected nodes (neurons) that process information by passing signals between layers.

Brain vs. Artificial Neural Network

🧠 Human Brain
  • • 86 billion neurons
  • • Learning through experience
  • • Pattern recognition
  • • Parallel processing
šŸ¤– Artificial NN
  • • Millions of parameters
  • • Learning from data
  • • Feature extraction
  • • GPU acceleration

Network Structure: Layers

šŸ“„

Input Layer

Receives raw data (pixels, numbers, text)

āš™ļø

Hidden Layers

Process and transform data. More layers = "deeper" network

šŸ“¤

Output Layer

Produces final prediction or classification

Beginner

The Perceptron: Simplest Neuron

A perceptron is a single artificial neuron - the building block of neural networks. It takes inputs, multiplies by weights, sums them up, and passes through an activation function.

🧮 Perceptron Formula

output = activation( Ī£ (inputs Ɨ weights) + bias )
perceptron.py
import numpy as np

class Perceptron:
    def __init__(self, n_inputs):
        # Initialize random weights and bias
        self.weights = np.random.randn(n_inputs)
        self.bias = np.random.randn()
    
    def forward(self, inputs):
        # Weighted sum + bias
        total = np.dot(inputs, self.weights) + self.bias
        # Step activation (output 0 or 1)
        return 1 if total > 0 else 0

# Create perceptron with 3 inputs
neuron = Perceptron(n_inputs=3)

# Test with sample input
inputs = np.array([0.5, -0.3, 0.8])
output = neuron.forward(inputs)

print(f"Weights: {neuron.weights}")
print(f"Bias: {neuron.bias:.4f}")
print(f"Input: {inputs}")
print(f"Output: {output}")
Output
Weights: [ 0.4219  1.2764 -0.8431]
Bias: 0.2156
Input: [0.5, -0.3, 0.8]
Output: 0
Core Concepts

Activation Functions

Activation functions add non-linearity to neural networks. Without them, any deep network would behave like a single linear layer!

ReLU (Rectified Linear Unit)

f(x) = max(0, x)

Most popular! Simple and fast. Outputs 0 for negatives.

Input: -2 → Output: 0
Input: 3 → Output: 3

Sigmoid

f(x) = 1 / (1 + e^-x)

Squashes output between 0 and 1. Good for probabilities.

Input: -2 → Output: 0.12
Input: 3 → Output: 0.95

Tanh

f(x) = (e^x - e^-x) / (e^x + e^-x)

Outputs between -1 and 1. Zero-centered.

Input: -2 → Output: -0.96
Input: 3 → Output: 0.99

Softmax

f(x)_i = e^x_i / Σe^x_j

Converts scores to probabilities (sum = 1). Used in output layer.

Input: [2, 1, 0.1]
Output: [0.65, 0.24, 0.11]
activation_functions.py
import numpy as np

def relu(x):
    return np.maximum(0, x)

def sigmoid(x):
    return 1 / (1 + np.exp(-x))

def softmax(x):
    exp_x = np.exp(x - np.max(x))  # Numerical stability
    return exp_x / np.sum(exp_x)

# Test values
x = np.array([-2, -1, 0, 1, 2])

print("Input:  ", x)
print("ReLU:   ", relu(x))
print("Sigmoid:", np.round(sigmoid(x), 3))
print("Softmax:", np.round(softmax(x), 3))
Output
Input:   [-2 -1  0  1  2]
ReLU:    [0 0 0 1 2]
Sigmoid: [0.119 0.269 0.5   0.731 0.881]
Softmax: [0.012 0.032 0.087 0.236 0.643]
Advanced

Backpropagation: How Networks Learn

Backpropagation is the algorithm that trains neural networks. It calculates how much each weight contributed to the error, then adjusts them to reduce the error.

Training Loop (Simplified)

  1. 1 Forward Pass: Input flows through network → Get prediction
  2. 2 Calculate Loss: Compare prediction to actual value (error)
  3. 3 Backward Pass: Calculate gradients (how to adjust weights)
  4. 4 Update Weights: Adjust weights using gradient descent
  5. 5 Repeat: Continue for many epochs until loss is minimized
Advanced

Build Your First Neural Network

Let's build a real neural network with Keras to classify handwritten digits (MNIST dataset). This is the "Hello World" of deep learning!

first_neural_network.py
import tensorflow as tf
from tensorflow.keras import layers, models

# Step 1: Load MNIST dataset (60,000 training + 10,000 test images)
(X_train, y_train), (X_test, y_test) = tf.keras.datasets.mnist.load_data()

# Step 2: Preprocess - normalize pixel values 0-255 → 0-1
X_train = X_train.reshape(-1, 784) / 255.0  # Flatten 28x28 → 784
X_test = X_test.reshape(-1, 784) / 255.0

print(f"Training data shape: {X_train.shape}")
print(f"Test data shape: {X_test.shape}")

# Step 3: Build the neural network
model = models.Sequential([
    layers.Dense(128, activation='relu', input_shape=(784,)),  # Hidden layer
    layers.Dropout(0.2),                                       # Prevent overfitting
    layers.Dense(64, activation='relu'),                        # Hidden layer
    layers.Dense(10, activation='softmax')                      # Output: 10 digits
])

# Step 4: Compile (configure training)
model.compile(
    optimizer='adam',
    loss='sparse_categorical_crossentropy',
    metrics=['accuracy']
)

# Step 5: Train the model
print("\nšŸš€ Training...")
history = model.fit(X_train, y_train, epochs=5, validation_split=0.1, verbose=1)

# Step 6: Evaluate on test data
test_loss, test_acc = model.evaluate(X_test, y_test, verbose=0)
print(f"\nšŸŽÆ Test Accuracy: {test_acc * 100:.2f}%")
Output
Training data shape: (60000, 784)
Test data shape: (10000, 784)

šŸš€ Training...
Epoch 1/5 - loss: 0.3241 - accuracy: 0.9052 - val_accuracy: 0.9633
Epoch 2/5 - loss: 0.1498 - accuracy: 0.9553 - val_accuracy: 0.9695
Epoch 3/5 - loss: 0.1103 - accuracy: 0.9664 - val_accuracy: 0.9723
Epoch 4/5 - loss: 0.0886 - accuracy: 0.9730 - val_accuracy: 0.9750
Epoch 5/5 - loss: 0.0739 - accuracy: 0.9773 - val_accuracy: 0.9763

šŸŽÆ Test Accuracy: 97.45%

What Each Layer Does

  • • Dense(128, 'relu'): 128 neurons with ReLU activation
  • • Dropout(0.2): Randomly drops 20% of neurons to prevent overfitting
  • • Dense(10, 'softmax'): Output layer with 10 classes (digits 0-9)
  • • Adam optimizer: Smart gradient descent with momentum

Next: Convolutional Neural Networks

Learn how CNNs revolutionized image recognition and computer vision.