Your First Machine Learning Project: From Python Data to a Working Model
Build your first machine learning project with Python by turning a small dataset into a working prediction model, from data preparation and feature selection to training, evaluation, and saving the model.

Tools used: Python, VS Code, Jupyter, pandas, NumPy, scikit-learn, Git, GitHub
Prerequisites: Basic Python, variables, functions, lists, dictionaries, and basic familiarity with CSV data.
Your First Machine Learning Project: From Python Data to a Working Model
Machine learning can look intimidating when you first encounter terms such as:
Features
Labels
Training
Validation
Inference
Classification
Regression
Overfitting
Precision
RecallBut your first machine learning project does not need to involve a giant neural network or millions of records.
A much better way to learn is to take a small dataset and follow the complete machine-learning workflow:
Problem
↓
Data
↓
Features
↓
Training
↓
Prediction
↓
Evaluation
↓
ImprovementIn this tutorial, we'll build a small customer-churn classification model with Python and scikit-learn.
The goal isn't to create a production-ready business system.
The goal is to understand what actually happens between:
"I have some data"
and:
"My program can make a prediction from new data."
What You'll Build
By the end of this project, you'll have a Python program that can learn from historical customer information and predict whether a new customer belongs to one of two classes:
Stay
or
ChurnOur simplified dataset will contain information such as:
Monthly spending
Support tickets
Months as customer
Contract length
Churn statusThe workflow will be:
This is the basic pattern you'll encounter repeatedly across machine-learning projects.
1. AI vs Machine Learning
Before writing code, clarify the terminology.
Artificial Intelligence
AI is the broader field concerned with systems that perform tasks associated with capabilities such as reasoning, perception, language understanding, planning, or decision-making.
Machine Learning
Machine learning is one approach within AI where systems learn patterns from data rather than relying entirely on manually written rules.
A simplified relationship is:
Artificial Intelligence
│
├── Machine Learning
│ ├── Supervised Learning
│ ├── Unsupervised Learning
│ └── Reinforcement Learning
│
├── Generative AI
├── Computer Vision
└── Natural Language ProcessingYou don't need to master the entire AI field before building your first ML project.
Start with the machine-learning workflow.
2. What Problem Are We Solving?
Imagine a subscription company wants to identify customers who may leave.
It has historical information:
| Customer | Monthly Spend | Support Tickets | Months Active | Churn |
|---|---|---|---|---|
| A | 20 | 1 | 24 | No |
| B | 80 | 7 | 3 | Yes |
| C | 35 | 2 | 18 | No |
| D | 75 | 6 | 4 | Yes |
| E | 40 | 1 | 20 | No |
We want the computer to learn patterns from these examples.
Then we give it a new customer:
Monthly Spend = 70
Support Tickets = 5
Months Active = 5and ask:
Will this customer churn?This is a classification problem because the output belongs to a category.
3. Classification vs Regression
Machine-learning problems often start with identifying what type of prediction you need.
Classification
Predict a category.
Examples:
Spam / Not Spam
Fraud / Not Fraud
Churn / Stay
Cat / Dog
Approved / RejectedRegression
Predict a numerical value.
Examples:
House price
Sales amount
Temperature
Delivery time
Monthly revenueA useful mental model:
Classification
↓
"What category?"
Regression
↓
"What number?"scikit-learn provides algorithms and tooling for both classification and regression, along with preprocessing and model evaluation.
4. What Is a Feature?
A feature is an input variable used by the model.
In our example:
Monthly Spend
Support Tickets
Months Activeare features.
The thing we want to predict is the target or label:
ChurnSo:
Features
↓
Model
↓
Target PredictionFor example:
Features:
[70, 5, 5]
↓
Machine Learning Model
↓
Prediction:
Churn5. Install the Tools
Create a project:
mkdir ml-first-project
cd ml-first-projectCreate a virtual environment:
python -m venv .venvActivate it on Windows:
.venv\Scripts\activateOn macOS/Linux:
source .venv/bin/activateInstall the packages:
python -m pip install pandas numpy scikit-learnYou can verify the installation:
python -c "import pandas, numpy, sklearn; print('Ready')"A project-specific environment keeps dependencies isolated from unrelated Python projects.
6. Create the Dataset
For our first project, we'll create the dataset directly in Python.
Create:
main.pyStart with:
import pandas as pd
data = {
"monthly_spend": [
20, 80, 35, 75, 40,
90, 25, 65, 30, 85,
45, 70, 22, 95, 38,
60, 28, 78, 32, 88
],
"support_tickets": [
1, 7, 2, 6, 1,
8, 1, 5, 2, 7,
2, 5, 1, 9, 2,
4, 1, 6, 1, 8
],
"months_active": [
24, 3, 18, 4, 20,
2, 30, 5, 16, 3,
22, 5, 28, 2, 19,
7, 26, 4, 15, 3
],
"churn": [
0, 1, 0, 1, 0,
1, 0, 1, 0, 1,
0, 1, 0, 1, 0,
1, 0, 1, 0, 1
]
}
df = pd.DataFrame(data)
print(df)Run:
python main.pyYou now have your first dataset.
7. Inspect the Data
Before training a model, inspect what you're working with.
print(df.head())Check the dimensions:
print(df.shape)Check the columns:
print(df.columns)Check data types:
print(df.dtypes)Check missing values:
print(df.isnull().sum())This step is easy to skip.
Don't skip it.
A machine-learning model cannot magically fix a poorly understood dataset.
8. Separate Features and Target
Now identify:
X = input features
y = targetIn our example:
X = df[
[
"monthly_spend",
"support_tickets",
"months_active"
]
]
y = df["churn"]Conceptually:
X
│
├── monthly_spend
├── support_tickets
└── months_active
y
└── churnThe model learns the relationship between X and y.
9. Why Do We Split the Data?
One of the most important ideas in machine learning is that you shouldn't judge a model only on the data it already saw.
Imagine studying for an exam by memorizing the exact answers and then taking the same questions.
You might score:
100%But that doesn't prove you understand the subject.
Machine learning has a similar problem.
We want the model to perform well on unseen data.
So we split the dataset.
Dataset
│
├── Training Data
│
└── Test DataUse:
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.25,
random_state=42,
stratify=y
)Now:
X_train → training inputs
y_train → training answers
X_test → unseen inputs
y_test → real answers10. Choose a Model
There are many machine-learning algorithms.
For a first classification project, a decision tree is easy to visualize conceptually.
from sklearn.tree import DecisionTreeClassifier
model = DecisionTreeClassifier(
max_depth=3,
random_state=42
)The important idea isn't memorizing this class.
The important idea is:
Dataset
↓
Algorithm
↓
ModelA model is the learned representation produced after fitting an algorithm to data.
11. Train the Model
Training is where the model learns from the examples.
model.fit(X_train, y_train)That's it.
You have trained a machine-learning model.
Conceptually:
X_train + y_train
↓
fit()
↓
Modelscikit-learn estimators commonly follow this fit() pattern and can then be used for prediction.
12. Make Predictions
Now give the model data it hasn't seen during training.
predictions = model.predict(X_test)
print(predictions)You might see:
[0 1 0 1 0]where:
0 = Stay
1 = ChurnThe model is making predictions.
13. Compare Predictions With Reality
We have:
y_testwhich contains the actual answers.
And:
predictionswhich contains the model's predictions.
Compare them:
comparison = pd.DataFrame({
"actual": y_test.values,
"predicted": predictions
})
print(comparison)You might get:
actual predicted
0 0 0
1 1 1
2 0 0
3 1 0
5 1 1Now we can evaluate how well the model performed.
14. Accuracy
A simple metric is accuracy.
from sklearn.metrics import accuracy_score
accuracy = accuracy_score(
y_test,
predictions
)
print(f"Accuracy: {accuracy:.2%}")If the result is:
Accuracy: 80.00%the model correctly classified 80% of the test examples.
But accuracy isn't always enough.
15. Why Accuracy Can Be Misleading
Imagine a fraud dataset:
990 legitimate transactions
10 fraudulent transactionsA terrible model could predict:
Every transaction = legitimateand still achieve:
99% accuracyBut it detected:
0 fraud casesSo we need additional metrics.
16. Precision and Recall
For binary classification, you will frequently encounter:
Precision
Recall
F1 ScorePrecision
Of the cases predicted positive, how many were actually positive?
Precision =
True Positives
--------------------------
True Positives + False PositivesRecall
Of all actual positive cases, how many did the model find?
Recall =
True Positives
--------------------------
True Positives + False NegativesThe correct metric depends on the problem.
For example:
Spam filtering
Fraud detection
Medical screening
Security alerts
Customer churncan have very different costs for false positives and false negatives.
17. Calculate Multiple Metrics
Use:
from sklearn.metrics import (
accuracy_score,
precision_score,
recall_score,
f1_score
)
print(
"Accuracy:",
accuracy_score(y_test, predictions)
)
print(
"Precision:",
precision_score(y_test, predictions)
)
print(
"Recall:",
recall_score(y_test, predictions)
)
print(
"F1:",
f1_score(y_test, predictions)
)For a real project, don't blindly maximize one number.
Understand what the metric means for your problem.
18. Confusion Matrix
A confusion matrix gives you a more detailed view of classification results.
from sklearn.metrics import confusion_matrix
matrix = confusion_matrix(
y_test,
predictions
)
print(matrix)Conceptually:
Predicted
No Yes
Actual No TN FP
Yes FN TPWhere:
TP = True Positive
TN = True Negative
FP = False Positive
FN = False NegativeThis is one of the most useful concepts to understand when evaluating classification models.
19. Try a New Customer
Now comes the exciting part.
Create a new customer:
new_customer = [[
72,
5,
4
]]Predict:
prediction = model.predict(
new_customer
)
print(prediction)You can make the output easier to understand:
if prediction[0] == 1:
print("Prediction: likely to churn")
else:
print("Prediction: likely to stay")You have now created a complete prediction pipeline.
20. The Full Pipeline So Far
Your project has followed:
Collect Data
↓
Inspect Data
↓
Choose Features
↓
Choose Target
↓
Split Dataset
↓
Choose Algorithm
↓
Train Model
↓
Predict
↓
Evaluate
↓
Use Model on New DataThis workflow is more important than memorizing individual algorithms.
21. The Complete Beginner Example
You can combine everything into one file:
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import (
accuracy_score,
precision_score,
recall_score,
f1_score
)
data = {
"monthly_spend": [
20, 80, 35, 75, 40,
90, 25, 65, 30, 85,
45, 70, 22, 95, 38,
60, 28, 78, 32, 88
],
"support_tickets": [
1, 7, 2, 6, 1,
8, 1, 5, 2, 7,
2, 5, 1, 9, 2,
4, 1, 6, 1, 8
],
"months_active": [
24, 3, 18, 4, 20,
2, 30, 5, 16, 3,
22, 5, 28, 2, 19,
7, 26, 4, 15, 3
],
"churn": [
0, 1, 0, 1, 0,
1, 0, 1, 0, 1,
0, 1, 0, 1, 0,
1, 0, 1, 0, 1
]
}
df = pd.DataFrame(data)
X = df[
[
"monthly_spend",
"support_tickets",
"months_active"
]
]
y = df["churn"]
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.25,
random_state=42,
stratify=y
)
model = DecisionTreeClassifier(
max_depth=3,
random_state=42
)
model.fit(X_train, y_train)
predictions = model.predict(X_test)
print(
"Accuracy:",
accuracy_score(y_test, predictions)
)
print(
"Precision:",
precision_score(y_test, predictions)
)
print(
"Recall:",
recall_score(y_test, predictions)
)
print(
"F1:",
f1_score(y_test, predictions)
)
new_customer = [[72, 5, 4]]
prediction = model.predict(new_customer)
if prediction[0] == 1:
print("Prediction: likely to churn")
else:
print("Prediction: likely to stay")This is a small project, but it contains the fundamental pieces of supervised machine learning.
22. Why This Dataset Is Too Simple
Our example is deliberately small.
Real-world data can contain:
Missing values
Categorical columns
Outliers
Incorrect records
Duplicate records
Different units
Text
Dates
Thousands or millions of rowsThat's where machine learning becomes more interesting.
The model isn't usually the hardest part.
Data quality often is.
23. Real Machine Learning Starts With Better Data
Imagine a real customer dataset:
customer_id
age
country
monthly_spend
contract_type
support_tickets
login_frequency
months_active
payment_failures
churnNow you need to ask:
Which columns are useful?
Which contain missing values?
Which are categorical?
Which could leak the answer?
Which should be removed?
Which should be transformed?This is called data preprocessing.
scikit-learn includes preprocessing tools for tasks such as feature extraction and normalization.
24. Categorical Data
Machine-learning algorithms often need numerical representations.
Suppose:
contract_type
monthly
yearlyYou cannot always pass raw text directly into an algorithm.
One common approach is one-hot encoding.
Conceptually:
monthly
yearlybecomes:
is_monthly
is_yearlyFor example:
monthly → [1, 0]
yearly → [0, 1]scikit-learn provides preprocessing utilities for this type of transformation.
25. Missing Data
Real datasets often contain missing values.
Example:
Age
25
31
?
42
?You have to decide what to do.
Possible approaches include:
Remove rows
Fill with a statistic
Use a model-based method
Use a domain-specific valueNever automatically replace every missing value with zero.
Zero may have a completely different meaning.
26. Data Leakage
One of the most dangerous beginner mistakes is data leakage.
Imagine you want to predict:
Will customer churn?and your dataset contains:
cancellation_dateThat's a problem.
The cancellation date may only become known after the customer has already churned.
If you give that information to the model during training, the model can appear extremely accurate for the wrong reason.
The general rule is:
Training data should contain only information that would actually be available when making the prediction.
27. Overfitting
A model can perform extremely well on training data while performing poorly on new data.
This is called overfitting.
Think of it as:
Model
↓
Memorizes training examples
↓
Excellent training score
↓
Poor unseen-data performanceWe want:
Model
↓
Learns useful patterns
↓
Generalizes to unseen dataThis is why evaluation on unseen data matters.
28. Underfitting
The opposite problem is underfitting.
The model is too simple to capture useful patterns.
Too simple
↓
Misses important relationships
↓
Poor performanceSo machine learning often involves finding an appropriate balance:
Underfitting
↓
Good Generalization
↓
Overfitting29. Why Train/Test Splits Aren't the Whole Story
A single test split can be useful, but when you are comparing models or tuning parameters, you need to be careful not to repeatedly optimize against the final test set.
Cross-validation can help estimate performance more reliably during model selection.
A common pattern is:
Training Data
↓
Cross-Validation
↓
Model Selection
↓
Final Evaluation
↓
Test Datascikit-learn provides cross-validation and model-selection tools as part of its ecosystem.
30. Try Another Model
Once your first model works, compare alternatives.
For example:
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(
n_estimators=100,
random_state=42
)
model.fit(X_train, y_train)
predictions = model.predict(X_test)Now compare:
Decision Tree
vs
Random ForestThe goal isn't:
"Which algorithm is coolest?"
The goal is:
"Which approach works appropriately for this problem and data?"
31. Machine Learning Is an Experiment
A good ML workflow often looks like:
Hypothesis
↓
Experiment
↓
Measure
↓
Analyze
↓
Change
↓
Experiment AgainFor example:
Decision Tree
↓
Accuracy = X
Try Random Forest
↓
Accuracy = Y
Improve preprocessing
↓
Accuracy = ZBut remember:
A higher accuracy number isn't automatically a better model.
Choose metrics based on the actual problem.
32. Save the Trained Model
Once you have a model you want to reuse, you can serialize it.
One common Python ecosystem option is joblib.
Install:
python -m pip install joblibSave:
import joblib
joblib.dump(model, "churn_model.joblib")Load later:
model = joblib.load(
"churn_model.joblib"
)Now your application doesn't have to retrain the model every time it starts.
33. Separate Training From Prediction
A better project structure is:
ml-project/
├── data/
├── models/
├── src/
│ ├── train.py
│ └── predict.py
├── notebooks/
├── tests/
├── requirements.txt
└── README.mdThen:
train.py
↓
Train model
↓
Save modeland:
predict.py
↓
Load model
↓
Receive input
↓
Make predictionThis is much closer to how a real application might separate model training from inference.
34. Turn the Model Into an API
Once you have a trained model, you can expose it through an API.
For example:
Frontend
↓
HTTP Request
↓
Python API
↓
Load ML Model
↓
Prediction
↓
JSON ResponseA request could conceptually look like:
{
"monthly_spend": 72,
"support_tickets": 5,
"months_active": 4
}The API could return:
{
"prediction": "churn"
}Now your machine-learning model becomes part of an application.
35. This Is Where AI Engineering Begins
A model sitting inside a notebook is useful for learning.
A model integrated into software is much closer to an AI product.
The progression becomes:
Python
↓
Dataset
↓
ML Model
↓
Evaluation
↓
Model File
↓
API
↓
Application
↓
MonitoringThis is why software-development skills remain valuable in AI.
You don't just need to understand models.
You need to build systems around them.
36. Traditional ML vs Generative AI
Not every AI application needs a large language model.
Traditional machine learning is useful for problems such as:
Classification
Regression
Fraud Detection
Forecasting
Recommendation
Customer Churn
Anomaly DetectionGenerative AI is designed for tasks such as generating:
Text
Images
Audio
Code
Other contentFor example:
Customer Churn
→ Traditional ML
Document Q&A
→ Generative AI + Retrieval
Image Classification
→ Computer Vision
Sales Forecast
→ Regression / Time SeriesChoosing the right approach starts with understanding the problem.
37. Don't Start With Deep Learning Just Because It Sounds Advanced
A beginner might think:
AI
↓
Neural Networks
↓
Transformers
↓
LLMsBut many useful problems can be solved with simpler models.
A good progression is:
Python
↓
Data
↓
Statistics Basics
↓
Classical ML
↓
Model Evaluation
↓
Deep Learning
↓
Generative AIUnderstanding simple models makes advanced systems easier to reason about.
38. A Better AI/ML Learning Path
Once you understand this project, continue with:
Stage 1 — Python
Functions
Collections
OOP
Files
Modules
Virtual EnvironmentsStage 2 — Data
NumPy
pandas
CSV
JSON
Data Cleaning
VisualizationStage 3 — Machine Learning
Classification
Regression
Clustering
Features
Training
Evaluation
Cross-ValidationStage 4 — Advanced ML
Feature Engineering
Hyperparameter Tuning
Ensembles
Pipelines
Model InterpretationStage 5 — Deep Learning
Neural Networks
PyTorch
CNNs
Transformers
EmbeddingsStage 6 — AI Applications
LLM APIs
RAG
Vector Databases
Agents
Evaluation
Deployment
MonitoringDon't rush through all six stages.
Build projects between them.
39. Project Ideas After This One
Once you finish the churn project, don't immediately start another tutorial.
Modify it.
Project 1
Customer Churn PredictorProject 2
Spam Message ClassifierProject 3
House Price PredictorProject 4
Customer SegmentationProject 5
Fraud Detection PrototypeProject 6
Recommendation SystemProject 7
AI Document AssistantThe difficulty should increase gradually.
40. How to Make an ML Project Portfolio-Worthy
A portfolio project shouldn't only contain:
model.fit()
model.predict()Add the engineering around it.
Your project should explain:
Problem
↓
Dataset
↓
Data Cleaning
↓
Feature Selection
↓
Model Choice
↓
Training
↓
Evaluation
↓
Error Analysis
↓
DeploymentAlso document:
Why this model?
Why these features?
What didn't work?
What metric did you choose?
What are the limitations?That demonstrates understanding.
41. What Makes This Different From a Tutorial Project?
A tutorial project says:
"I followed these steps."
A strong portfolio project says:
"I made these decisions."
That difference matters.
For example:
I tested three models.
Decision Tree:
0.78 F1
Random Forest:
0.84 F1
Logistic Regression:
0.81 F1Then explain:
"I selected Random Forest for this experiment because it produced the strongest validation result under the chosen metric, while also remaining practical for the dataset."
Now you are demonstrating reasoning.
42. Common Beginner Mistakes
Mistake 1: Starting with an enormous dataset
Start small.
Understand the pipeline first.
Mistake 2: Focusing only on accuracy
Understand:
Precision
Recall
F1
Confusion Matrixand choose metrics based on the problem.
Mistake 3: Ignoring the data
A sophisticated model cannot automatically rescue poor data.
Mistake 4: Training and testing on the same data
This makes evaluation unreliable.
Use an appropriate evaluation strategy.
Mistake 5: Data leakage
Make sure information from the future or target outcome isn't accidentally included in the input features.
Mistake 6: Comparing models without a consistent evaluation process
Use the same data split or appropriate cross-validation strategy when comparing approaches.
Mistake 7: Building everything inside a notebook
Notebooks are excellent for exploration.
Production systems often need clearer separation between:
Data
Training
Model
API
Application
Tests43. Your First ML Project Checklist
[ ] Define the problem
[ ] Identify the target
[ ] Collect a dataset
[ ] Inspect the data
[ ] Clean the data
[ ] Select features
[ ] Split the data
[ ] Choose a baseline model
[ ] Train the model
[ ] Make predictions
[ ] Evaluate the model
[ ] Analyze errors
[ ] Compare alternatives
[ ] Save the model
[ ] Document the project
[ ] Build an API if appropriate
[ ] Add tests
[ ] Deploy if usefulYou don't need every item for your first experiment.
But this checklist gives you a path toward a real ML project.
44. What You Should Understand After This Project
You should now be able to explain:
What is a feature?
What is a target?
What is supervised learning?
What is classification?
Why do we split data?
What does model.fit() do?
What does model.predict() do?
Why do we evaluate on unseen data?
What is overfitting?
What is data leakage?
Why isn't accuracy always enough?
What are precision and recall?
Why does preprocessing matter?If you can explain these concepts in your own words, you've made meaningful progress.
45. The Bigger Picture
Machine learning is not:
Dataset
↓
Magic AI
↓
Perfect PredictionA more realistic picture is:
Real Problem
↓
Data Collection
↓
Data Cleaning
↓
Feature Engineering
↓
Model Selection
↓
Training
↓
Evaluation
↓
Error Analysis
↓
Iteration
↓
Deployment
↓
Monitoring
↓
ImprovementThe model is only one component.
46. From This Tiny Project to a Real AI System
Your first project might look like:
Python
+
pandas
+
scikit-learnA larger system might eventually look like:
Data Sources
↓
Data Pipeline
↓
Storage
↓
Feature Processing
↓
ML Model
↓
Model Registry
↓
API
↓
Application
↓
MonitoringThat is the bridge between:
Learning Machine Learningand:
Building Machine-Learning Systems47. Final Takeaway
You don't need to begin your AI journey by training a massive neural network.
Start much smaller.
Take a dataset.
Ask a useful question.
Choose features.
Train a model.
Test it on unseen data.
Study where it fails.
Improve it.
Then turn it into an application.
The most important transition is:
Reading about ML
↓
Writing ML code
↓
Understanding ML results
↓
Building ML systemsYour first model probably won't be impressive.
That's okay.
The purpose of the first project isn't to build the world's best model.
It's to understand the complete journey from:
data → learning → prediction → evaluation → application.
Once that workflow makes sense, more advanced AI topics become much easier to learn.
Don't start by trying to build the biggest AI model. Start by learning how to turn data into a useful prediction.







Comments (0)
Be the first to share your thoughts.