Python BASICS OF NEURAL NETWORKS (with PREREQUISITE: derivatives & gradients): 14 practice problems
UNIT 4 of the free Python for AI course. Read the short theory, then solve the problems below with instant tests. Python runs in your browser.
▶ Practise BASICS OF NEURAL NETWORKS (with PREREQUISITE: derivatives & gradients) nowAll topicsTheory: BASICS OF NEURAL NETWORKS (with PREREQUISITE: derivatives & gradients) in Python
PREREQUISITE THEORY — just enough calculus
------------------------------------------
* DERIVATIVE f'(x) = slope of f at x = how fast f changes when x changes a tiny bit.
f(x) = x² -> f'(x) = 2x f(x) = 3x + 1 -> f'(x) = 3
Numerically: f'(x) ≈ (f(x + h) - f(x - h)) / (2h) for a tiny h (central difference).
* The derivative tells you which way is DOWNHILL: to minimise f, move x opposite to f'(x).
That's GRADIENT DESCENT: x_new = x - learning_rate * f'(x)
* CHAIN RULE: if y = f(g(x)) then dy/dx = f'(g(x)) * g'(x). BACKPROPAGATION is just the chain
rule applied layer by layer, from the output back to the inputs.
* Gradient = vector of partial derivatives (one per weight).
NEURAL NETWORK THEORY
---------------------
* ARTIFICIAL NEURON: z = w1*x1 + w2*x2 + ... + b (weighted sum = dot product + bias)
a = activation(z)
WEIGHTS = importance of each input; BIAS = shifts the threshold. Both are LEARNED.
* ACTIVATION FUNCTIONS (add non-linearity — without them, many layers = one linear layer)
step 1 if z >= 0 else 0 (perceptron; not differentiable)
sigmoid 1 / (1 + e^-z) -> (0, 1) probability output; σ'(z) = σ(z)(1 - σ(z))
tanh -> (-1, 1), zero-centred
ReLU max(0, z) default for hidden layers, fast, no vanishing gradient for z>0
leaky ReLU max(αz, z) fixes "dead" ReLUs
softmax e^zi / Σ e^zj multi-class probabilities summing to 1
* LAYERS: input layer (features) -> hidden layer(s) -> output layer. "Deep" = many hidden layers.
Dense layer forward pass for a batch: A = activation(X @ W + b), X (n, d), W (d, h), b (h,)
Parameters in a dense layer = inputs*outputs (weights) + outputs (biases).
* LOSS: how wrong predictions are. MSE (regression) · Binary cross-entropy
-mean(y log p + (1 - y) log(1 - p)) (binary classification) · categorical cross-entropy.
* TRAINING LOOP: forward pass -> loss -> backprop (gradients) -> update weights
(w -= lr * grad) -> repeat for many EPOCHS (passes over the data), often in mini-BATCHES.
* PERCEPTRON (Rosenblatt 1958): single neuron + step; learns w += lr * (y - ŷ) * x.
Can only separate classes with a straight line -> learns AND, OR, NAND but NOT XOR
(Minsky & Papert 1969) -> need a HIDDEN LAYER (multi-layer perceptron).
* Hyper-parameters (you choose): learning rate, epochs, batch size, layers, neurons, activation.
Too high lr -> diverges; too low -> slow. Overfitting -> more data, dropout, regularisation, early stopping.
* Network families: Feed-forward/MLP · CNN (images) · RNN/LSTM (sequences) · Transformer (LLMs).
14 BASICS OF NEURAL NETWORKS (with PREREQUISITE: derivatives & gradients) practice problems
1. PREREQ — Numerical Derivative (central difference)
Easy1 way to solve📤 OUTPUT: return a float, e.g. 6.0. Use `return`, not print().
numeric_derivative(lambda x: x ** 2, 3) -> 6.0 (approximately; return a float)
Solve “PREREQ — Numerical Derivative (central difference)” in your browser →2. PREREQ — Gradient Descent on One Variable
Easy1 way to solve📤 OUTPUT: return a float, e.g. 5.0. Use `return`, not print().
Real world: Find the price that minimises a cost curve.
Repeat `steps` times: x = x - lr * f_prime(x). Return x rounded to 3.
minimise(lambda x: 2 * (x - 5), 0, 0.1, 200) -> 5.0
Solve “PREREQ — Gradient Descent on One Variable” in your browser →3. One Artificial Neuron
Easy2 ways to solve📤 OUTPUT: return a float, e.g. 0.5. Use `return`, not print().
z = x · w + b; apply activation "sigmoid", "relu", "step" (1 if z >= 0 else 0) or "linear".
Return a float (step returns 1.0 / 0.0).
neuron([1, 2], [0.5, -0.25], 0.0) -> 0.5 (z = 0)
neuron([1, 2], [1, 1], -1, "relu") -> 2.0
Solve “One Artificial Neuron” in your browser →4. Leaky ReLU on arrays
Easy2 ways to solve📤 OUTPUT: return a NumPy array, e.g. [-0.1, 0.0, 5.0]. Use `return`, not print().
leaky_relu(np.array([-10.0, 0.0, 5.0])) -> [-0.1, 0.0, 5.0]
Solve “Leaky ReLU on arrays” in your browser →5. Sigmoid Derivative — σ(z) * (1 - σ(z)), works on arrays
Easy1 way to solve📤 OUTPUT: return a NumPy array, e.g. 0.25. Use `return`, not print().
sigmoid_grad(0) -> 0.25
Solve “Sigmoid Derivative — σ(z) * (1 - σ(z)), works on arrays” in your browser →6. Softmax — numerically stable (subtract max). Return an array summing to 1.
Easy1 way to solve📤 OUTPUT: return a NumPy array that sums to 1, e.g. [0.659, 0.2424, 0.0986]. Use `return`, not print().
softmax(np.array([2.0, 1.0, 0.1])) -> [0.659, 0.2424, 0.0986] (approx)
Solve “Softmax — numerically stable (subtract max). Return an array summing to 1.” in your browser →7. Binary Cross-Entropy Loss
Medium1 way to solve📤 OUTPUT: return a float, e.g. 0.1053605. Use `return`, not print().
Clip predictions to [1e-12, 1 - 1e-12] to avoid log(0). Return the mean as a float.
binary_cross_entropy([1, 0], [0.9, 0.1]) -> 0.10536 (approx)
Solve “Binary Cross-Entropy Loss” in your browser →8. Teach a Perceptron a Logic Gate
Medium1 way to solve📤 OUTPUT: return a NumPy array, e.g. [0, 0, 0, 1]. Use `return`, not print().
gate is "AND", "OR" or "NAND". Inputs X = [[0,0],[0,1],[1,0],[1,1]].
Train with the perceptron rule (w, b start at 0; step(z) = 1 if z >= 0 else 0), then return the
list of 4 predictions (ints). A correct trainer returns the gate's truth table:
perceptron_gate("AND") -> [0, 0, 0, 1]
Solve “Teach a Perceptron a Logic Gate” in your browser →9. Dense Layer Forward Pass for a Batch
Easy2 ways to solve📤 OUTPUT: return a NumPy array, e.g. [[2.0]]. Use `return`, not print().
Return activation(X @ W + b) with activation "relu", "sigmoid" or "linear".
dense_forward(np.array([[1.0, 2.0]]), np.array([[1.0], [1.0]]), np.array([-1.0])) -> [[2.0]]
Solve “Dense Layer Forward Pass for a Batch” in your browser →10. How Big Is My Model? — parameters of a dense network
Easy2 ways to solve📤 OUTPUT: return an int, e.g. 17. Use `return`, not print(). Real world: GPT-3 has 175 billion parameters; yours has a few. layer_sizes [2, 4, 1] -> (2*4 + 4) + (4*1 + 1) = 17Solve “How Big Is My Model? — parameters of a dense network” in your browser →
11. Train a Linear Neuron with Gradient Descent (MSE loss)
Hard1 way to solve📤 OUTPUT: return a tuple, e.g. (2.0, 1.0). Use `return`, not print().
Model: y_hat = w * x + b, start w = b = 0. Each epoch:
error = y_hat - y (for all points, NumPy arrays)
dw = 2 * mean(error * x); db = 2 * mean(error)
w -= lr * dw; b -= lr * db
Return (w, b) rounded to 2. fit_linear_gd([0, 1, 2, 3], [1, 3, 5, 7]) -> (2.0, 1.0)
Solve “Train a Linear Neuron with Gradient Descent (MSE loss)” in your browser →12. Solve XOR by Hand — why hidden layers matter
Hard1 way to solve📤 OUTPUT: return (W1, b1, W2, b2) as NumPy arrays so that. Use `return`, not print().
A single perceptron CAN'T compute XOR. Two layers with step activations CAN.
Return (W1, b1, W2, b2) as NumPy arrays so that
hidden = step(X @ W1 + b1) X shape (4, 2), W1 (2, 2), b1 (2,)
out = step(hidden @ W2 + b2) W2 (2, 1), b2 (1,)
gives [[0], [1], [1], [0]] for X = [[0,0],[0,1],[1,0],[1,1]].
Hint: hidden neuron 1 = OR, hidden neuron 2 = NAND, output = AND of the two.
Solve “Solve XOR by Hand — why hidden layers matter” in your browser →13. Customer-Churn Predictor — interview at a telecom company (data-science team)
Project1 way to solve📤 OUTPUT: return (w, b). Use `return`, not print().
Interviewer: "Train a single sigmoid neuron (logistic regression) that flags customers about to leave."
w = zeros(n_features), b = 0. Each epoch (whole batch, NumPy, no loops over rows):
p = sigmoid(X @ w + b); dw = X.T @ (p - y) / n; db = mean(p - y)
w -= lr * dw; b -= lr * db
Return (w, b).
Solve “Customer-Churn Predictor — interview at a telecom company (data-science team)” in your browser →14. Stage 19 — a Perceptron that spots English pasted into code
Compiler1 way to solve📤 OUTPUT: return a NumPy array, e.g. [1, 0, 1, 0]. Use `return`, not print(). Features come from _line_features(line) (given above). Perceptron: w = [0, 0, 0, 0], b = 0, lr = 0.1, 20 epochs over the training lines in order; predict = 1 if w·x + b >= 0 else 0; on a mistake: w += lr * (label - predict) * x, b += lr * (label - predict). Return the list of predictions (ints) for test_lines.Solve “Stage 19 — a Perceptron that spots English pasted into code” in your browser →
← Introduction to artificial intelligence Unit 4 / course objective — building a basic ai chatbot →