Would a machine learning classifier algorithm be able to determine whether a number is odd or even? I was testing out some classifier algorithms in scikit but wasn't able to find a classifier (linear or non-linear) that managed to provide good prediction on whether an input number is odd or even. Here's the code:
import numpy as np
from sklearn.linear_model import SGDClassifier
from sklearn.linear_model import LogisticRegression, LogisticRegressionCV, RidgeClassifierCV
from sklearn.svm import SVC, NuSVC
length = 10000

evens = np.array([np.arange(0, length*2, 2)])
zeroes = np.array([np.resize([[0]], length)])

odds = np.array([np.arange(1, length*2, 2)])
ones = np.array([np.resize([[1]], length)])

evens_data = np.concatenate((evens.T, zeroes.T), axis=1)
odds_data = np.concatenate((odds.T, ones.T), axis=1)

data = np.array([np.append(evens_data, odds_data)]).reshape(length*2, 2)
np.random.shuffle(data)
X = np.array([data[:,0]]).reshape(length*2,1)
y = data[:,1]

## 
## Tried all algorithms below
##
# clf = LogisticRegression(random_state=42, max_iter=1000)
# clf = LogisticRegressionCV(cv=5, random_state=42, max_iter=1000)
# clf = RidgeClassifierCV(cv=5)
# clf = SGDClassifier(max_iter=1000)
# clf = SVC(random_state=42, max_iter=1000)
clf = NuSVC(random_state=42)
clf.fit(X, y)

for tuple_ in [(np.arange(0, 20, 2), 0), (np.arange(1, 22, 2), 1)]:
    X, y = tuple_
    for x in X:
        predicted = clf.predict([[x]])
        print(f'{"Good" if predicted[0] == y else "Bad"} predicting: {x} is {predicted[0]} and it should be {y}')

I anticipate some people saying that I could (should) have processed my data in a more machine learning ready way (like translating it to binary) but I didn't want to do that as my idea is to being able to find a classifier algorithm that could clusterize the data based on features not as clear as odd/even but on something the analyst couldn't foresee just by looking at the data.
I wonder if Linear or SVM-based classifier algorithms aren't able to do that. If not, I'd appreciate someone explaining why not.
Also, (if Linear / SVM-based classifiers are not indicated for this job) what would be the right tool for that?
 A: As is often the case, the issue is one of defining your features.
If you use the digits of the binary expansion of the number as features, your classifiers should have no problem picking up the fact that only one feature perfectly separates the target classes.
Here  I construct an example where the training data is 500 integers randomly selected from $\{1,2, \dots, 1000\}$ and use linear regression to classify:
y <- sample(1:1000, 500, replace=FALSE)

x <- t(matrix(as.integer(intToBits(y)), 32))
x <- x[, 1:10]  # as the numbers < 1001 don't use any higher bits

tgt <- y %% 2

train_data <- data.frame(cbind(tgt,x))
m1 <- lm(tgt~., data=train_data)

y_pred <- sample(1:1000, 10, replace=FALSE)
x_pred <- t(matrix(as.integer(intToBits(y_pred)), 32))[, 1:10]
test_data <- data.frame(x_pred)

test_results <- data.frame(actual = y_pred, odd_even = predict(m1, test_data))

# Clean up the results, as floating point math doesn't always give exact integers
test_results$cleaned_odd_even <- ifelse(test_results$odd_even < 1e-10, 0, 1)

and the results:
> test_results
   actual      odd_even cleaned_odd_even
1     727  1.000000e+00                1
2     544 -1.311871e-15                0
3     689  1.000000e+00                1
4     647  1.000000e+00                1
5     444 -1.116987e-15                0
6      89  1.000000e+00                1
7     168 -1.229638e-15                0
8     770 -1.401580e-15                0
9     870 -1.107620e-15                0
10     31  1.000000e+00                1

This would allow you to classify any non-negative integer based on its lowest order 10 bits (or however many bits we include).  The algorithm figured out that only the lowest order bit mattered.
A: This is a fun little problem.
@jbowman notes

"As is often the case, the issue is one of defining your features".

One way to engineer a feature for this problem is to look at the last digit of the number. Here is a simple little script in sklearn
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, FunctionTransformer

@np.vectorize
def get_last_digit_of_float(x):
    str_x = str(x)
    if len(str_x) == 1:
        return int(str_x)
    else:
        return int(str_x[-1])

last_digit_transformer = FunctionTransformer(get_last_digit_of_float)

def main():

    train_set = np.arange(100).reshape(-1, 1)
    y_train = np.arange(100) % 2
    test_set = np.arange(100, 200).reshape(-1, 1)
    y_test = np.arange(100, 200) % 2

    model = make_pipeline(
        last_digit_transformer,
        OneHotEncoder(categories='auto', sparse=False, handle_unknown='error', drop='first'),
        LogisticRegression(solver='lbfgs', multi_class='multinomial')
    )

    model.fit(train_set, y_train)

    print('Test Set Accuracy:', model.score(test_set, y_test))


if __name__ == '__main__':
    main()

This returns a test set accuracy of 1.0.  The trick here is to turn the last digit of the number into a feature and then one hot encode the number. This works because any number which ends in an even number is also even.  The result is a design matrix with 9 columns (numbers 1 through 9, 0 is not needed in this case since it is absorbed by the intercept in Logistic regression).  As always, a clever feature engineering approach is all that is needed.
A: A sine curve should do the trick. Pick a sine curve with a vertical distance of $1$ and a period of 2 so the curve hits $0$ at the even numbers and $1$ at the odd numbers. Then the output is the probability of being off vs even, and the predicted probabilities exactly match the labels.
If you want to make an optimizer do some work, you could consider a model like $y=a+b\sin(cx+d)$, where you let the optimizer figure out the amplitude, frequency, phase shift, and vertical shift.
A: This answer won't solve your problem directly, but I think it's important to give a more philosophical interpretation, otherwise the question might results a bit confusing for a beginner.
I am a statistician, not a machine learning or computer science expert, so expect inaccuracies and superficiality in the content (please, feel free to enrich it with more technical details, I would be thankful).
Here comes the point:
As previous answers and comments pointed out, the answer to this question is completely deterministic. You don't need a machine learning algorithm to solve it, because if you know the definition of odd and even number, that itself would be the trivial solution to the question. This solution can be interpreted and solved straightforwardly by any basic machine. To be more practical, for most modern programming languages this problem can be answer by a single IF statement: IF (the number can be divided by 2 with reminder equal to zero) THEN (even) ELSE (odd). Naturally, in the all answers provided above they assumed to know this definition and they built the model around it. Inevitably the accuracy will be always 1. And I can tell you more: if I know the definition there are infinite perfect solutions to your problem, think about it!
Imagining that we don't know the definition of even/odd number. How do I solve this problem? Well, I don't really know what is the problem you are trying to solve because a real problem would come with a set of features, that is some real (and imperfect) pieces of information that we have available to classify odd and even numbers.
To sum it up, do we know the definition of odd or even number?

*

*YES. Then, there is no need for classification algorithms because we know the answer already and it is straightforwardly translatable in machine language.

*NO. Then, we need some real data (features) and a trial-and-error strategy to understand what's the best model in terms of accuracy.

I hope this helps providing a different view point.
A: I think a linear model can't do it because there is no direct or inverse relationship between a number (your feature) and the class it belongs to (odd/even). I mean, you can't say something like "as the number gets bigger it will tend to be odd". Also, there are no clusters of even and odd numbers, both classes are uniformly distributed in the set of integer numbers, so SVM, KNN or any clustering algorithm will fail as well.
I think you should ask yourself the following: "How can I recognize whether a number is even or odd if the only thing I know is the number itself?" well, there are a bunch of ways to do that. For example, you can divide by two and check if the result is an integer or decimal, but linear models (or any ML model, I think) know nothing about integers or decimal numbers, so they can't help you. Other ways would be using transformations as described in the previous answers but, again, a linear model won't be able to create a binary or sine transformation (perhaps a deep ANN can do something like the sine transform, but I'm not sure).
At the end, I think the answer was already given:

"...the issue is one of defining your features".

You need to help the ML model by providing useful features.
