Reading history

Neural Network Basics in Python: Neurons to MLPClassifier

5 min read 0 views

Learn neural network basics in Python: neurons, activations, loss and gradient descent from scratch with NumPy, and multi-layer perceptrons in scikit-learn.

Neural networks power image recognition, speech assistants and large language models, but their building block is surprisingly simple. A single neuron multiplies its inputs by weights, adds a bias and passes the result through an activation function. Stack many neurons in layers and adjust all the weights with gradient descent, and the network can learn complex patterns. This lesson builds one neuron from scratch with NumPy, then trains a multi-layer network with scikit-learn.

In this lesson you will learn

  • What a neuron computes: weights, bias and activation
  • The forward pass, the loss and gradient descent
  • Training a neuron from scratch with NumPy
  • Multi-layer perceptrons with MLPClassifier
  • Layers, parameters, epochs and early stopping

This lesson builds on logistic regression, which is exactly one neuron with a sigmoid activation.

One Neuron From Scratch

import numpy as np

# One neuron learns the AND gate with gradient descent
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=float)
y = np.array([0, 0, 0, 1], dtype=float)

rng = np.random.default_rng(0)
w = rng.normal(0, 0.5, 2)
b = 0.0
lr = 1.0

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

for epoch in range(2001):
    out = sigmoid(X @ w + b)                 # forward pass
    error = out - y                          # gradient of the loss w.r.t. z (cross-entropy)
    w -= lr * X.T @ error / len(X)           # backward pass: update weights
    b -= lr * error.mean()
    if epoch % 500 == 0:
        loss = -np.mean(y * np.log(out) + (1 - y) * np.log(1 - out))
        print(f"epoch {epoch:4d}  loss {loss:.4f}")

print("weights:", w.round(2), "bias:", round(b, 2))
print("outputs:", sigmoid(X @ w + b).round(3))

Output

epoch    0  loss 0.6934
epoch  500  loss 0.0346
epoch 1000  loss 0.0174
epoch 1500  loss 0.0116
epoch 2000  loss 0.0087
weights: [8.82 8.82] bias: -13.4
outputs: [0.    0.01  0.01  0.986]
  • Forward pass: the neuron computes z = x1·w1 + x2·w2 + b and squashes it with the sigmoid function into a probability between 0 and 1.
  • Loss: cross-entropy measures how far the outputs are from the targets. It starts at 0.69 (random guessing) and falls towards 0.
  • Gradient descent: for sigmoid with cross-entropy, the gradient of the loss with respect to z is simply output − target. Multiplying by the inputs gives the gradient for each weight, and the weights move a small step (the learning rate) against it.
  • After 2,000 epochs (passes over the data), both weights are about 8.8 and the bias is −13.4. Only when both inputs are 1 does z become positive, so the neuron has learned AND.
  • A single neuron can only draw a straight boundary. Problems like XOR need hidden layers.

A Multi-Layer Network

from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = load_digits(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0, stratify=y)

for hidden in [(10,), (64,), (64, 32)]:
    mlp = make_pipeline(
        StandardScaler(),
        MLPClassifier(hidden_layer_sizes=hidden, max_iter=500, early_stopping=True, random_state=0),
    ).fit(X_train, y_train)
    net = mlp[-1]
    params = sum(w.size for w in net.coefs_) + sum(b.size for b in net.intercepts_)
    print(f"hidden layers {str(hidden):9s} parameters={params:5d}  "
          f"epochs={net.n_iter_:3d}  test accuracy={mlp.score(X_test, y_test):.3f}")

Output

hidden layers (10,)     parameters=  760  epochs= 69  test accuracy=0.878
hidden layers (64,)     parameters= 4810  epochs= 42  test accuracy=0.962
hidden layers (64, 32)  parameters= 6570  epochs= 39  test accuracy=0.956
  • A multi-layer perceptron (MLP) has an input layer (64 pixels), one or more hidden layers, and an output layer with one neuron per digit. Hidden neurons use the ReLU activation by default, which outputs max(0, z).
  • hidden_layer_sizes=(64, 32) means two hidden layers with 64 and 32 neurons. Training adjusts every weight with backpropagation, which passes the error gradient backwards through the layers.
  • The parameter count is every weight plus every bias. The network with 64 hidden neurons has 64×64 + 64 + 64×10 + 10 = 4,810.
  • Ten hidden neurons are too few (87.8%); 64 reach 96.2%. Adding a second layer did not help on this small dataset, showing that bigger is not automatically better.
  • early_stopping=True holds back 10% of the training data and stops when its score stops improving, a simple guard against overfitting.

Key Terms

TermMeaning
Weight, biasThe learned numbers inside each neuron
ActivationA non-linear function such as sigmoid, tanh or ReLU
LossA number measuring how wrong the predictions are
Learning rateStep size for each weight update
EpochOne full pass over the training data
BackpropagationComputing gradients for all layers using the chain rule

Scikit-learn’s MLP is fine for small tabular problems. For images, text and large models, frameworks such as PyTorch and TensorFlow add GPUs, convolutional and attention layers, and much more control.

Common Mistakes

  1. Not scaling inputs, which makes training slow or unstable.
  2. A learning rate that is too high (the loss jumps around or explodes) or too low (training crawls).
  3. Making the network huge for a small dataset, which overfits.
  4. Using a network when a simpler model does as well; for many tabular problems, gradient boosting is stronger and easier to tune.

Practice Exercises

Exercise 1. Change the targets in the NumPy example to the OR gate. What weights does the neuron learn?

Show answer
y = np.array([0, 1, 1, 1], dtype=float)

The weights become large and positive while the bias is negative but smaller than either weight, so any single input of 1 makes z positive.

Exercise 2. How many parameters does a network with 4 inputs, one hidden layer of 5 neurons and 3 outputs have?

Show answer

Input to hidden: 4×5 weights + 5 biases = 25. Hidden to output: 5×3 weights + 3 biases = 18. Total 43.

Frequently Asked Questions

What is the difference between machine learning and deep learning?

Deep learning is the part of machine learning that uses neural networks with many layers. See AI vs ML vs Deep Learning for the full picture.

Why is ReLU used instead of sigmoid in hidden layers?

Sigmoid flattens out for large or small inputs, so gradients become tiny and deep networks learn slowly. ReLU keeps a constant gradient for positive inputs and is very cheap to compute.

Summary

  • A neuron computes a weighted sum plus bias, then an activation.
  • Training repeats forward pass, loss, gradient and update.
  • Hidden layers with non-linear activations let networks learn complex boundaries.
  • Scale inputs, size the network to the data, and use early stopping.

Next: ROC Curve and AUC in Python.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *