Neural Network – How to Train to Distinguish Between Even and Odd Numbers

categorical dataclassificationgenetic algorithmsmachine learningneural networks

Question: is it possible to train a NN to distinguish between odd and even numbers only using as input the numbers themselves?

I have the following dataset:

Number Target
1      0
2      1
3      0
4      1
5      0
6      1
...   ...
99     0
100    1

I trained a NN with two input neurons (one being the variable Number, the other being a bias neuron), nine neurons in the hidden layer and one output neuron using a very simple genetic algorithm: at each epoch, two sets of weights "fight" against each other; the one with the highest error loses and it's replaced by a modified version of the winner.

The script easily solve simple problems like the AND, the OR and the XOR operators but get stuck while trying to categorise odd and even numbers. Right now the best it managed to do is to identify 53 numbers out of 100 and it took several hours. Whether I normalize or not the inputs seems to make no difference.

If I wanted to cheat I could just pre-processed the data and feed % 2 to the NN as an input but I don't want to do that; NN should be able to approximate every function, including the modulo operator (I believe). What am I doing wrong?

Best Answer

As with any machine learning task, the representation of your input plays a crucial role in how well you learn and generalise.

I think, the problem with the representation is that the function (modulo) is highly non-linear and not smooth in the input representation you've chosen for this problem.

I would try the following:

  1. Try a better learning algorithm (back-propagation/gradient descent and its variants).

  2. Try representing the numbers in binary using a fixed length precision.

  3. If your input representation is a b-bit number, I would ensure your training set isn't biased towards small or large numbers. Have numbers that are uniformly, and independently chosen at random from the range $[0, 2^b-1]$.

  4. As you've done, use a multi-layer network (try 2 layers first: i.e., hidden+output, before using more layers).

  5. Use a separate training+test set. Don't evaluate your performance on the training set.