Neural network foundations · Day 12
Hidden layers: why nonlinearity matters
See why stacking linear layers cannot solve XOR. Follow the complete original lesson, then verify the math, inspect the actual Python results and build an exact two-unit solution.

Contents
Complete historical lesson
All original explanations follow in their original order. The checked companion guide below adds separate clarifications; the original examples and table remain unchanged. Original embedded titles are retained as source labels.
Understanding Non-Linearity in Neural Networks
Understanding Non-Linearity in Neural Networks
Non-linearity in neural networks is essential for solving complex tasks where the data is not linearly separable. This blog post explains why hidden layers and non-linear activation functions are necessary, using the XOR problem as an example.
What is Non-Linearity?
Non-linearity in neural networks allows the model to learn and represent more complex patterns. In the context of decision boundaries, a non-linear decision boundary can bend and curve, enabling the separation of classes that are not linearly separable.
Role of Activation Functions
The primary role of an activation function is to introduce non-linearity into the neural network. Without non-linear activation functions, even networks with multiple layers would behave like a single-layer network, unable to learn complex patterns. Common non-linear activation functions include sigmoid, tanh, and ReLU.
Role of Hidden Layers
Hidden layers provide the network with additional capacity to learn complex patterns by applying a series of transformations to the input data. However, if these transformations are linear, the network will still be limited to linear decision boundaries. The combination of hidden layers and non-linear activation functions enables the network to learn non-linear relationships and form non-linear decision boundaries.
Mathematical Explanation
Without Hidden Layers
A single-layer neural network (perceptron) computes the output as:
z = w · x + b
y = f(z)
Where:
- x is the input vector.
- w is the weight vector.
- b is the bias.
- f is the activation function (e.g., sigmoid).
For the decision boundary:
w · x + b = 0
This is a linear equation, so the decision boundary is a straight line.
With Hidden Layers
A neural network with one hidden layer computes the output as:
z(1) = W(1) · x + b(1)
a(1) = f(z(1))
z(2) = W(2) · a(1) + b(2)
y = g(z(2))
Where:
- W(1), b(1) are the weights and biases for the hidden layer.
- W(2), b(2) are the weights and biases for the output layer.
- f and g are activation functions (e.g., tanh).
The non-linear activation function f introduces non-linearity, enabling the network to learn complex patterns and create non-linear decision boundaries.
Understanding Non-Linearity in Neural Networks
Understanding Non-Linearity in Neural Networks
Example: XOR Problem
The XOR problem is a classic example of a non-linearly separable dataset. We will train a neural network with and without hidden layers to demonstrate how decision boundaries are formed.
Code with Hidden Layer
import numpy as np
import matplotlib.pyplot as plt
from sklearn.neural_network import MLPClassifier
# Define the XOR dataset
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([0, 1, 1, 0])
# Train a neural network
mlp = MLPClassifier(hidden_layer_sizes=(2,), activation='tanh', max_iter=10000, random_state=42)
mlp.fit(X, y)
# Plot the decision boundary
def plot_decision_boundary(model, X, y, title):
x_min, x_max = X[:, 0].min() - 0.5, X[:, 0].max() + 0.5
y_min, y_max = X[:, 1].min() - 0.5, X[:, 1].max() + 0.5
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.01),
np.arange(y_min, y_max, 0.01))
Z = model.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, alpha=0.8, cmap=plt.cm.Paired)
plt.scatter(X[:, 0], X[:, 1], c=y, edgecolors='k', cmap=plt.cm.Paired)
plt.title(title)
plt.xlabel('x1')
plt.ylabel('x2')
plt.show()
plot_decision_boundary(mlp, X, y, "Neural Network Decision Boundary")
Code Without Hidden Layer
from sklearn.linear_model import LogisticRegression
# Train a logistic regression model
log_reg = LogisticRegression()
log_reg.fit(X, y)
# Plot decision boundaries
plot_decision_boundary(log_reg, X, y, "Logistic Regression Decision Boundary")
Analysis
- With Hidden Layer: The network creates a non-linear decision boundary, enabling it to solve the XOR problem. The hidden layer and activation function introduce the non-linearity required.
- Without Hidden Layer: The logistic regression model produces a linear decision boundary, failing to separate the XOR dataset correctly.
Comparison Table
| Input | Hidden Layer Outputs (A(1)) | Output (y) |
|---|---|---|
| (1, 0) | (0.462, -0.462) | 0.5 |
| (0, 1) | (0.462, -0.462) | 0.5 |
| (0, 0) | (0, 0) | 0.5 |
| (1, 1) | (0.762, -0.762) | 0.5 |
Conclusion
The combination of hidden layers and non-linear activation functions allows neural networks to solve complex problems like XOR. By introducing non-linearity, the network can create flexible decision boundaries capable of separating non-linearly separable datasets.
Transformation of input space through non-linear activation.Checked companion guide
Why more layers alone are not enough
A hidden layer is an intermediate representation: it converts the input coordinates into features that another layer can use. The word “hidden” does not mean secret; the training labels specify the desired final answer, rather than a target for each intermediate neuron. Width counts the units in a layer. Depth counts successive transformations. Neither quantity by itself guarantees that training will succeed.
Two affine layers collapse into one
Strictly, a weighted sum plus a bias is affine, although it is often called linear in introductory discussions. Suppose the hidden activation is the identity. Substitute the hidden expression into the output expression, keeping matrix multiplication in its original order:
z = W₂h + b₂ = (W₂W₁)x + (W₂b₁ + b₂)
The effective weight is W₂W₁ and the effective bias is W₂b₁ + b₂. The dimensions must be compatible; matrix multiplication does not generally commute.
For two input features and two hidden units, W₁ is 2 × 2, b₁ has two entries, W₂ is 1 × 2 and b₂ is scalar. Adding further identity-activation layers repeats the same argument. A final monotone sigmoid changes the score into a probability, but at threshold 0.5 its boundary still occurs at z = 0. A straight line in two dimensions becomes a hyperplane in higher dimensions. This qualification makes the original lesson’s straight-line statement precise.
A short proof that a line cannot separate XOR
XOR labels (0,0) and (1,1) as 0, and (0,1) and (1,0) as 1. Suppose positive scores represent class 1 and negative scores represent class 0, with no ties. The four requirements on the same weights and bias are:
w₂ + b > 0; w₁ + b > 0
Adding the negative-class inequalities gives w₁ + w₂ + 2b < 0. Adding the positive-class inequalities gives the same expression > 0: a contradiction.
A consistent tie rule does not rescue a perfect linear classifier: both class groups have the same midpoint, (0.5,0.5). Their convex hulls intersect. Nonlinear features change the representation so that a linear output can separate the transformed points.
Build XOR with two ReLU units
This construction uses chosen weights, not a training run. Let s be the sum of the two binary inputs. One hidden unit measures s; the second turns on only after s passes 1. Subtracting twice the second activation bends the response back down at the (1,1) corner.
h₁ = max(0, s); h₂ = max(0, s − 1)
ŷ = h₁ − 2h₂
The hidden weight rows are (1,1) and (1,1), hidden biases are 0 and −1, and the linear output weights are (1,−2), with output bias 0.
| Input | s | h₁ | h₂ | ŷ | XOR target |
|---|---|---|---|---|---|
| (0,0) | 0 | 0 | 0 | 0 | 0 |
| (0,1) | 1 | 1 | 0 | 1 | 1 |
| (1,0) | 1 | 1 | 0 | 1 | 1 |
| (1,1) | 2 | 2 | 1 | 0 | 0 |
For example, input (1,1) gives s = 2, h₁ = 2 and h₂ = 1, hence ŷ = 2 − 2 = 0. Input (1,0) gives h₁ = 1 and h₂ = 0, hence ŷ = 1. These values were checked by executing the formula for all four inputs. Outside the binary inputs this is a continuous piecewise-linear function, not a calibrated probability model or a claim about a trained network.
What the original code actually does
Separate verification note, 16 November 2026: both original Python blocks above were executed together without changing their code strings, using NumPy 2.3.5, scikit-learn 1.8.0 and Matplotlib’s noninteractive Agg backend. The second block depends on X, y and the plotting function defined in the first. The original tanh model stopped after 433 iterations and predicted [1, 0, 1, 0] for inputs [(0,0), (0,1), (1,0), (1,1)]: 2/4 correct. Its class-1 probabilities were approximately [0.506238, 0.412174, 0.609540, 0.497819].
The original logistic regression predicted [0, 0, 0, 0], with probability 0.5 for each point. Its flat probability surface is consistent with the symmetry of this balanced XOR dataset. The nonlinear model’s failure here does not show that XOR is impossible for a neural network. It shows that the chosen initialization, optimizer and stopping conditions did not produce the desired fit in this run. Raising max_iter supplies a ceiling; it does not require the optimizer to use every iteration or guarantee a solution.
Historical-table clarification: the original table is preserved exactly, including all repeated 0.5 outputs and both repeated hidden vectors. Those rows do not establish a successful XOR classifier. In particular, equal outputs at every input cannot implement XOR. The table also does not specify a complete weight set that would let a reader reproduce it from the original fitted estimator. Use the separately labeled exact construction above to follow a fully specified calculation.

A separate reproducible fitting example
This additional example uses four tanh hidden units and L-BFGS, with zero regularization for a deliberately small fitting demonstration. These are explicit example choices, not a general prescription for production data. It produced [0, 1, 1, 0] and 4/4 training accuracy here. The corresponding probabilities were approximately [0.000000, 1.000000, 0.999819, 0.000035]. Rounded probabilities are not exact mathematical zeros or ones.
import numpy as np
from sklearn.neural_network import MLPClassifier
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([0, 1, 1, 0])
model = MLPClassifier(
hidden_layer_sizes=(4,), activation="tanh",
solver="lbfgs", alpha=0, max_iter=10000,
random_state=42,
).fit(X, y)
print(model.predict(X))
print(model.predict_proba(X)[:, 1])
assert np.array_equal(model.predict(X), y)
Always inspect predictions, probability estimates and convergence information rather than assuming the architecture worked. Four training examples establish a teaching demonstration; they cannot estimate performance on new real-world data. For larger tasks, set aside validation/test data and select model settings using training/validation results. A random seed improves repeatability but does not promise identical floating-point outcomes across software versions and hardware.
Primary references and further study
The Deep Learning textbook, Chapter 6 explains learned representations and the XOR example. The official MLPClassifier API reference documents hidden activations, solvers and stopping parameters; its stable version may differ from the 1.8.0 environment recorded here. This lesson’s numerical results come from its own executed checks.
Try changing the two-ReLU construction’s output coefficient from −2 to −1. At (1,1), the output becomes 1 instead of 0. This small exercise isolates the role of the output weights. Then restore −2 and check every row again. The exercise requires no dataset download or account.
Questions about hidden layers and XOR
Why do hidden layers need nonlinear activations?
Without them, successive affine layers collapse into a single affine map. Nonlinear hidden features can give the output classifier a boundary it cannot draw in the original input space.
Can one straight line solve XOR?
No. The two positive corners and two negative corners cannot be separated by one straight line. The worked contradiction in this lesson proves it.
Did the original Python example solve XOR in this check?
No. With scikit-learn 1.8.0, the unchanged original tanh example classified two of the four training points correctly. Its architecture has nonlinear capacity, but this training run did not find an XOR solution.
Does the original table show a successful XOR model?
No. Every listed output is 0.5. It is retained for historical completeness; the added table gives a separately verified construction.
Does 100% on four XOR points prove generalization?
No. It demonstrates fitting those four training inputs. It is not an evaluation on unseen real-world data.
Must every layer use a nonlinear activation?
No. Hidden nonlinearities provide expressive features. An output may be linear for regression, or use sigmoid or softmax for probabilities, depending on the task and loss.
