Get a simple MLP in TensorFlow to model XOR
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
XOR is the standard example of a pattern that a single linear layer cannot represent. The four input points are not linearly separable, so a perceptron fails no matter how long you train it. A small multilayer perceptron with a hidden layer solves it easily, which is why XOR is still useful for checking whether a neural-network setup is structurally correct.
Why a Single Layer Fails
The XOR truth table is:
- '
0, 0 -> 0' - '
0, 1 -> 1' - '
1, 0 -> 1' - '
1, 1 -> 0'
No single straight decision boundary can separate the positive and negative examples. That means you need at least one hidden layer with a nonlinear activation.
A Minimal TensorFlow Model
A tiny Keras model is enough. The key ingredients are:
- input size
2 - a hidden layer with a nonlinear activation such as
tanh - an output layer with
sigmoid - enough training epochs for the tiny dataset
This should produce outputs close to 0, 1, 1, 0.
Why This Architecture Works
The hidden layer lets the network build an intermediate representation where XOR becomes separable. You can think of the hidden units as learning multiple regions in the input space, then the output layer combines those regions into the final classification.
The exact number of hidden units is not very important here. Even a very small hidden layer can solve XOR. What matters is that you include a nonlinear activation.
Good Defaults for XOR
For a toy problem like XOR, overly complex architecture is usually a sign of confusion. A good baseline is:
- '
Dense(4, activation="tanh")' - '
Dense(1, activation="sigmoid")' - '
binary_crossentropy' - '
Adam'
You can also use relu, but tanh often works smoothly for this tiny symmetric dataset.
How to Verify Learning
Do not stop at training accuracy. Inspect the raw predictions.
This helps you see whether the network truly separated the four cases or just hovered around ambiguous values.
For XOR, a correct model should predict values near:
- '
0for[0, 0]' - '
1for[0, 1]' - '
1for[1, 0]' - '
0for[1, 1]'
Common Reasons It Does Not Learn
If the network fails, the usual causes are:
- using no hidden layer
- using a linear activation everywhere
- training too briefly
- using an unstable learning rate
- shape mismatches between labels and outputs
A single dense output layer with sigmoid still cannot solve XOR because the core issue is representational, not just probabilistic output.
A Slightly More Explicit Functional Model
If you prefer the functional API:
This behaves the same but makes it easier to inspect or extend the architecture later.
Why XOR Still Matters
XOR is small, but it tests the basics correctly. If a framework setup cannot learn XOR, the issue is often with:
- model structure
- activation choice
- label shape
- optimizer or training loop configuration
That makes it a useful sanity check when experimenting with custom training code.
Common Pitfalls
The biggest pitfall is assuming "MLP" automatically means the model is nonlinear. If you omit the hidden layer or use only linear activations, XOR still fails.
Another issue is undertraining. Four samples do not mean one epoch is enough. Toy problems often need enough iterations for the network to settle.
Be careful with output thresholds too. A prediction of 0.49 is not a correct confident zero just because it rounds down.
Finally, do not make the example harder than necessary. XOR is a structural demonstration, not a benchmark.
Summary
- XOR is not linearly separable, so a single-layer model cannot solve it.
- A simple MLP with one hidden layer and a nonlinear activation is enough.
- '
tanhin the hidden layer andsigmoidin the output layer is a solid baseline.' - Train long enough and inspect the actual predictions, not only accuracy.
- If XOR does not learn, the model setup is usually structurally wrong.
- XOR remains a useful sanity check for TensorFlow and neural-network basics.
Related reading
- Get audiences insights using Keras and TensorFlow
- Get coefficients of a linear regression in Tensorflow
- get_config missing while loading previously saved model without custom layers
- get_config missing while loading previously saved model without custom layers
- Get confidence interval from sklearn linear regression in python
- Get Gradients with Keras Tensorflow 2.0
- Get info of exposed models in Tensorflow Serving
- Get Keras model input from inside a custom callback
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.