Section 1 · Lesson 1

What machine learning is: features, labels and your first model

How supervised learning turns labeled examples into predictions, and the fit/predict pattern every scikit-learn model shares.

35 min 2 practice tasks Free preview
A Gentle Introduction to Machine Learning by StatQuest with Josh Starmer on YouTube

In traditional programming you write the rules. In machine learning you supply examples with the answers and an algorithm works out the rules for you.

A marketer deciding who to retarget might write a rule: “show ads to anyone who added something to their cart”. A model looks at thousands of past visitors and learns how cart adds, recency, visit counts and email sign-ups combine, including patterns no one thought to write down.

The vocabulary

Term Meaning In our data
Observation (row, example) One thing we make a prediction about One visitor
Features (X) The inputs that describe each row Sessions, cart adds, recency…
Label or target (y) What we want to predict converted (0 or 1)
Model The learned mapping from X to y A decision tree
Training (fitting) Learning the model’s parameters from labeled rows model.fit(X, y)
Prediction (inference) Applying the model to new rows model.predict(X_new)

Kinds of machine learning

  • Supervised learning: every training row has a known label. If the label is a number (tomorrow’s conversions, a customer’s spend) it’s regression. If it’s a category (will this visitor convert, yes or no?) it’s classification.
  • Unsupervised learning: no labels. You look for structure, like clustering customers into segments or flagging unusual traffic.

This course is about supervised learning, which covers most business prediction problems.

The data: audience.csv

The audience table holds 5,000 people who visited an advertiser’s site and were then shown ads for 14 days. About 15% converted. Each row has demographics (age, country, device), the acquisition source, 30 days of on-site behavior (sessions_30d, pages_viewed_30d, minutes_on_site_30d, cart_adds_30d), days_since_last_visit, past_purchases, email_subscriber (0/1), ad frequency (ad_impressions_7d) and the label converted.

The scikit-learn pattern

Every scikit-learn model follows the same three steps:

from sklearn.tree import DecisionTreeClassifier

model = DecisionTreeClassifier(max_depth=3, random_state=42)  # 1. choose and configure
model.fit(X, y)                                               # 2. learn from labeled rows
model.predict(X_new)                                          # 3. predict labels (0/1)
model.predict_proba(X_new)                                    #    or class probabilities

X is two-dimensional (a DataFrame, one column per feature) and y is one-dimensional. Settings you choose up front, like max_depth, are hyperparameters. random_state fixes any randomness so you get the same model every run. Once you know this pattern, swapping in a different algorithm is a one-line change.

A first look at a decision tree

A decision tree asks a series of yes/no questions such as “is cart_adds_30d above 0?” and then “was the last visit within 3 days?”. Each final box (a leaf) stores the share of training visitors in it who converted. That share is what predict_proba returns, and predict turns it into 0 or 1 at 50%. max_depth=3 allows at most three questions in a row.

What to keep out of X

  • The label, or anything computed from it. An order_value column would give the answer away. This is called target leakage: the model looks brilliant in testing and fails in production.
  • Information you won’t have at prediction time. If you score visitors before showing ads, you can’t use what happened after.
  • Identifiers. user_id is just a counter. A model can memorize it but can’t learn from it.

Accuracy on the rows a model was trained on tells you very little. The next lesson fixes that with a proper train/test split.

Practice

Write your answer, press Run to see results and Check answer to grade it. Shortcuts: Ctrl/⌘ + Enter run, Shift + Enter check.

1

Build X and y

Load audience.csv: 5,000 people who visited an advertiser's site and were then shown ads for 14 days. converted is 1 if they bought during those 14 days.

  • features: a list of these 8 behavior columns: sessions_30d, pages_viewed_30d,

minutes_on_site_30d, cart_adds_30d, days_since_last_visit, past_purchases, email_subscriber, ad_impressions_7d

  • X: a DataFrame with just those columns
  • y: the converted column
  • n_rows, n_features: the number of rows and columns in X
  • positive_rate: the share of visitors who converted, rounded to 4 decimals
Need a hint?
  1. Select several columns with a list: audience[features].
  2. X.shape is a (rows, columns) tuple, and the mean of a 0/1 column is the share of 1s.
Python 3
import pandas as pd

audience = pd.read_csv("audience.csv")
print(audience.head())

features = []
X = None
y = None
n_rows = None
n_features = None
positive_rate = None
Files in the working directory
audience.csv (5,000 rows)
user_id, age, country, device, source, sessions_30d, pages_viewed_30d, minutes_on_site_30d, cart_adds_30d, days_since_last_visit, past_purchases, email_subscriber, ad_impressions_7d, converted
daily_stats.csv (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
campaigns.csv (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
2

Fit and predict with a decision tree

Fit a DecisionTreeClassifier(max_depth=3, random_state=42) on X and y.

  • model: the fitted tree
  • train_accuracy: the share of rows where model.predict(X) equals y, rounded to 4 decimals
  • new_proba: the predicted probability that the visitor in new_visitor converts (the

second column of model.predict_proba(new_visitor)), rounded to 4 decimals

The next lesson shows why accuracy measured on the rows the model learned from is too optimistic.

Need a hint?
  1. model.fit(X, y) learns from the data; afterwards model.predict(X) returns a 0/1 prediction per row.
  2. predict_proba returns one row per visitor and one column per class (0, then 1), so [0, 1] is the first row's probability of converting.
Python 3
import pandas as pd
from sklearn.tree import DecisionTreeClassifier

audience = pd.read_csv("audience.csv")
features = ["sessions_30d", "pages_viewed_30d", "minutes_on_site_30d", "cart_adds_30d",
            "days_since_last_visit", "past_purchases", "email_subscriber", "ad_impressions_7d"]
X = audience[features]
y = audience["converted"]

# A visitor the model has never seen
new_visitor = pd.DataFrame([{
    "sessions_30d": 12, "pages_viewed_30d": 70, "minutes_on_site_30d": 85.0,
    "cart_adds_30d": 2, "days_since_last_visit": 1, "past_purchases": 1,
    "email_subscriber": 1, "ad_impressions_7d": 4,
}])

model = DecisionTreeClassifier(max_depth=3, random_state=42)
# TODO: fit the model, then predict

train_accuracy = None
new_proba = None
print(train_accuracy, new_proba)
Files in the working directory
audience.csv (5,000 rows)
user_id, age, country, device, source, sessions_30d, pages_viewed_30d, minutes_on_site_30d, cart_adds_30d, days_since_last_visit, past_purchases, email_subscriber, ad_impressions_7d, converted
daily_stats.csv (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
campaigns.csv (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status