Step 1: Open Google Colab
Google Colab is a free notebook that runs in your browser: you type Python into boxes called cells, run them, and see the result right underneath. Google runs the computer for you, and pandas and scikit-learn, the two libraries this guide uses, are already installed.
- Go to colab.research.google.com and sign in with a Google account.
- Choose New notebook. You get an empty code cell.
- Name the notebook at the top, for example “First model.” It’s saved in your Google Drive.
Step 2: Run your first cell
Paste this into the cell and press Shift+Enter (or the play button on its left). The first run takes a few seconds while Colab starts a computer for you.
CodeYour first cell
# pip install pandas scikit-learn
import sys
import pandas as pd
import sklearn
print("Python", sys.version.split()[0])
print("pandas", pd.__version__, "and scikit-learn", sklearn.__version__, "are ready")
print(2 + 2)You should see the versions and a 4. Every cell remembers what earlier cells did, so run them in order, top to bottom. If something looks odd, Runtime → Restart and run all starts again from a clean slate.
Step 3: Get some data
A model learns from examples where you already know the answer; that’s supervised learning. Here each example is one visit to an online shop: how many pages the visitor viewed, how long they stayed, whether they’d been before, whether they came from an ad, how many items were in their cart, their device, and the answer: did they buy?
This cell makes 5,000 realistic visits so you can follow along. To use your own data instead, click the folder icon on the left in Colab, drag your CSV file in, and read it with pd.read_csv in the next step.
CodeMake a sample visits.csv
import numpy as np
import pandas as pd
rng = np.random.default_rng(42)
n = 5_000
visits = pd.DataFrame({
"pages_viewed": rng.poisson(5, n) + 1,
"minutes_on_site": rng.gamma(2, 3, n).round(1),
"returning_visitor": rng.random(n) < 0.35,
"came_from_ad": rng.random(n) < 0.25,
"items_in_cart": rng.poisson(0.8, n),
"device": rng.choice(["phone", "computer", "tablet"], n, p=[0.6, 0.32, 0.08]),
})
# How likely each visit is to end in a purchase (hidden from the model, which has to learn it).
score = (-5.5 + 0.25 * visits.pages_viewed + 0.1 * visits.minutes_on_site + 1.2 * visits.returning_visitor
+ 1.6 * visits.items_in_cart - 0.6 * visits.came_from_ad + 0.5 * (visits.device == "computer"))
visits["bought"] = rng.random(n) < 1 / (1 + np.exp(-score))
visits.to_csv("visits.csv", index=False)
print(f"{n:,} visits saved to visits.csv")Step 4: Look before you model
Always look at the data first. Check that the numbers make sense, and how common each answer is.
CodeLook at the data
visits = pd.read_csv("visits.csv")
print(visits.head())
print(visits.describe().round(1))
print(visits.bought.value_counts(normalize=True).round(3))About 1 visit in 4 ends in a purchase. Remember that number: it decides what “good” means in Step 6.
Step 5: Keep some visits back for testing
A model can memorize the examples it learns from, so you can only judge it on examples it has never seen. Set a quarter of the visits aside as a test set, and don’t touch it until the end. The model gets X, the inputs, and learns to predict y, the answer. Text columns like the device become yes/no columns, because models only read numbers.
CodeInputs, answer, and a test set
from sklearn.model_selection import train_test_split
X = pd.get_dummies(visits.drop(columns="bought"), columns=["device"])
y = visits.bought
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, stratify=y, random_state=0)
print(len(X_train), "visits to learn from,", len(X_test), "to test on")stratify=y keeps the share of purchases the same in both parts, so the test isn’t accidentally easier or harder.
Step 6: Know what “good” means
Before training anything, see what a model that always answers “no purchase” scores. That’s your baseline: anything you build has to beat it.
CodeA baseline that always says no
from sklearn.dummy import DummyClassifier
from sklearn.metrics import accuracy_score
baseline = DummyClassifier(strategy="most_frequent").fit(X_train, y_train)
print("Always 'no' is right", f"{accuracy_score(y_test, baseline.predict(X_test)):.0%}", "of the time")It’s right about 3 times in 4 without learning anything, because most visits don’t end in a purchase. This is why Accuracy alone can fool you when one answer is much more common than the other, which is called class imbalance.
Step 7: Train your first model
A decision tree learns a short list of yes/no questions, like “more than one item in the cart?”, and is easy to read. Limit it to 3 levels of questions, train it with fit, and check it on the test set.
CodeYour first model: a small decision tree
from sklearn.metrics import classification_report
from sklearn.tree import DecisionTreeClassifier, export_text
tree = DecisionTreeClassifier(max_depth=3, random_state=0).fit(X_train, y_train)
print(classification_report(y_test, tree.predict(X_test), digits=2))
print(export_text(tree, feature_names=list(X.columns)))Read the two lines for True. Precision says how often it’s right when it predicts a purchase, and recall says how many of the real purchases it finds. Here it’s usually right when it says “purchase,” but it finds only about a third of them. The printed rules show what it learned: items in the cart matter most, then time on the site.
Step 8: Find the right amount of complexity
Give the tree more levels and it fits the training visits better and better. But past a point it starts memorizing them, and gets worse on new visits. That’s overfitting, and it’s the most common mistake in machine learning.
CodeToo simple, too complex, about right
for depth in [1, 3, 6, None]:
m = DecisionTreeClassifier(max_depth=depth, random_state=0).fit(X_train, y_train)
print(f"depth {str(depth):>4}: training {m.score(X_train, y_train):.0%}, test {m.score(X_test, y_test):.0%}")With no limit, the tree is right about almost every training visit and noticeably worse on the test set. That gap is the warning sign. Try the overfitting example to see the same thing on a curve.
Step 9: Try a stronger model
A random forest trains hundreds of trees on different samples of the data and lets them vote. It usually beats a single tree with almost no tuning. Compare the two with ROC-AUC: how well each one ranks buyers above non-buyers, from 0.5 (guessing) to 1 (perfect).
CodeA stronger model: a random forest
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import roc_auc_score
forest = RandomForestClassifier(n_estimators=300, min_samples_leaf=5, random_state=0).fit(X_train, y_train)
for name, m in [("Decision tree", tree), ("Random forest", forest)]:
print(f"{name:<14} ROC-AUC {roc_auc_score(y_test, m.predict_proba(X_test)[:, 1]):.3f}")The forest is a little better here. On real data the gap is often bigger, and it’s worth checking every time.
Step 10: Use the model, and keep it
Ask the model about a visit it has never seen. predict_proba gives a chance between 0% and 100%, which is often more useful than a plain yes or no: you might show a discount only to visitors below 30%.
CodeAsk the model about a new visit
new_visit = pd.DataFrame([{"pages_viewed": 9, "minutes_on_site": 14.0, "returning_visitor": True, "came_from_ad": False,
"items_in_cart": 2, "device": "computer"}])
new_visit = pd.get_dummies(new_visit, columns=["device"]).reindex(columns=X.columns, fill_value=False)
print(f"Chance this visit ends in a purchase: {forest.predict_proba(new_visit)[0, 1]:.0%}")Save the trained model to a file so you can use it later without training again. In Colab, files disappear when the session ends, so download it from the folder panel, or save it to Google Drive.
CodeSave the model
import joblib
joblib.dump(forest, "purchase_model.joblib")
print("Saved purchase_model.joblib")That’s the whole loop every project follows: get data, set a test set aside, beat a baseline, train, check for overfitting, use the model. Next, describe your own idea for a plan built around your data, or follow the learning path.
Common pitfalls
- Running cells out of order, so a later cell uses something an earlier one changed. Use Restart and run all when in doubt.
- Judging the model on the data it learned from. Only the test set tells you how it does on new examples.
- Celebrating a high accuracy without checking what “always no” would score.
- Making the model more complex until the training score is perfect, which is usually overfitting.
- Forgetting that Colab deletes your files when the session ends. Download the model or save it to Drive.