Python for AI Engineers · Part C · Lesson 20 of 26

scikit-learn tutorial: regression, trees, k-NN and a text classifier

scikit-learn for Java and JavaScript developers: the fit/predict API, linear and logistic regression, decision trees, random forests, k-NN, StandardScaler, Pipeline, train_test_split, a TF-IDF ticket router, and when a classic model beats an LLM on cost, speed and data.

⏱ 45 min3 exercises that check your codeRuns in your browser

By the end you can

  • Use the scikit-learn pattern every model shares: create, fit(X, y), predict(X), and read what it learned
  • Train and compare linear and logistic regression, decision trees, random forests and k-NN on a fair train_test_split with a fixed random_state
  • Scale features with StandardScaler and chain steps into one Pipeline you can save and load
  • Build a support ticket router with TfidfVectorizer + LogisticRegression that hands unsure tickets to an LLM
  • Explain when a classic model beats an LLM: cost, latency, labelled data and control
1 / 7

1The scikit-learn pattern: create, fit, predict

scikit-learn is the standard Python library for classic machine learning: models that learn from a table of numbers, train in milliseconds on a laptop and need no GPU. You install it with uv add scikit-learn and import it as sklearn. The boxes on this page run it inside your browser; the first Run takes a few seconds while scikit-learn loads.

Every model, which scikit-learn calls an estimator, works the same way. You create it with its settings, fit it on examples, then predict on new rows. The examples come in two parts. X is the input table: one row per example, one column per feature (a number that describes the example). The capital letter is a convention for "a 2D table". y holds the right answer for each row, called the label or target.

Here we predict how long an LLM request takes from its input and output token counts, with linear regression: it finds the weights w1, w2 and the offset b that make b + w1 * input + w2 * output as close as possible to the real times. We made the six timings from the rule 200 ms + 0.05 ms per input token + 20 ms per output token, so you can check that the model finds it.

Try it: edit and run
from sklearn.linear_model import LinearRegression

# each row is one past request: [input tokens, output tokens]
X = [[500, 50], [1000, 100], [2000, 80], [800, 200], [1500, 150], [300, 30]]
# what we want to predict: how long each request took, in milliseconds
y = [1225, 2250, 1900, 4240, 3275, 815]

model = LinearRegression()     # 1. create: choose the algorithm and its settings
model.fit(X, y)                # 2. fit: learn from examples (X) and answers (y)

print("ms per input token: ", round(model.coef_[0], 3))
print("ms per output token:", round(model.coef_[1], 3))
print("fixed overhead ms:  ", round(model.intercept_, 1))

new = [[1200, 60], [400, 300]]
print("predicted ms:", model.predict(new).round(0).tolist())   # 3. predict new rows
Expected output
ms per input token:  0.05
ms per output token: 20.0
fixed overhead ms:   200.0
predicted ms: [1460.0, 6220.0]
The same contract as a Java interface (an illustration, not a real library)
interface Regressor {
    Regressor fit(double[][] X, double[] y); // learn, return this
    double[] predict(double[][] X);          // one answer per row
}

// every scikit-learn model has these same methods, so swapping
// LinearRegression for a random forest is a one-line change

Things to notice. What a model learned lives in attributes whose names end with an underscore, like coef_ (one weight per column of X) and intercept_ (the offset b); they only exist after fit. predict takes a 2D table even for one row, and returns a NumPy array (lesson 15); .round(0) rounds every value and .tolist() turns it into a plain Python list for printing. Plain lists of lists work as X, and so do NumPy arrays and pandas DataFrames.

Tip Learn the pattern, not each model. Once you know fit, predict and score, every other estimator in scikit-learn works the same way, and only the settings you pass when you create it change.

2Classification with logistic regression, and a fair test

Classification means predicting a category instead of a number: spam or not, which team gets a ticket, will this ticket be escalated (passed up to a manager). Despite its name, logistic regression is a classifier. It computes a weighted sum like linear regression, then squashes it into a probability between 0 and 1.

To know whether a model works, you test it on rows it did not see while training. train_test_split shuffles the rows and cuts them in two. test_size=0.25 keeps 25% for the test. random_state=42 fixes the shuffle, so you get the same split on every run, like new Random(42) in Java. stratify=y keeps the same share of each class in both parts. It returns four values, which we unpack into four variables in one line.

Try it: edit and run
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split

# [hours open, messages from the customer] for 24 past support tickets
X = [[1, 1], [2, 1], [3, 2], [1, 3], [4, 1], [5, 2], [2, 2], [6, 1], [3, 1], [8, 2], [14, 1], [18, 2],
     [20, 4], [30, 6], [12, 5], [26, 3], [15, 7], [40, 5], [10, 6], [36, 8], [3, 6], [2, 7], [22, 5], [5, 8]]
y = [0] * 12 + [1] * 12            # first 12 were not escalated (0), last 12 were (1)

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, random_state=42, stratify=y)
print("train rows:", len(X_train), "| test rows:", len(X_test))
print("test answers:", y_test)

clf = LogisticRegression()
clf.fit(X_train, y_train)          # learn only from the training rows
print("predicted:   ", clf.predict(X_test).tolist())
print("accuracy:", clf.score(X_test, y_test))

ticket = [[7, 4]]                          # open 7 hours, 4 customer messages
p_no, p_yes = clf.predict_proba(ticket)[0]
print(f"P(escalate) = {p_yes:.2f}")
Expected output
train rows: 18 | test rows: 6
test answers: [0, 1, 1, 1, 0, 0]
predicted:    [0, 1, 1, 1, 0, 0]
accuracy: 1.0
P(escalate) = 0.46

[0] * 12 + [1] * 12 builds a list of twelve 0s followed by twelve 1s. score on a classifier is accuracy: the share of test rows it got right (on a regressor, score returns a different number, R²). predict answers 0 or 1 by cutting the probability at 0.5. predict_proba gives the probabilities themselves: one row per ticket, one column per class in the order of clf.classes_ (here [0, 1]). [0] takes the first (only) row, and p_no, p_yes = ... unpacks its two numbers.

A perfect score on 6 test tickets proves very little; the metrics lesson shows better numbers than accuracy. And with random_state left out, you get a different split, and maybe a different score, every time you run the program.

Watch out Never measure a model on the rows it was trained on. It has seen the answers, so the score looks great and tells you nothing about new data. Split first, fit on the training part only, score on the test part.

3Decision trees: if/else rules learned from data

A decision tree learns a set of nested yes/no questions about the features, the kind of if / else you would write by hand. To pick each question, it tries every feature and threshold and keeps the one that best separates the classes. export_text prints the rules it learned, so you can read the model like code.

max_depth=2 allows at most two questions on any path. Without a limit, a tree keeps adding questions until every training row is classified correctly, which usually means it memorises noise.

Try it: edit and run
from sklearn.tree import DecisionTreeClassifier, export_text

# [hours open, messages from the customer] for 24 past support tickets
X = [[1, 1], [2, 1], [3, 2], [1, 3], [4, 1], [5, 2], [2, 2], [6, 1], [3, 1], [8, 2], [14, 1], [18, 2],
     [20, 4], [30, 6], [12, 5], [26, 3], [15, 7], [40, 5], [10, 6], [36, 8], [3, 6], [2, 7], [22, 5], [5, 8]]
y = [0] * 12 + [1] * 12            # first 12 were not escalated (0), last 12 were (1)

tree = DecisionTreeClassifier(max_depth=2, random_state=0)
tree.fit(X, y)
print(export_text(tree, feature_names=["hours_open", "messages"]))
print("prediction for [7, 4]:", tree.predict([[7, 4]])[0])
print("importance:", tree.feature_importances_.round(2).tolist())
Expected output
|--- messages <= 2.50
|   |--- class: 0
|--- messages >  2.50
|   |--- hours_open <= 1.50
|   |   |--- class: 0
|   |--- hours_open >  1.50
|   |   |--- class: 1

prediction for [7, 4]: 1
importance: [0.15, 0.85]

Read it as code: if messages <= 2.5: not escalated, elif hours_open <= 1.5: not escalated, else: escalated. Thresholds fall halfway between values seen in the data (2 and 3 messages give 2.5). The second rule exists for one ticket, [1, 3]. That is how trees overfit: they happily build a rule around a single odd example.

feature_importances_ says how much each column helped (they add up to 1): here the number of messages did most of the work. random_state matters even for one tree, because when two splits are equally good the tree picks one at random. The logistic regression above gave the ticket [7, 4] a 0.46 chance; this tree says "escalate". Different models, different answers: that is why you compare them on a test set.

Tip Trees do not care about the scale of a feature (hours, dollars, millions of tokens), and their rules are easy to explain to a product manager. That makes a small tree a good first model whenever someone asks "why did it decide that?".

4Random forests: many trees vote

A random forest trains many trees, each on a random sample of the training rows (drawn with replacement) and with a random subset of the features to choose from at each question. Every tree overfits in its own way, so when they all vote (scikit-learn averages their predicted probabilities), the mistakes mostly cancel out. n_estimators is the number of trees; random_state fixes all that randomness.

The test below uses make_moons, a scikit-learn helper that generates two curved, overlapping groups of 2D points, a classic shape a straight line cannot separate. The same fit and score calls work for all three models, so a dict of models and one loop is all it takes to compare them.

Try it: edit and run
from sklearn.datasets import make_moons
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier

X, y = make_moons(n_samples=300, noise=0.3, random_state=0)   # 300 points, 2 features, 2 classes
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0)

models = {
    "logistic regression": LogisticRegression(),
    "one deep tree": DecisionTreeClassifier(random_state=0),
    "random forest": RandomForestClassifier(n_estimators=200, random_state=0),
}
for name, model in models.items():
    model.fit(X_train, y_train)
    train_acc = model.score(X_train, y_train)
    test_acc = model.score(X_test, y_test)
    print(f"{name:20} train {train_acc:.2f}  test {test_acc:.2f}")
Expected output
logistic regression  train 0.84  test 0.81
one deep tree        train 1.00  test 0.83
random forest        train 1.00  test 0.93

{name:20} pads the name to 20 characters so the columns line up, and {train_acc:.2f} prints two decimals. Read the table row by row. Logistic regression draws one straight line, so it is wrong on the curves even on its own training data (0.84). The single tree with no depth limit memorised the training set (1.00) but does much worse on new points (0.83). The forest also scores 1.00 on training data, yet 0.93 on the test: averaging many trees generalises far better than one.

Tip For a table of numbers (users, orders, logs), a random forest with default settings is a strong first baseline: hard to get badly wrong, no scaling needed. Gradient-boosted trees (HistGradientBoostingClassifier, or the XGBoost and LightGBM libraries) are often a little better still.

5k-NN, and why you scale features

k-nearest neighbours (k-NN) is the simplest model of all. fit just stores the training rows. To predict, it finds the k training rows closest to the new one (straight-line distance) and lets them vote. It is also the idea behind vector search in RAG: find the stored embeddings nearest to the question.

Distance has a catch. Below, each user has a satisfaction rating from 1 to 5 (which predicts whether they cancel) and the number of tokens they used (millions, no signal at all). In raw numbers a difference of 3 rating points is nothing next to a difference of 500,000 tokens, so the neighbours are chosen almost only by tokens.

StandardScaler fixes that. It is a transformer: fit learns each column's mean and standard deviation (stored as mean_ and scale_), and transform rewrites each value as "how many standard deviations from the mean", so every column ends up with mean 0 and standard deviation 1. fit_transform does both in one call.

Try it: edit and run
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import StandardScaler

rng = np.random.RandomState(0)           # a seeded random generator: same numbers every run
n = 300
rating = rng.uniform(1, 5, n)            # the user's last satisfaction rating, 1 to 5
tokens = rng.uniform(0, 2_000_000, n)    # tokens used last month: big numbers, no real signal
X = np.column_stack([rating, tokens])    # 300 rows, 2 columns
y = (rating < 2.5).astype(int)           # 1 = the user cancelled
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0)

knn = KNeighborsClassifier(n_neighbors=5)
knn.fit(X_train, y_train)
print(f"k-NN, raw features:    {knn.score(X_test, y_test):.2f}")

scaler = StandardScaler()
X_train_s = scaler.fit_transform(X_train)    # learn mean and std from TRAINING rows only
X_test_s = scaler.transform(X_test)          # reuse those numbers on the test rows
knn.fit(X_train_s, y_train)
print(f"k-NN, scaled features: {knn.score(X_test_s, y_test):.2f}")

print("learned means:", scaler.mean_.round(1).tolist())
print("first row raw:   ", X_train[0].round(1).tolist())
print("first row scaled:", X_train_s[0].round(2).tolist())
Expected output
k-NN, raw features:    0.64
k-NN, scaled features: 0.99
learned means: [2.9, 1001185.6]
first row raw:    [2.2, 1773921.6]
first row scaled: [-0.68, 1.29]

rng.uniform(1, 5, n) draws n random decimals between 1 and 5 from a generator seeded with 0, so the data is the same on every run and every machine. np.column_stack glues the two arrays into a 300 x 2 table. rating < 2.5 gives an array of True/False, and .astype(int) turns it into 1/0. Calling fit again on the same knn object throws away what it learned before. Scaling took k-NN from 0.64, barely better than guessing, to 0.99. In the last line, the first user's rating is 0.68 standard deviations below average and their token count 1.29 above.

Watch out Fit the scaler on the training rows only, then transform the test rows with those same numbers. Fitting it on all the data first lets facts about the test rows leak into training, so your score looks better than it will be in production (the data leakage lesson goes deeper).

6Pipeline: preprocessing and model as one object

Scaling by hand means remembering to call transform with the same scaler everywhere you predict: in the test, in the API, in the batch job. Forget it once and the model silently gets raw numbers. A Pipeline chains the steps into one estimator. fit runs fit_transform on each step in order and fit on the last one; predict runs transform on each step and predict on the last.

make_pipeline names each step after its class in lowercase. To choose the names yourself, write Pipeline([("scale", StandardScaler()), ("knn", KNeighborsClassifier())]). If you know Java, it is like a chain of filters in front of a handler; in JavaScript, like composing functions.

Try it: edit and run
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

rng = np.random.RandomState(0)
rating = rng.uniform(1, 5, 300)
tokens = rng.uniform(0, 2_000_000, 300)
X = np.column_stack([rating, tokens])
y = (rating < 2.5).astype(int)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0)

model = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=5))
model.fit(X_train, y_train)            # scaler.fit_transform, then knn.fit, in one call
print("steps:", list(model.named_steps))
print(f"accuracy: {model.score(X_test, y_test):.2f}")

new_users = [[1.5, 900_000], [4.5, 50_000]]   # raw numbers, straight from the database
print("will cancel:", model.predict(new_users).tolist())
print("scaler mean:", model.named_steps["standardscaler"].mean_.round(1).tolist())
Expected output
steps: ['standardscaler', 'kneighborsclassifier']
accuracy: 0.99
will cancel: [1, 0]
scaler mean: [2.9, 1001185.6]

Same data and same score as the hand-scaled version, with less code and no way to forget a step. You pass raw numbers to predict and the pipeline scales them with the means it learned during fit. named_steps is a dict-like object from step name to step, so you can still look inside. Because the whole pipeline is one object, you save and load it as one file (section 9), and the cross-validation tools in later lessons re-fit the scaler correctly on every split.

Tip Make "everything is a Pipeline" a habit, even with one preprocessing step. It is the single best defence against the "worked in the notebook, wrong in production" bug.

7A text classifier: routing support tickets

Models need numbers, so text must become a vector first. TfidfVectorizer is a transformer that does that without any neural network. fit builds a vocabulary of every word in the training texts. transform turns each text into a row with one column per vocabulary word. The value is TF-IDF: how often the word appears in this text (term frequency), scaled down for words that appear in many texts (inverse document frequency), so "the" counts little and "refund" counts a lot. By default it lowercases, keeps words of two or more letters or digits (so "I" is dropped), and scales each row to length 1.

Put it in front of a LogisticRegression and you have a real ticket router: 18 labelled tickets, three teams, trained in milliseconds. Logistic regression handles more than two classes out of the box. C=10 loosens its built-in regularisation (a penalty on large weights, C=1.0 by default): with this little data the default gives every class roughly the same probability, and every ticket below would go to the LLM.

The route function adds the part that matters in production: if the model is not confident enough, it says so, and the ticket goes to an LLM (or a person) instead.

Try it: edit and run
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline

TICKETS = [
    ("I was charged twice for my subscription this month", "billing"),
    ("Please refund the last payment, I cancelled already", "billing"),
    ("My invoice shows the wrong amount", "billing"),
    ("How do I update the credit card on my account", "billing"),
    ("Why did my plan price go up", "billing"),
    ("I need a receipt for the payment for my company", "billing"),
    ("The app crashes when I upload a PDF", "bug"),
    ("Export button does nothing, nothing downloads", "bug"),
    ("Error 500 when I open the dashboard", "bug"),
    ("The page is blank after the latest update", "bug"),
    ("Search returns an error for long queries", "bug"),
    ("The chat widget freezes and crashes on mobile", "bug"),
    ("I forgot my password and the reset email never arrives", "account"),
    ("How do I change the email on my account", "account"),
    ("Please delete my account and my data", "account"),
    ("I cannot log in, it says my account is locked", "account"),
    ("Add a teammate to my workspace", "account"),
    ("Turn on two factor login for my account", "account"),
]
texts = [text for text, _ in TICKETS]
labels = [label for _, label in TICKETS]

router = make_pipeline(TfidfVectorizer(), LogisticRegression(C=10))
router.fit(texts, labels)

vec = router.named_steps["tfidfvectorizer"]
print("matrix:", vec.transform(texts).shape, "| classes:", router.classes_.tolist())


def route(text, threshold=0.6):
    probs = router.predict_proba([text])[0]   # one probability per class, in classes_ order
    best = probs.argmax()                     # index of the most likely class
    label = str(router.classes_[best]) if probs[best] >= threshold else "ask the LLM"
    return label, float(probs[best])


for text in [
    "I was charged twice, please refund me",
    "the app crashes every time I click export",
    "I can't log in to my account",
    "do you have an office in Berlin",
]:
    label, confidence = route(text)
    print(f"{label:12} {confidence:.2f}  {text}")
Expected output
matrix: (18, 87) | classes: ['account', 'billing', 'bug']
billing      0.75  I was charged twice, please refund me
bug          0.81  the app crashes every time I click export
account      0.83  I can't log in to my account
ask the LLM  0.36  do you have an office in Berlin

The key lines. [text for text, _ in TICKETS] is a list comprehension that unpacks each (text, label) pair and keeps the text; _ is the usual name for a value you ignore. The 18 tickets became an 18 x 87 matrix: 87 different words. It is stored sparse (only the non-zero values), because each row uses only a handful of those words. classes_ is sorted alphabetically, and predict_proba returns its columns in that order.

In route, the pipeline expects a list of texts, so we pass [text] and take row [0]. probs.argmax() is the position of the largest probability. str(...) and float(...) turn NumPy values into plain Python ones, which is what JSON and your API code expect. The Berlin question uses none of the words the model knows well, so its best guess is only 0.36 and the router hands it on instead of guessing.

Tip Pick the threshold from data, not by feel: on a labelled test set, check how accurate the model is above each threshold and what share of tickets it keeps. "Handles 85% of tickets at 97% accuracy, sends 15% to the LLM" is a number your team can decide on.

8When a classic model beats an LLM

You could send every ticket to an LLM with a prompt like "Classify this ticket as billing, bug or account". It works on day one with no training data, which is a real advantage. But compare the two once the volume grows:

Classic model (TF-IDF + logistic regression) LLM
Data you need a few hundred labelled examples or more none, or a few examples in the prompt
Cost per prediction close to zero on a CPU you already run you pay for every input and output token
Latency under a millisecond per ticket hundreds of milliseconds to seconds
Output always one of your labels, with a probability free text you must parse and validate
New category relabel and retrain edit the prompt
Unusual or vague input weak, but it tells you (low confidence) strong
Data privacy stays on your servers sent to the provider, unless the model runs locally

The rule of thumb: a fixed set of labels, high volume and labelled history (support routing, spam, intent detection, fraud flags) favour a classic model. Few or no labels, categories that change every week, or a task that needs reading comprehension or writing favour an LLM. The best systems often use both, like the router above. The box below does the cost arithmetic with example prices.

Try it: edit and run
# Example prices for a small hosted model, in dollars per million tokens. Check your provider's real prices.
PRICE_IN = 0.40
PRICE_OUT = 1.60


def llm_cost_per_month(tickets_per_day, tokens_in=600, tokens_out=5, share=1.0):
    """Dollars per month if `share` of the tickets go to the LLM (1.0 = all of them)."""
    tickets = tickets_per_day * 30 * share
    return tickets * (tokens_in * PRICE_IN + tokens_out * PRICE_OUT) / 1_000_000


print("dollars per month")
print("tickets/day   LLM for all   LLM for the unsure 15%")
for per_day in [1_000, 30_000, 300_000]:
    everything = llm_cost_per_month(per_day)
    hybrid = llm_cost_per_month(per_day, share=0.15)
    print(f"{per_day:>11,}   {everything:>10,.2f}   {hybrid:>10,.2f}")
Expected output
dollars per month
tickets/day   LLM for all   LLM for the unsure 15%
      1,000         7.44         1.12
     30,000       223.20        33.48
    300,000     2,232.00       334.80

A classification prompt is mostly input: the instructions, the list of categories, a few examples and the ticket (about 600 tokens here), for an answer of a few tokens. {per_day:>11,} right-aligns the number in 11 characters with thousands separators, and {everything:>10,.2f} does the same with two decimals. The money is often not the deciding factor at small volume; latency is. Routing a ticket in under a millisecond inside your own service, instead of waiting on a network call that can time out or be rate limited, is often what tips the choice.

Tip No labelled data yet? Let an LLM label a few thousand past tickets, have a person check a sample, then train a classic model on those labels. You pay for the LLM once instead of on every ticket. This is called distillation.

9Save the model and use it in your app

In a real project you train once, save the fitted pipeline to a file, and load it when your app starts. joblib (installed with scikit-learn, but add it yourself since you import it directly) saves Python objects that hold large NumPy arrays efficiently. This part needs files on disk, so it does not run in the browser: create a project with these commands and the file below. The output shows the packages uv installs.

Run
uv init ticket-router --python 3.12
cd ticket-router
uv add scikit-learn==1.9.1 joblib==1.6.0
You should see
 + joblib==1.6.0
 + numpy==2.5.5
 + scikit-learn==1.9.1
 + scipy==1.18.1
 (plus a few helper packages)
train_router.py
"""Train the ticket router once and save it to router.joblib."""
import joblib
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline

TICKETS = [
    ("I was charged twice for my subscription this month", "billing"),
    ("Please refund the last payment, I cancelled already", "billing"),
    ("My invoice shows the wrong amount", "billing"),
    ("How do I update the credit card on my account", "billing"),
    ("Why did my plan price go up", "billing"),
    ("I need a receipt for the payment for my company", "billing"),
    ("The app crashes when I upload a PDF", "bug"),
    ("Export button does nothing, nothing downloads", "bug"),
    ("Error 500 when I open the dashboard", "bug"),
    ("The page is blank after the latest update", "bug"),
    ("Search returns an error for long queries", "bug"),
    ("The chat widget freezes and crashes on mobile", "bug"),
    ("I forgot my password and the reset email never arrives", "account"),
    ("How do I change the email on my account", "account"),
    ("Please delete my account and my data", "account"),
    ("I cannot log in, it says my account is locked", "account"),
    ("Add a teammate to my workspace", "account"),
    ("Turn on two factor login for my account", "account"),
]

texts = [text for text, _ in TICKETS]
labels = [label for _, label in TICKETS]

router = make_pipeline(TfidfVectorizer(), LogisticRegression(C=10))
router.fit(texts, labels)
joblib.dump(router, "router.joblib")
print("saved router.joblib with classes", router.classes_.tolist())
  1. joblib.dump and joblib.load save and load any Python object; they are the usual way to store a scikit-learn model.line 2
  2. In a real project these rows come from your ticket history (a CSV export or a database query), usually thousands of them.line 7
  3. The **whole pipeline** is saved: the vocabulary, the IDF weights and the model weights. Saving only the model would lose the vocabulary.line 31

Next to it, route.py loads the file once, when the program starts, and reuses it for every ticket:

"""Load the saved router and classify the tickets given on the command line."""
import sys

import joblib

router = joblib.load("router.joblib")      # load once, at startup, not per request


def route(text: str, threshold: float = 0.6) -> tuple[str, float]:
    probs = router.predict_proba([text])[0]
    best = probs.argmax()
    label = str(router.classes_[best]) if probs[best] >= threshold else "ask the LLM"
    return label, float(probs[best])


def main() -> None:
    for text in sys.argv[1:]:              # every word after the script name
        label, confidence = route(text)
        print(f"{label:12} {confidence:.2f}  {text}")


if __name__ == "__main__":
    main()

sys.argv is the list of command-line arguments, like String[] args in Java, except that sys.argv[0] is the script name, so [1:] skips it. if __name__ == "__main__": is true only when you run the file directly, not when another file imports it, so a FastAPI app could from route import route without running main(). (That is also why the boxes on this page simply call their code at the top level: in the browser, __name__ is not "__main__".) Train, then route three tickets:

uv run python train_router.py
uv run python route.py "Please refund my last payment" "The export button crashes the app" "Do you have an office in Berlin"
saved router.joblib with classes ['account', 'billing', 'bug']
billing      0.78  Please refund my last payment
bug          0.83  The export button crashes the app
ask the LLM  0.36  Do you have an office in Berlin

To serve it, put the same route function behind a FastAPI endpoint (FastAPI lesson) and load the model at startup. When route says "ask the LLM", call the model as in the first LLM call lab.

Watch out joblib.load uses Python's pickle, which can run code while loading, so only load model files you created yourself. Load with the same scikit-learn version you trained with: a different version shows an InconsistentVersionWarning and can give wrong results or fail. That is why the version is pinned above.

Common mistakes

  • Scoring a model on the same rows it was trained on. It has seen the answers; split with train_test_split and score on the test part.
  • Leaving out random_state, then wondering why the split, the forest and the score change on every run.
  • Using k-NN (or anything distance-based) on features with very different scales without a StandardScaler.
  • Fitting the scaler or the TfidfVectorizer on all the data before splitting, so test-set information leaks into training. Put them in a Pipeline and fit it on the training rows only.
  • Passing one row as a flat list, predict([7, 4]). scikit-learn wants a 2D table even for one row: predict([[7, 4]]).
  • Saving only the final model and not the whole pipeline, so the app has no vocabulary or scaler to turn new input into the right numbers.

Practice

Write the code, then press Check. Your work is saved in this browser.

1Put the scaler in the pipeline

make_model() should return an unfitted model that scales the features with StandardScaler and then classifies with KNeighborsClassifier(n_neighbors=5), as one Pipeline. The tests fit it on the churn data from section 5 (rating and tokens) and expect at least 0.95 accuracy.

Exercise
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler


def make_model():
    return KNeighborsClassifier(n_neighbors=5)   # no scaling yet
Hint

`make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=5))` builds both steps in the right order.

2Route or hand over

Write route(model, text, threshold=0.6). model is a fitted text pipeline like the ticket router. Return the predicted label as a plain Python str when the highest probability is at least threshold, and the string "llm" otherwise. Try it in the box with the ROUTER defined below the function.

Exercise
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline


def route(model, text, threshold=0.6):
    return model.predict([text])[0]        # always trusts the model


ROUTER = make_pipeline(TfidfVectorizer(), LogisticRegression(C=10)).fit(
    ["refund my payment", "charged twice on my card", "wrong invoice amount",
     "app crashes on upload", "error 500 on the page", "export button broken"],
    ["billing", "billing", "billing", "bug", "bug", "bug"],
)
print(route(ROUTER, "refund my card payment"), route(ROUTER, "hello there"))
Hint

`probs = model.predict_proba([text])[0]`, `best = probs.argmax()`, then compare `probs[best]` with the threshold and return `str(model.classes_[best])` or `"llm"`.

3A fair split of sorted data

Your labelled data comes from a database query sorted by label: all the 0s first, then all the 1s. split(X, y) should return X_train, X_test, y_train, y_test with 20% of the rows in the test part, shuffled with random_state=42, and the same share of 1s in the test part as in the whole data. The starter just cuts off the last 20% of rows: see what that does to sorted data.

Exercise
from sklearn.model_selection import train_test_split


def split(X, y):
    cut = int(len(X) * 0.8)
    return X[:cut], X[cut:], y[:cut], y[cut:]


X = [[i] for i in range(50)]
y = [0] * 40 + [1] * 10            # sorted: forty 0s, then ten 1s
X_train, X_test, y_train, y_test = split(X, y)
print("test labels:", list(y_test))
Hint

`return train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)` already returns the four parts in this order.

Interview questions

Q1What is the difference between an estimator and a transformer in scikit-learn?

An estimator is anything with fit. A predictor (a model) also has predict (and usually score), and a transformer has transform to turn data into new data, such as StandardScaler or TfidfVectorizer. A Pipeline chains transformers and a final model into one estimator, so fit and predict run every step in order.

Q2Why do you scale features, and which models need it?

Models based on distances or on weight penalties (k-NN, SVMs, regularised linear and logistic regression, neural networks) are dominated by the features with the biggest numbers. StandardScaler gives every column mean 0 and standard deviation 1. Tree-based models (decision trees, random forests, gradient boosting) split on one feature at a time and do not need it. Fit the scaler on the training data only.

Q3Why does a random forest usually beat a single decision tree?

A deep tree overfits: it memorises noise in its training rows. A forest trains many trees on random samples of rows and random subsets of features, so each tree makes different mistakes, and averaging their votes cancels most of them. You get lower variance and better accuracy on new data, at the cost of a model that is harder to read.

Q4What do train_test_split, random_state and stratify do?

train_test_split shuffles the rows and splits them into a training part and a test part so you can measure the model on data it has not seen. random_state fixes the shuffle so the split, and the results, repeat exactly. stratify=y keeps the class proportions the same in both parts, which matters when one class is rare.

Q5When would you choose a classic model over an LLM for classification?

When the labels are fixed, the volume is high and you have labelled data: a TF-IDF plus logistic regression model costs almost nothing per prediction, answers in under a millisecond, always returns a valid label with a probability, and keeps data in house. Choose an LLM when you have little labelled data, the categories change often, or the task needs real language understanding. A common design uses the classic model first and sends low-confidence cases to the LLM.