AI-Based Odd-Even Predictor in Python on Linux

By Raman Kumar

Updated on Aug 30, 2024

In this tutorial, we'll explain AI-based odd-even predictor in Python on Linux. 

How to Run a Python Script on Ubuntu Using sklearn and numpy: AI-Based Odd or Even Number Prediction
In this tutorial, we will walk you through creating a simple Python script on Ubuntu that uses sklearn and numpy to predict whether a number is odd or even. The script will generate sample data, create a machine learning model, train it, and then use the model to make predictions.

Prerequisites

  • Linux installed dedicated server, KVM VPS or desktop.
  • Python 3 installed on your Ubuntu system.
  • Basic knowledge of Python programming.
  • Familiarity with machine learning concepts is helpful but not necessary.

AI-Based Odd-Even Predictor in Python

Step 1: Install Required Packages

First, you need to install the necessary Python packages, namely scikit-learn (sklearn) and numpy. You can do this using pip:

On Debian/Ubuntu

sudo apt update
sudo apt install python3-pip -y

On Redhat/CentOS/AlmaLinux/RockyLinux

sudo dnf update -y
sudo dnf install python3-pip -y

Step 2: Set Up a Virtual Environment

It's best practice to use a virtual environment for your Flask projects to manage dependencies separately. Create and activate a virtual environment as follows:

sudo apt install python3-venv -y
python3 -m venv env
source env/bin/activate

Your terminal prompt will change to indicate that the virtual environment is active.

Step 3: Generate Sample Data

We will generate a simple dataset where each input is a number, and the output will be 0 for even numbers and 1 for odd numbers.

Create a Python script named odd_even_predictor.py:

nano odd_even_predictor.py

Add the following code to the file:

import numpy as np

# Generate sample data
# X is an array of numbers
# y is the corresponding label (0 for even, 1 for odd)
X = np.arange(1, 10001).reshape(-1, 1)
y = X % 2

# Flatten y to create a 1D array of labels
y = y.flatten()

print("Sample Data Generated:")
print(f"First 10 numbers: {X[:10].flatten()}")
print(f"Corresponding labels: {y[:10]}")

This code generates numbers from 1 to 10001 and labels them as 0 (even) or 1 (odd). The labels are flattened to make them a 1D array.

Step 4: Create and Train the Model

Next, we will create a simple machine learning model using sklearn. We'll use a DecisionTreeClassifier to train the model on our data.

Append the following code to your odd_even_predictor.py script:

from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score

# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Create a Decision Tree model
model = DecisionTreeClassifier()

# Train the model
model.fit(X_train, y_train)

# Predict on the test set
y_pred = model.predict(X_test)

# Evaluate the model
accuracy = accuracy_score(y_test, y_pred)
print(f"Model accuracy: {accuracy * 100:.2f}%")

Step 5: Predict Odd or Even Numbers

Now, let's predict whether a given number is odd or even using the trained model. Add the following code to the script:

# Function to predict if a number is odd or even
def predict_odd_even(number):
    prediction = model.predict(np.array([[number]]))
    return "Odd" if prediction[0] == 1 else "Even"

# Test the prediction function
test_number = 7
result = predict_odd_even(test_number)
print(f"The number {test_number} is {result}.")

Step 6: Run the Python Script

Save the file and run the script:

python3 odd_even_predictor.py

You should see the generated sample data, the model accuracy, and the prediction result for the test number.

Sample Data Generated:
First 10 numbers: [ 1  2  3  4  5  6  7  8  9 10]
Corresponding labels: [1 0 1 0 1 0 1 0 1 0]
Model accuracy: 4.70%
The number 7 is Odd

Step 7: Customize and Extend the Script

You can further customize this script by experimenting with different machine learning algorithms from sklearn, increasing the complexity of the dataset, or adding additional features.

Conclusion

In this tutorial, we covered how to create a simple AI-based odd-even predictor in Python on Linux to predict whether a number is odd or even. We used numpy for data manipulation and scikit-learn (sklearn) for building and training the machine learning model. This basic example demonstrates how you can apply machine learning to even simple problems, giving you a foundation to explore more complex applications.