AI With Python 2026 (Part 8): Your First Machine Learning Model — From Data to Predictions

In Part 7, we explored the fundamentals of Machine Learning.
We learned what Machine Learning is, how it differs from the broader field of Artificial Intelligence, the three major types of Machine Learning, and how computers learn patterns from data.
Now, it is time to move from understanding the concepts to building something practical.
Your First Machine Learning Model
For many beginners, building a Machine Learning model sounds complicated.
Algorithms. Training data. Testing data. Predictions. Accuracy.
There are many new terms to understand.
But the fundamental process is simpler than it first appears.
In this article, we will walk through the complete Machine Learning workflow and build a simple predictive model using Python and Scikit-learn.
Welcome to Part 8 of AI With Python 2026.
What Are We Going to Build?
We will create a simple Machine Learning model that predicts a student’s examination score based on the number of hours they studied.
The idea is simple:
Input: Hours Studied
Output: Predicted Examination Score
For example:
A student studies for 2 hours → What score might they achieve?
A student studies for 6 hours → What score might they achieve?
The Machine Learning model will examine existing data, identify the relationship between study time and examination scores, and use that relationship to make predictions.
This is a basic supervised learning regression problem.
Understanding the Machine Learning Workflow
Most Machine Learning projects follow a similar process:
Define the Problem → Collect Data → Prepare Data → Split the Data → Choose a Model → Train the Model → Make Predictions → Evaluate the Model → Improve the Model
Understanding this workflow is more important than memorizing hundreds of algorithms.
Let’s walk through each stage.
Step 1: Define the Problem
Every successful Machine Learning project begins with a clearly defined problem.
Our problem is:
Can we use the number of hours a student studies to predict their examination score?
This is a prediction problem because we want our model to estimate a numerical value.
Clearly defining the problem helps determine:
- What data we need
- What Machine Learning approach to use
- Which algorithm may be appropriate
- How we will evaluate success
Do not start by choosing an algorithm.
Start by understanding the problem.
Step 2: Collect the Data
Machine Learning models learn from examples.
For our project, imagine we have collected the following dataset:

The model will use these examples to learn the relationship between study hours and examination performance.
In real-world projects, datasets may contain thousands or millions of records.
But the principle remains the same.
Machine Learning systems learn from data.
Step 3: Prepare the Data
Before training our model, we need to separate our dataset into:
Features (X)
The information the model uses to make predictions.
In our example:
Hours Studied
Target (y)
The value the model is trying to predict.
In our example:
Examination Score
Our Python code could look like this:
import pandas as pd
data = {
"hours_studied": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
"exam_score": [35, 42, 50, 58, 65, 72, 78, 85, 90, 95]
}
df = pd.DataFrame(data)
X = df[["hours_studied"]]
y = df["exam_score"]
Notice that X is written with double square brackets.
This keeps the feature data in a two-dimensional format expected by many Scikit-learn models.
Step 4: Split the Dataset
One of the most important concepts in Machine Learning is separating data into:
- Training Data
- Testing Data
The training data teaches the model.
The testing data evaluates whether the model can make predictions on data it has not seen before.
A common split might be:
80% Training Data
20% Testing Data
We can use Scikit-learn to perform the split:
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.2,
random_state=42
)
Why do we need testing data?
Because a model that performs well only on its training data may not work well when given new information.
The goal is not simply to memorize the dataset.
The goal is to generalize.
Step 5: Choose a Machine Learning Model
Our dataset appears to have a relatively straightforward relationship between study hours and examination scores.
For this beginner project, we will use:
Linear Regression
Linear Regression is an algorithm used to predict continuous numerical values.
Examples include predicting:
- House prices
- Sales revenue
- Electricity consumption
- Crop yields
- Examination scores
Scikit-learn provides an implementation of Linear Regression.
from sklearn.linear_model import LinearRegression
model = LinearRegression()
At this stage, we have created the model.
But it has not learned anything yet.
Step 6: Train the Model
Training is the process where the Machine Learning algorithm studies the training data and learns patterns from it.
We train our model using:
model.fit(X_train, y_train)
This single line of code performs an important operation.
The model analyzes the relationship between the study hours and examination scores in the training dataset.
It then learns parameters that can be used to make predictions.
The model has now been trained.
Step 7: Make Predictions
Once the model has been trained, we can use it to make predictions.
First, we can predict examination scores for the testing dataset:
predictions = model.predict(X_test)
print(predictions)
We can also provide new data.
For example, suppose a student studies for 6.5 hours.
new_student = pd.DataFrame({
"hours_studied": [6.5]
})
predicted_score = model.predict(new_student)
print(predicted_score)
The model will estimate the student’s examination score based on the pattern it learned from the training data.
You have now built a system that can learn from examples and make predictions.
Step 8: Evaluate the Model
Building a model is not enough.
We need to determine how well it performs.
For regression problems, several evaluation metrics can be used.
One beginner-friendly metric is:
Mean Absolute Error (MAE)
MAE calculates the average difference between the model’s predictions and the actual values.
from sklearn.metrics import mean_absolute_error
mae = mean_absolute_error(y_test, predictions)
print("Mean Absolute Error:", mae)
A smaller MAE generally indicates that the model’s predictions are closer to the actual values.
Another commonly used metric is:
R² Score
The R² score helps measure how well the model explains variation in the target variable.
from sklearn.metrics import r2_score
r2 = r2_score(y_test, predictions)
print("R² Score:", r2)
No single evaluation metric tells the entire story.
The appropriate metric depends on the problem you are solving.
Step 9: Visualize the Results
Remember what we learned in Part 6?
Visualization helps us understand our data and models.
We can use Matplotlib to visualize the relationship between study hours and examination scores.
import matplotlib.pyplot as plt
plt.scatter(X["hours_studied"], y)
plt.plot(
X["hours_studied"],
model.predict(X)
)
plt.xlabel("Hours Studied")
plt.ylabel("Examination Score")
plt.title("Study Hours vs Examination Scores")
plt.show()
The scatter points represent the original data.
The line represents the relationship learned by the Linear Regression model.
This visualization helps us inspect whether the model fits the data reasonably well.
The Complete Machine Learning Code
Here is the complete project:
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, r2_score
from sklearn.model_selection import train_test_split
data = {
"hours_studied": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
"exam_score": [35, 42, 50, 58, 65, 72, 78, 85, 90, 95]
}
df = pd.DataFrame(data)
X = df[["hours_studied"]]
y = df["exam_score"]
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.2,
random_state=42
)
model = LinearRegression()
model.fit(X_train, y_train)
predictions = model.predict(X_test)
mae = mean_absolute_error(y_test, predictions)
r2 = r2_score(y_test, predictions)
print("Mean Absolute Error:", mae)
print("R² Score:", r2)
new_student = pd.DataFrame({
"hours_studied": [6.5]
})
predicted_score = model.predict(new_student)
print("Predicted Score:", predicted_score[0])
plt.scatter(X["hours_studied"], y)
plt.plot(
X["hours_studied"],
model.predict(X)
)
plt.xlabel("Hours Studied")
plt.ylabel("Examination Score")
plt.title("Study Hours vs Examination Scores")
plt.show()
Congratulations.
You have now walked through the complete workflow for building a simple Machine Learning model.
What Just Happened?
Let’s summarize the process.
We:
- Defined a prediction problem.
- Created a dataset.
- Separated features from the target.
- Split our data into training and testing sets.
- Selected a Linear Regression algorithm.
- Trained the model.
- Made predictions.
- Evaluated the results.
- Visualized the model.
This fundamental workflow appears again and again in Machine Learning projects.
The datasets may become larger.
The algorithms may become more sophisticated.
The infrastructure may become more complex.
But the core development process remains recognizable.
Training vs Testing: Why the Difference Matters
A common beginner mistake is training and evaluating a model using the same dataset.
This can produce misleading results.
Imagine giving students the exact questions and answers before an examination and then using the same examination to measure their understanding.
High scores would not necessarily mean they learned how to solve new problems.
Machine Learning models face a similar challenge.
Testing data helps us measure whether a model can work with unseen examples.
This ability is called:
Generalization
A useful Machine Learning model should perform well beyond the data it memorized during training.
Common Beginner Mistakes
As you begin building Machine Learning models, avoid these common mistakes:
Using Poor-Quality Data
Missing, inaccurate, or biased data can lead to unreliable models.
Skipping Data Exploration
Always understand and visualize your dataset before training a model.
Training and Testing on the Same Data
This prevents you from properly evaluating generalization.
Choosing Complex Algorithms Too Early
Start with simple models.
A more complicated algorithm does not automatically produce better results.
Focusing Only on Accuracy
Evaluation metrics must match the real-world problem you are solving.
Ignoring the Problem You’re Trying to Solve
Machine Learning is a tool.
Start with the problem — not the algorithm.
A Professional Mindset
Beginner mindset:
“I trained a Machine Learning model. The project is finished.”
Machine Learning mindset:
“I trained, evaluated, tested, and improved a model that solves a clearly defined problem.”
Building the model is only one part of the Machine Learning lifecycle.
A Simple Challenge for You
Take the project from this article and modify it.
Try:
- Adding more student records
- Changing some examination scores
- Predicting scores for different study hours
- Comparing the predicted values with the original dataset
- Visualizing the results
Then choose another simple prediction problem.
For example:
- Advertising budget → Sales
- Rainfall → Crop yield
- Website traffic → Revenue
- Temperature → Electricity consumption
Follow the same Machine Learning workflow.
The goal is not to copy the code.
The goal is to understand the process.
Why This Matters for Your AI Journey
You have crossed an important point in this series.
You started by understanding Artificial Intelligence.
Then you learned about data, NumPy, Pandas, visualization, and Machine Learning concepts.
Now, you have built your first predictive model.
The next stage is learning how modern applications connect to powerful AI systems and Generative AI models.
What’s Coming Next
In Part 9, we will explore:
AI APIs and Generative AI — Connecting Python to Intelligent Models
You’ll learn:
- What AI APIs are
- How Python applications communicate with AI models
- The role of Large Language Models
- Text and image generation
- Building AI-powered applications with APIs
- API keys, security, cost management, and responsible development
This is where we begin connecting Python applications to modern Generative AI systems.
Series Schedule Reminder
Wednesdays → AI With Python 2026
Mondays → Broader tech, AI, cybersecurity, broadcasting technology, and innovation articles
The first Machine Learning model you build may be simple.
But understanding the workflow behind it gives you the foundation to build increasingly powerful systems.
Define the problem. Understand the data. Train the model. Evaluate the results. Improve continuously.
See you in Part 9.
Previous: 5 Powerful Cisco Troubleshooting Commands Every Network Technician Should Know
Next: Master Control Room (MCR) & Production Control Room (PCR): A Complete Guide
Leave a comment