Machine Learning
Artificial Neural Networks
Odd Numbers Classification
Data Science
Computational Mathematics

Using machine learning ANN to classify odd numbers

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

You can train an artificial neural network to classify odd numbers, but that does not mean you should. Parity is a deterministic rule with an exact one-line solution, so the interesting part of this problem is understanding why an ANN is educational here and why it is a poor engineering choice for production.

The Real Rule for Odd Numbers

An integer is odd when dividing by 2 leaves a remainder of 1. In ordinary code, the direct solution is trivial:

python
1def is_odd(n: int) -> bool:
2    return n % 2 == 1
3
4print(is_odd(7))
5print(is_odd(12))

That baseline matters because any ML solution should be compared against the simplest exact rule. Here, the rule-based approach is faster, perfectly accurate, explainable, and generalizes to every integer immediately.

Why an ANN Struggles More Than You Might Expect

Parity is easy for arithmetic but surprisingly awkward for many neural-network setups. If you feed a model raw decimal integers such as 1, 2, 3, and 4, the network may memorize the training range instead of learning the true concept of oddness.

That happens because odd and even labels alternate. There is no smooth numeric threshold separating the classes. A network that sees only small integers does not automatically infer what happens for much larger ones.

For example, a model trained on values 0 through 999 might perform badly on 100001 unless the representation exposes the underlying binary structure.

If You Still Want to Try It, Encode the Number Properly

The parity of an integer depends only on its least significant bit. That makes binary representation far more sensible than using a single floating-point feature.

python
1def to_bits(n: int, width: int = 8) -> list[int]:
2    return [(n >> i) & 1 for i in range(width)]
3
4print(to_bits(13, width=8))

With this encoding, the network can at least see the bit pattern that determines the answer.

A Small Keras Example

The following example trains a tiny network on binary features. It works as a demonstration, not as the recommended solution to parity.

python
1import numpy as np
2import tensorflow as tf
3
4def to_bits(n, width=8):
5    return [(n >> i) & 1 for i in range(width)]
6
7X = np.array([to_bits(n, width=8) for n in range(256)], dtype=np.float32)
8y = np.array([n % 2 for n in range(256)], dtype=np.float32)
9
10model = tf.keras.Sequential([
11    tf.keras.layers.Input(shape=(8,)),
12    tf.keras.layers.Dense(8, activation="relu"),
13    tf.keras.layers.Dense(1, activation="sigmoid"),
14])
15
16model.compile(optimizer="adam", loss="binary_crossentropy", metrics=["accuracy"])
17model.fit(X, y, epochs=20, verbose=0)
18
19test = np.array([to_bits(13), to_bits(42)], dtype=np.float32)
20predictions = model.predict(test, verbose=0)
21print(predictions)

Even here, the model is still approximating a rule that your code already knows exactly.

Why a Logic Rule Wins

This is a classic example of choosing the right tool. ANN models are powerful when the relationship between inputs and outputs is hard to write down explicitly, such as image recognition, speech, or noisy real-world classification.

Odd-versus-even classification is the opposite. The rule is exact and tiny:

python
1def classify_number(n: int) -> str:
2    return "odd" if n & 1 else "even"
3
4print(classify_number(13))

The bitwise version is especially revealing. It shows that parity is really about one bit, not about a large learned decision surface.

When This Exercise Is Still Useful

Despite being overkill, the task can still teach useful lessons:

  • feature representation matters more than model complexity,
  • some mathematical functions are hard for a network to extrapolate from raw scalar inputs,
  • and benchmarking against a rule-based baseline prevents unnecessary ML.

It is also a safe sandbox for learning Keras or PyTorch because the data generation is simple and the labels are guaranteed correct.

Better Educational Variants

If the goal is to learn ML, more realistic classification tasks are better. You could classify handwritten digits as odd or even from images, or classify noisy sensor readings where a closed-form rule is not obvious.

In those cases, the model is not learning arithmetic parity directly. It is learning to infer the underlying digit or class from ambiguous input. That is the kind of setting where an ANN earns its keep.

Common Pitfalls

The biggest pitfall is feeding the network a single normalized integer and thinking high training accuracy means it learned parity. It may have only memorized a narrow range.

Another mistake is ignoring the baseline. If a one-line arithmetic rule solves the problem exactly, an ANN is not improving correctness or maintainability.

Developers also often overlook representation. Binary features expose the relevant structure; raw decimal magnitude does not.

Finally, do not confuse a successful toy demo with a justified production architecture. A model that can solve a problem is not automatically the right solution.

Summary

  • An ANN can classify odd numbers, but the direct arithmetic rule is strictly better.
  • Parity depends on the least significant bit, so binary encoding is the sensible feature representation.
  • Raw scalar integers often cause poor generalization because parity alternates rather than following a smooth trend.
  • This is a useful teaching exercise for model representation and baselines.
  • In real systems, use n % 2 or n & 1 instead of machine learning.

Course illustration
Course illustration

All Rights Reserved.