What Is a Neural Network? Perceptrons, Weights, Biases & Linear Layers
Start from zero: how a single neuron makes a weighted decision, what weights & biases mean geometrically, and how PyTorch nn.Linear batches thousands of neurons on a GPU.
Every LLM, Vision Transformer, ResNet, and Diffusion model is built by stacking this exact atomic operation: y = xWᵀ + b!
Over 90% of GPU FLOPs in GPT-4, Llama 3, and Claude are spent inside nn.Linear matrix multiplications (GEMM). Mastering exact (B, d_in) → (B, d_out) shapes and parameter counts is the #1 daily skill of a Deep Learning engineer.
Recognizing that a single neuron with Sigmoid is literally Logistic Regression — and a single neuron with no activation is Linear Regression — unifies all of Classical ML and Deep Learning into one mental model.
Interviewers routinely ask beginners and seniors alike: 'What is the exact shape of nn.Linear(768, 3072).weight in PyTorch, why is it stored transposed, and what happens geometrically if you set bias=False?'
Suppose you create a PyTorch linear layer nn.Linear(in_features=10, out_features=4, bias=True) and pass a batch of 32 samples with shape (32, 10). What are the exact output shape and total trainable parameter count?
- Compute a single neuron's output z = w·x + b by hand and understand what each weight wᵢ and bias b physically controls
- Visualize w·x + b = 0 geometrically as a hyperplane whose tilt is w and whose offset from the origin is b
- Scale from 1 neuron to a full Linear Layer Y = X Wᵀ + b and track exact batch tensor shapes (B, d_in) → (B, d_out)
- Calculate exact parameter counts (d_in × d_out + d_out) and implement nn.Linear from scratch in PyTorch
Forget sci-fi brains for a second! Imagine deciding whether to go surfing today based on 3 clues: Wave Height (x₁), Sunshine (x₂), and Shark Alerts (x₃). You give Wave Height a big positive vote (w₁ = +0.8), Sunshine a medium vote (w₂ = +0.5), and Shark Alerts a huge negative veto (w₃ = −5.0). Finally, you add your personal laziness threshold (bias b = −2.0). If the total score z = w·x + b is positive, you grab your board! Congratulations — you just invented the Perceptron!
1. From Everyday Decisions to the Artificial Neuron (Perceptron)
In 1957, psychologist Frank Rosenblatt built the Perceptron — a mathematical model of a biological neuron. Signals arrive at dendrites (x₁, x₂, x₃), get amplified or damped by synapse strengths (w₁, w₂, w₃), sum inside the cell body (Σ), and fire down the axon (ŷ) if they beat a threshold (b). Watch the glowing signals flow below!
The Exact Single-Neuron Equation
Given an input vector , learnable weights , and scalar bias :
- Positive weight (): Higher pushes the neuron to fire stronger.
- Negative weight (): Higher inhibits (suppresses) the neuron.
- Zero weight (): The neuron completely ignores feature .
- Bias (): Acts as the neuron's baseline tendency — negative makes it skeptical (harder to fire), positive makes it eager!
Click each glowing piece to see its exact role in a neuron's decision
Raw numeric measurements of the current example (e.g., pixels, sensor readings, embeddings).
2. Geometric Intuition: Weights Tilt the Fence, Bias Slides It!
In 2D, the equation w₁x₁ + w₂x₂ + b = 0 draws a straight line cutting the plane into two half-spaces: a positive side (z > 0) and a negative side (z < 0). In 3D, it's a flat sheet (plane). In 1,000D, it's a hyperplane! Drag w₁, w₂, and b below to tilt and slide the fence yourself.
Two Geometric Superpowers to Remember Forever
- is always perpendicular (normal) to the decision boundary: Rotating rotates the boundary line; scaling makes the neuron more confident (steeper slope) without moving where sits!
- Bias slides the boundary parallel to itself: Specifically, the perpendicular distance from the origin to the boundary is . If you drop the bias (
bias=False), EVERY decision line is pinned to pass straight through !
Tilt w₁, w₂ & Shift Bias b to Separate Blue (0) from Emerald (1)
A neuron has weights w = [3, 4] and bias b = −10. What is its raw score z at input x = [2, 2], and how far is the decision boundary from the origin?
3. Scaling Up: From 1 Neuron to a Full Linear Layer (Batched Matrix Math)
One neuron outputs 1 number. What if we want 128 neurons all looking at the same 784 pixels at once — AND we want to process 32 images simultaneously on a GPU? Stack the 32 images into a matrix X of shape (32, 784) and stack the 128 neurons' weights into W of shape (128, 784)!
The Batched Linear Layer Equation (PyTorch Standard)
- Input : shape
(B, d_in)— samples in the mini-batch. - Weight : stored in PyTorch as
(d_out, d_in)so each row is neuron 's weight vector ! Transposing gives of shape(d_in, d_out). - Bias : shape
(d_out,), automatically broadcast across all rows. - Output : shape
(B, d_out)— row , column is neuron 's score on sample !
Hand-Worked Batched Linear Layer: (2, 3) → (2, 2)
Let's trace a mini-batch of B = 2 examples (3 features each) passing through nn.Linear(3, 2) by hand!
Input X has shape (2, 3): [[1, 0, 2], [0, 3, 1]]. Weight W has shape (2, 3): [[1, 2, 0], [-1, 1, 2]]. Bias b has shape (2,): [0.5, -1.0].
d_in = 3 matches before multiplying!In PyTorch, what is the shape of layer.weight for layer = nn.Linear(784, 256)?
4. Linear Layers as Geometric Space Transformations (Geometric View)
Here is the geometric mental superpower that makes all of Deep Learning click: stop thinking of W·x + b as boring tables of numbers! Think of an nn.Linear(2, 2) layer as grabbing the entire 2D rubber sheet of space, stretching it, shearing it, rotating it, and sliding the origin to b! Try it live in the obsidian MotionStage below.
Reading a Weight Matrix Geometrically
- Column 1 of tells you exactly where the unit x-vector lands.
- Column 2 of tells you exactly where the unit y-vector lands.
- Notice one huge limitation: a Linear Layer ALWAYS keeps grid lines parallel and evenly spaced — it can stretch and rotate space, but it can NEVER bend or fold space! That is why we need Hidden Layers + Non-Linear Activations in Chapter 2!
Calculate the total trainable parameter count of a 2-layer MLP: nn.Linear(784, 256) followed by nn.Linear(256, 10) (both with bias=True).
When is it actually GOOD practice in modern Deep Learning to set bias=False on an nn.Linear layer?
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
Great math catch! Strictly speaking, Wx is linear (maps 0 to 0) and Wx + b is affine (linear + translation). Deep learning frameworks named it nn.Linear / Dense for brevity, and everybody uses the term informally.
Watch y = W·x + b Continuously Stretch, Shear & Shift 2D Space
Every nn.Linear(2, 2) layer is a smooth geometric transformation of the entire coordinate grid!
LLM Projection Matrices (Q, K, V, FFN)
Transformer attention and feed-forward blocks are giant nn.Linear projections running at trillions of FLOPs/sec.
Classification Heads
The final layer of ResNet (nn.Linear(2048, 1000)) or GPT (nn.Linear(4096, 128000)) maps features to class logits.
Tabular Deep Learning
Embedding lookups concatenated with continuous features feed directly into stacked nn.Linear layers.
Feature Compression / Autoencoders
Bottleneck linear projections squeeze high-dimensional vectors into compact latent codes.
import torch
import torch.nn as nn
# 1. From-Scratch Linear Layer (exact PyTorch math!)
def linear_forward_scratch(x: torch.Tensor, weight: torch.Tensor, bias: torch.Tensor) -> torch.Tensor:
# x: (B, d_in), weight: (d_out, d_in), bias: (d_out,)
return x @ weight.T + bias # -> (B, d_out)
# 2. Idiomatic Production PyTorch nn.Linear
B, d_in, d_out = 32, 784, 128
layer = nn.Linear(d_in, d_out, bias=True)
x = torch.randn(B, d_in) # (32, 784)
y = layer(x) # (32, 128)
print("Weight shape:", layer.weight.shape) # torch.Size([128, 784])
print("Bias shape: ", layer.bias.shape) # torch.Size([128])
print("Output shape:", y.shape) # torch.Size([32, 128])
print("Total params:", sum(p.numel() for p in layer.parameters())) # 100,480
nn.Linear(in, out).weight has shape (in, out).(out_features, in_features) and computes x @ W.T + b for memory-contiguous matmuls.(784,) when downstream layers expect a batch dimension (1, 784).(B, d_in) — use x.unsqueeze(0) for single-item inference.nn.Linear works on arbitrary leading dimensions (B, T, d_in)!nn.Linear applies cleanly to the LAST dimension, transforming (B, T, d_in) → (B, T, d_out) without flattening!nn.Linear(64, 10, bias=True) have?bias=False on a single 2D Perceptron?nn.Linear(100, 20).weight in PyTorch?