Setting Up a Simple ML Project: Tools and Platforms

Set up a small, reproducible machine learning project in Python: the tools you need, where to run them, and a worked scikit-learn example with a baseline.

AI & ML

Most first machine learning projects don’t fail on the model. They fail because nobody can run them again a month later: the notebook depends on a library version that has since changed, the data split was different each time, and there is no record of which experiment produced the number in the slide deck. Setting the project up properly takes about fifteen minutes and saves you from all of that.

This article walks through that setup. It covers the small set of tools a first project needs, where to run them (your laptop, a free hosted notebook or a cloud ML platform), and a worked example that trains and compares models on a dataset that ships with scikit-learn. Every number in the example came from actually running the code.

If the terms feature, label and test set are new, read Key Concepts and Terminologies in ML first. The evaluation ideas used here are covered in more depth in Introduction to Model Training and Evaluation.

The shape of a small ML project

Whatever the problem, a supervised learning project goes through the same loop. You frame the question, get data, split it, try a few models against a baseline, evaluate the best one once on held-out data, and save it so something else can use it.

flowchart LR
    A[Frame the problem] --> B[Get and inspect data]
    B --> C[Split train and test]
    C --> D[Baseline model]
    D --> E[Try candidate models]
    E --> F{Beats baseline?}
    F -- No --> B
    F -- Yes --> G[Final test evaluation]
    G --> H[Save model and versions]

The loop back from “beats baseline?” to the data is the important part. When a model disappoints, the fix is more often in the data or the features than in a different algorithm, a point AI is Transforming Industries: The Role of Data in Machine Learning makes at length.

Framing the problem comes first because it decides everything after it. Write down, in one sentence, what you are predicting, from which inputs, and how you’ll judge success. “Predict a diabetes progression score one year out from ten baseline measurements, judged by mean absolute error” is a usable framing. “Use AI on our patient data” is not.

The tools you need

A first project needs very little. Python is the default language for machine learning because the libraries are there, not because it is fast; the heavy numerical work runs in compiled code underneath.

JobToolWhy this one
Isolated environmentvenv (built into Python)Keeps project libraries separate from the system and from other projects
Data handlingpandas, NumPyTables, filtering, joins and fast array maths
Classical modelsscikit-learnConsistent API for preprocessing, models, cross-validation and metrics
ExplorationJupyterLab or VS Code notebooksRun code in cells and see tables and plots inline
PlotsMatplotlib (optionally seaborn)Residual plots, distributions, actual-versus-predicted charts
Saving modelsjoblibSaves fitted estimators to disk, as documented by scikit-learn
Version controlGitTrack code and configuration, not large data files
Deep learning, laterPyTorch or TensorFlowOnly when you move to images, text or very large datasets

Two things are deliberately missing. You don’t need a deep learning framework for tabular data with a few hundred or thousand rows; scikit-learn’s linear models and tree ensembles are the right starting point and train in seconds on a laptop. And you don’t need a GPU. GPUs pay off for neural networks, not for the algorithms covered in Choosing an ML Algorithm: A Comparative Guide.

Setting up the environment

Create a project folder, a virtual environment inside it, and install the libraries:

mkdir diabetes-ml && cd diabetes-ml
python3 -m venv .venv
source .venv/bin/activate        # on Windows: .venv\Scripts\activate
pip install scikit-learn pandas matplotlib jupyterlab
pip freeze > requirements.txt
git init
printf ".venv/\nmodels/\ndata/raw/\n" > .gitignore

pip freeze writes the exact version of every installed package into requirements.txt. Commit that file. Anyone, including you on a new machine, can then rebuild the same environment with pip install -r requirements.txt. Without it, “works on my machine” becomes “worked on my machine in March”.

A layout that stays manageable as the project grows:

diabetes-ml/
  data/raw/          # original data, never edited, not in Git
  notebooks/         # exploration only
  train.py           # model comparison
  final.py           # final fit, test evaluation, save
  models/            # saved models, not in Git
  requirements.txt

The split between notebooks and scripts matters. Notebooks are good for looking at data, but cells can run out of order and hide state. Once you know what you want to do, move it into a script that runs top to bottom with one command.

Why commit the output of pip freeze to Git?

  • It makes the libraries install faster
  • It records exact library versions so the environment can be rebuilt
  • Git needs it to track Python files

Correct! Pinned versions in requirements.txt let anyone recreate the same environment and get the same results.

Where to run it

You have three realistic options, and for a first project the cheapest one is usually right.

flowchart TD
    Q[Where should the code run?] --> L{Small data, no GPU needed?}
    L -- Yes --> Local[Laptop with venv and JupyterLab]
    L -- No --> T{Team, governance or cloud data?}
    T -- No --> Hosted[Hosted notebook: Colab or Kaggle]
    T -- Yes --> Cloud[Cloud ML platform]
    Cloud --> V[Vertex AI on Google Cloud]
    Cloud --> S[SageMaker AI on AWS]
    Cloud --> Z[Azure Machine Learning]

Your own machine

For datasets that fit in memory, a laptop is the fastest feedback loop you’ll get. There is no session timeout, your files stay where you put them, and the environment is exactly what requirements.txt says. The example in this article runs in a few seconds on any recent laptop.

Hosted notebooks

Google Colab and Kaggle Notebooks give you a Jupyter-style notebook in the browser with common libraries preinstalled and free access to limited compute, including GPU time within usage limits. They are useful when your laptop is underpowered, when you want to share a runnable notebook, or when the dataset is already on Kaggle.

The trade-offs: sessions time out and the machine is wiped, so files you don’t save to Drive or download disappear; preinstalled library versions change without notice; and free GPU access is not guaranteed. Pin versions at the top of the notebook with pip install if results must be repeatable, and don’t upload data you aren’t allowed to share with a third party.

Cloud ML platforms

When a project involves a team, data already stored in a cloud account, scheduled retraining or deployment behind an API, the cloud platforms take over the infrastructure work. Each provider has one main service:

PlatformNotebook optionsWhere it fits
Vertex AI (Google Cloud)Colab Enterprise, or Vertex AI Workbench instancesData in BigQuery or Cloud Storage; managed training, pipelines and endpoints
Amazon SageMaker AI (AWS)SageMaker Studio, or notebooks in SageMaker Unified StudioData in S3 or Redshift; managed training jobs, model registry and endpoints
Azure Machine Learning (Microsoft)Notebooks on compute instances in Azure Machine Learning studioData in Azure storage; jobs, pipelines, registry and managed endpoints

A note on names, since older tutorials use different ones. AWS renamed the original Amazon SageMaker to Amazon SageMaker AI in December 2024; “Amazon SageMaker” now refers to the wider data and AI product that includes SageMaker Unified Studio. Google’s older AI Platform became Vertex AI, and Google Cloud now offers two notebook products under it: Colab Enterprise, which provisions the runtime for you, and Vertex AI Workbench, which gives you more control over the underlying virtual machine.

All three bill for compute while it runs, including idle notebook instances. Set up a budget alert before you start, and stop instances when you finish. Check each provider’s pricing page rather than relying on figures in a tutorial. The same scikit-learn code runs unchanged on all of them, which is one more reason to keep the core logic in plain scripts.

You have a 20 MB CSV and want to compare three scikit-learn models. What is the most sensible place to start?

  • Your laptop, in a virtual environment
  • A GPU instance on a cloud ML platform
  • A managed training pipeline with a model registry

Correct! Small tabular data and classical models run in seconds locally; cloud platforms earn their cost with larger data, teams or deployment.

A worked example: predicting diabetes progression

The example uses the diabetes dataset that ships with scikit-learn: 442 patients, ten baseline measurements (age, sex, body mass index, average blood pressure and six blood serum values), and a target that measures disease progression one year later. The target ranges from 25 to 346 with a mean of about 152. The features come already centred and scaled, so you can skip preprocessing here and focus on the workflow.

Older tutorials, including the original version of this article, use the Boston housing dataset through load_boston. That function was deprecated in scikit-learn 1.0 and removed in 1.2 over ethical problems with one of the dataset’s columns, so that code now fails with an ImportError. Use the diabetes dataset, or fetch_california_housing if you want a house price problem.

Load the data and hold out a test set

from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split

X, y = load_diabetes(return_X_y=True, as_frame=True)
print(X.shape)            # (442, 10)
print(y.describe())

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)

as_frame=True returns a pandas DataFrame with named columns instead of a bare array, which makes inspection easier. random_state=42 fixes the shuffle, so the split is the same every run. Change it and your numbers will move a little; that movement is a useful reminder of how noisy a single split is on small data.

From this point on, treat X_test and y_test as locked. You’ll use them once, at the end.

Compare models against a baseline with cross-validation

A model score means nothing on its own. A baseline that always predicts the training mean tells you what “no skill” looks like, and any real model has to beat it clearly.

To compare candidates without touching the test set, use five-fold cross-validation on the training data: scikit-learn splits the training set into five parts, trains on four and scores on the fifth, five times over.

from sklearn.dummy import DummyRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score

candidates = {
    "baseline (mean)": DummyRegressor(strategy="mean"),
    "linear regression": LinearRegression(),
    "random forest": RandomForestRegressor(n_estimators=300, random_state=42),
}

for name, model in candidates.items():
    scores = cross_val_score(
        model, X_train, y_train, cv=5, scoring="neg_mean_absolute_error"
    )
    print(f"{name:18} CV MAE {-scores.mean():5.1f} (+/- {scores.std():.1f})")

Output with scikit-learn 1.9:

baseline (mean)    CV MAE  66.8 (+/- 7.3)
linear regression  CV MAE  45.5 (+/- 3.1)
random forest      CV MAE  47.9 (+/- 4.1)

Mean absolute error (MAE) is in the same units as the target: the linear model is off by about 45 progression points on average, against about 67 for guessing the mean. scikit-learn reports it negated because its scoring functions always treat higher as better.

The result is worth pausing on. The random forest, the more flexible model, does no better than plain linear regression here, and the gap is within the spread across folds. With 442 rows and ten mostly linear relationships there isn’t enough signal for the extra flexibility to pay off. When two models are this close, prefer the simpler one: it is faster, easier to explain and less likely to overfit. Linear Regression: Predicting Outcomes explains what the model is fitting and when to add regularization, and Random Forest: An Ensemble Learning Method covers the cases where the forest wins.

Evaluate once on the test set and save the model

import joblib
from sklearn.metrics import mean_absolute_error, r2_score

model = LinearRegression().fit(X_train, y_train)
pred = model.predict(X_test)
print(f"Test MAE: {mean_absolute_error(y_test, pred):.1f}")   # 42.8
print(f"Test R2:  {r2_score(y_test, pred):.2f}")               # 0.45

joblib.dump(model, "models/diabetes-linear.joblib")

The test MAE of 42.8 is in line with the cross-validated estimate, which is what you want: it suggests the model selection didn’t overfit the training data. An R-squared of 0.45 means the model explains a bit under half the variance in progression. That is a realistic result for this dataset, not a failure; ten baseline measurements simply don’t determine how a disease develops.

Report the test score once. If you go back, change something and test again, the test set has become part of model selection and its score is no longer an honest estimate. Get a fresh hold-out set or rely on cross-validation instead.

Load and use the saved model

import joblib
from sklearn.datasets import load_diabetes

model = joblib.load("models/diabetes-linear.joblib")
X, _ = load_diabetes(return_X_y=True, as_frame=True)
print(model.predict(X.head(3)).round(1))   # [210.7  69.4 184.1]

Two cautions from the scikit-learn model persistence guide. Load the model with the same scikit-learn version that saved it, which is another reason to keep requirements.txt in Git. And never load a joblib or pickle file from a source you don’t trust, because loading one can run arbitrary code. The guide describes safer formats such as skops and ONNX for models you share.

Why compare candidate models with cross-validation on the training set instead of on the test set?

  • Cross-validation always gives higher scores
  • The test set is too small to score a model
  • Choosing models by test score makes that score an optimistic estimate

Correct! Once the test set influences your choices it stops measuring performance on unseen data, so keep it for one final check.

Making it reproducible

The example already does most of what reproducibility needs. To summarise:

  • Pinned environment. requirements.txt from pip freeze, committed to Git.
  • Fixed randomness. random_state on the split and on any model that uses randomness, such as random forests.
  • Scripts over notebook state. train.py and final.py run from a clean start and produce the same numbers every time.
  • Raw data untouched. Keep original files read-only under data/raw/ and write cleaned versions elsewhere. For data too large for Git, record where it came from and a checksum, or use a tool built for data versioning.
  • A short results log. One line per experiment with the date, Git commit, model, settings and cross-validated score. A text file is enough to start.

When you need more, experiment tracking tools such as MLflow record parameters, metrics and model files automatically, and all three cloud platforms above have their own tracking and model registry features.

Where to go next

With the structure in place, the useful next steps are mostly about the data and the evaluation, not the tooling:

  • Try a harder dataset. fetch_california_housing has about 20,000 rows, where tree ensembles start to beat linear models.
  • Add preprocessing in a pipeline. Real data has missing values, categories and unscaled numbers. scikit-learn’s Pipeline and ColumnTransformer keep preprocessing inside cross-validation so it can’t leak information from the validation folds.
  • Look at the errors. Plot actual against predicted values and residuals against each feature. Patterns in the residuals point to missing features or relationships the model can’t represent.
  • Serve the model. Wrapping model.predict in a small FastAPI app and packaging it in a container is a short step; Introduction to Containers and Docker covers the packaging side.

For further reading, the official scikit-learn getting started guide, the toy datasets reference and the Python venv documentation cover the tools used here in more detail.

Key takeaways

  • A small ML project needs Python, a virtual environment, pandas, scikit-learn, a notebook for exploration and Git. Deep learning frameworks and GPUs can wait.
  • Start on your laptop. Move to hosted notebooks for more compute or easy sharing, and to Vertex AI, SageMaker AI or Azure Machine Learning when you need team workflows, cloud data access or deployment.
  • Always compare against a baseline. Here, guessing the mean gave an MAE of 66.8 and linear regression 45.5.
  • Choose models with cross-validation on training data, and use the test set once at the end.
  • A more complex model is not automatically better: on 442 rows the random forest didn’t beat linear regression.
  • Pin library versions, fix random seeds, keep the core logic in scripts, and only load saved models from sources you trust.
  • load_boston no longer exists in scikit-learn; tutorials that use it are out of date.

Part 8 of 9 · Introduction to Machine Learning and AI

  1. 01What is Machine Learning?
  2. 02The Evolution of Artificial Intelligence
  3. 03AI vs. Machine Learning vs. Deep Learning: Understanding the Differences
  4. 04Supervised vs. Unsupervised Learning: Applications of Machine Learning in Everyday Life
  5. 05History of AI: From Turing to Modern ML & Types of Machine Learning Algorithms
  6. 06AI is Transforming Industries: The Role of Data in Machine Learning
  7. 07Introduction to Model Training and Evaluation. Challenges in AI and Machine Learning
  8. 08Setting Up a Simple ML Project: Tools and Platforms
  9. 09Key Concepts and Terminologies in ML
Ready to check your understanding?Take the Artificial Unintelligence quiz
esc

Type to search all articles · ↑↓ to move · ↵ to open