Training a model is one line of code: model.fit(X, y). Everything around that line is what makes a machine learning project succeed or fail. Professionals follow the same workflow every time, whether they're predicting house prices or detecting fraud.
This guide walks through the ten steps of that workflow with one complete, runnable Python example: a spam filter that predicts whether an email is spam from the words and characters it contains, using the public Spambase dataset.
The workflow at a glance
- Define the problem
- Collect the data
- Explore the data
- Prepare the data
- Split the data
- Build a baseline
- Train models
- Evaluate
- Tune and improve
- Deploy and monitor
It's not a straight line. You'll loop back often: evaluation shows a problem, so you return to preparing the data or collecting more.
In the picture, steps 7 to 9 are the inner loop you'll repeat most. The dashed arrow is the outer loop: a model in use produces new data and new questions.
Step 1: define the problem
Before any code, answer four questions:
- What decision will the model help with? Here: which emails go to the spam folder.
- What exactly is predicted? Spam or not spam: a binary classification problem.
- How will we measure success? Accuracy, but also how many real emails end up in the spam folder, because losing a real email is far worse than seeing one spam.
- Is ML even needed? If a simple rule works, use the rule.
Getting this step wrong wastes every later step. A model that predicts the wrong thing perfectly is useless.
Step 2: collect the data
Real projects pull data from databases, CSV exports, APIs or logs. Here, scikit-learn downloads the data from OpenML:
Download the data: spambase.csv (1.1 MB), or from the original source, the UCI Machine Learning Repository. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with
pd.read_csv("spambase.csv").
from sklearn.datasets import fetch_openml
X, y = fetch_openml(data_id=44, as_frame=True, return_X_y=True) # Spambase
y = y.astype(int)
print(X.shape) # (4601, 57): 4,601 emails, 57 numbers each
X holds the features, the inputs: how often words such as "free" and "money" appear, how often "!" and "$" appear, and how long the runs of capital letters are. y holds the target, the answer: 1 for spam, 0 for not spam.
Step 3: explore the data
Look before you model. This is called exploratory data analysis (EDA):
print(y.value_counts()) # 0: 2,788 not spam, 1: 1,813 spam
print(X.isna().sum().sum()) # 0 missing values
print(X.duplicated().sum()) # 394 duplicate rows
print(X.describe().T.head()) # ranges of the first few features
Things to check:
- Class balance: 61% not spam, 39% spam. Not badly imbalanced, but worth remembering.
- Missing values: none here. Real data almost always has some.
- Duplicates: 394 rows are exact copies of other rows. If a copy lands in the training set and its twin in the test set, the test score is a little too optimistic. We keep them here to keep the example short; remove duplicate rows shows how to handle them.
- Scales: the capital-letter counts go into the thousands, while most word percentages are below 1, which matters for some models.
- Charts: histograms of each feature and a correlation heatmap often reveal problems and ideas.
Step 4: prepare the data
Typical preparation includes filling or removing missing values, converting text categories into numbers, removing duplicates, fixing obvious errors, and scaling features so large numbers don't dominate. Here, the data is clean, and we'll handle scaling inside a pipeline in step 7.
Step 5: split the data
The model must be judged on data it has never seen, or you'll fool yourself. Hold back a test set now, and don't touch it until the very end:
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, stratify=y
)
test_size=0.2keeps 20% (921 emails) for the final test.stratify=ykeeps the same spam/not-spam ratio in both parts.random_state=42makes the split the same every time you run it.
Step 6: build a baseline
A baseline is the simplest possible "model". Here, always predict the most common class:
from sklearn.dummy import DummyClassifier
baseline = DummyClassifier(strategy="most_frequent").fit(X_train, y_train)
print(round(baseline.score(X_test, y_test), 3)) # 0.606
61% accuracy while learning nothing at all. Any real model must beat this clearly. Without a baseline, "90% accuracy" sounds impressive even when it isn't.
Step 7: train a model
Now a real model: logistic regression, with feature scaling, combined in a pipeline so the scaling is learned from the training data only:
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
Start simple. A simple model you understand is a better first step than a complex one you don't.
Step 8: evaluate with cross-validation
Instead of judging the model on a single split, cross-validation trains and tests it five times on different slices of the training data, and averages the results:
from sklearn.model_selection import cross_val_score
scores = cross_val_score(model, X_train, y_train, cv=5)
print(scores.mean().round(3)) # 0.924
92% against the baseline's 61%: the model has genuinely learned something. In later lessons you'll look beyond accuracy, at precision for the spam class: how many of the emails it sends to spam really are spam.
Step 9: tune and improve
Try changing one thing at a time and compare cross-validation scores. Here, C controls how strongly logistic regression is kept simple:
for C in [0.01, 0.1, 1, 10]:
tuned = make_pipeline(StandardScaler(), LogisticRegression(C=C, max_iter=1000))
print(C, cross_val_score(tuned, X_train, y_train, cv=5).mean().round(3))
# 0.01 0.908
# 0.1 0.918
# 1 0.924
# 10 0.923
The default, C=1, is already among the best. Other ways to improve: better features, more data, other algorithms such as random forests or gradient boosting.
Only when you've chosen your final model do you use the test set, once:
model.fit(X_train, y_train)
print(round(model.score(X_test, y_test), 3)) # 0.929
92.9% on emails it has never seen, close to the cross-validation estimate of 92.4%, so we didn't fool ourselves.
Step 10: deploy and monitor
A model is only useful when people can use it:
- Save it with
joblib.dump(model, "model.joblib"). - Serve it: an API that other software calls, a web app, or a nightly batch job.
- Monitor it: the world changes, so real-world data drifts from the training data and accuracy slowly drops. Track performance and retrain when needed.
Mistakes to avoid at each step
| Step | Mistake |
|---|---|
| Define | Optimising accuracy when the real cost is in missed cases |
| Explore | Skipping it, and missing duplicates, errors or leaks |
| Prepare | Scaling or filling missing values using the whole dataset before splitting: this leaks test information |
| Split | Using the test set repeatedly while tuning, until it's no longer "unseen" |
| Baseline | Not having one, so you can't tell if 90% is good |
| Deploy | Never checking the model again after launch |
Key takeaways
- The workflow is: define, collect, explore, prepare, split, baseline, train, evaluate, tune, deploy and monitor.
- Hold back a test set early and use it only once, at the end.
- Always compare against a simple baseline.
- Use pipelines and cross-validation to get honest, reliable scores.
- Expect to loop back: ML is iterative.
Practice
- Replace logistic regression with a random forest and compare its cross-validation score.
Show the answer
from sklearn.ensemble import RandomForestClassifier
forest = RandomForestClassifier(random_state=42)
print(cross_val_score(forest, X_train, y_train, cv=5).mean().round(3))
It scores 0.954, three points better than logistic regression's 0.924. Random forests can combine features in ways a straight-line model can't, such as "lots of capitals and lots of '$'". They don't need feature scaling, so no pipeline is required.
- Why is
stratify=yuseful when splitting?
Show the answer
It keeps the proportion of each class the same in the training and test sets. Without it, a random split could, by chance, put too few spam emails in the test set, making the evaluation unreliable. It matters most when classes are imbalanced.
- A colleague scales the whole dataset with
StandardScaler, then splits it into train and test sets. What's wrong?
Show the answer
Data leakage: the scaler learned the mean and spread from all rows, including the test rows, so information from the test set leaked into training. Split first, then fit preparation steps on the training data only. A pipeline does this automatically.
Interview questions
Walk me through an end-to-end machine learning project.
Define the problem and success metric with stakeholders; collect data; explore it; clean and engineer features; split into train and test sets; build a baseline; train and compare models with cross-validation; tune hyperparameters; evaluate once on the held-out test set; deploy; then monitor performance and data drift and retrain as needed.
Why do we need a baseline model?
A baseline, such as predicting the majority class or the mean, sets the minimum performance a useful model must beat. It reveals when a high-sounding score is actually trivial, for example 95% accuracy on data where 95% of examples belong to one class.
What is the difference between a validation set and a test set?
The validation set (or cross-validation folds) is used during development to compare models and tune hyperparameters. The test set is held out until the end and used once to estimate real-world performance. Reusing the test set for decisions makes its score optimistic.
What is data drift?
A change over time in the distribution of the data a model receives in production compared with its training data, such as customer behaviour shifting after a price change. It usually degrades accuracy, so models are monitored and retrained.
What to learn next
- Build your intuition for the maths, starting with linear algebra for machine learning.
- Revisit machine learning for beginners and try the workflow on the iris dataset yourself.