Courses / Data Science & ML with AI
Session 6 of 8
Classification in Python: Logistic Regression, the
Notes
Classification in Python: Logistic Regression, the Confusion Matrix, Precision and Recall
Course: Data Science & ML with AI
Before you start
You need Python 3 with pandas, numpy and scikit-learn installed (pip install pandas numpy scikit-learn). The examples use a dataset that ships inside scikit-learn, so there is nothing to
download, no account and no API key. You should know what a train/test split is and why a model is
scored on rows it did not learn from; this chapter restates the little you need. No statistics
background is assumed.
Keep one question in mind while you read: a classifier reports “96% accurate”. What else must I look at before I believe it is a good classifier? By the end you will be able to read a confusion matrix, compute precision and recall by hand, move a decision threshold on purpose, and check an AI assistant’s choice of threshold against the matrix it implies.
Summary
A classifier predicts one label from a fixed list, and logistic regression is the standard first one: it turns the input columns into a probability and then into a label by comparing that probability with a threshold, which is 0.5 by default. Accuracy, the share of correct predictions, can look excellent while a model misses the cases that matter, so a classifier is judged with a confusion matrix that counts the four kinds of outcome, and with precision (how many flagged rows were right) and recall (how many true rows were found). Moving the threshold trades one for the other, and which way to move it is a decision about the cost of each kind of mistake, not a setting to leave at its default. This chapter trains a logistic regression on the bundled breast cancer dataset and shows how to check an AI assistant’s threshold against the confusion matrix it implies.
Key concepts
| Term | Definition |
|---|---|
| Classification | Supervised learning where the target is one label from a fixed list, such as benign or malignant. |
| Binary classification | Classification with exactly two labels. One is named the positive class, the case the project is trying to find. |
| Positive class | The label the model is asked to find, such as “malignant”. The choice is yours; precision and recall are measured relative to it. |
| Logistic regression | A classifier that combines the input columns into one score, converts the score to a probability between 0 and 1, and predicts the positive class when that probability passes a threshold. Despite the name, it is a classification model. |
| Probability (predicted) | The model’s estimate, between 0 and 1, that a row belongs to the positive class. In scikit-learn it comes from predict_proba. |
| Decision threshold | The probability above which the model predicts the positive class. By default scikit-learn uses 0.5. |
| Confusion matrix | A table that counts a classifier’s predictions against the true labels: one row per true class, one column per predicted class. |
| True positive, false positive | A true positive is a positive row correctly flagged; a false positive is a negative row wrongly flagged as positive (a false alarm). |
| False negative, true negative | A false negative is a positive row the model missed; a true negative is a negative row correctly left alone. |
| Accuracy | The share of all predictions that are correct: (true positives + true negatives) divided by all rows. |
| Precision | Of the rows the model flagged as positive, the share that really are positive: true positives divided by (true positives + false positives). |
| Recall | Of the rows that really are positive, the share the model found: true positives divided by (true positives + false negatives). |
| Class imbalance | A target where one label is much more common than the other, which lets a model score high accuracy by favouring the common label. |
| Majority-class baseline | A classifier that ignores the inputs and always predicts the most common label, the least a real model must beat. |
Explanations
The failure, before the explanation
A hospital team wants software that flags suspicious tumour measurements for a second look. An analyst builds a classifier, scores it on 143 held-back cases and writes in her report: “accuracy 62.9%, better than a coin flip”. The report goes out. A week later a pathologist asks how many of the malignant cases the software caught. The answer is none. The model has never flagged a single case. It always answers “benign”, and because 90 of the 143 held-back cases are benign, it is right 62.9% of the time.
Nothing in her code failed, and the accuracy figure is correct. The failure is that one number hid the thing the hospital cared about. The rest of this chapter gives you the tools that expose it: a table that separates the kinds of mistake, two metrics that measure them, and a threshold you can move. You will reproduce her 62.9% in the section on accuracy.
What classification and logistic regression are
Think of an email filter. For each message it does not just say “spam” or “not spam”; somewhere inside, it forms a degree of suspicion, say 0.93 for a message full of prize offers and 0.02 for a note from a colleague, and then applies a rule: “if the suspicion is above one half, move it to the spam folder”. Two steps: first a number, then a cut-off. That is exactly how logistic regression works.
A second picture: a bank clerk adds up points for a loan application, so many points for income, minus points for missed payments, and then converts the total into a chance of repayment, where a large positive total means “very likely” and a large negative total means “very unlikely”. The clerk’s total is the model’s score. Turning that total into a chance between 0 and 1 is done by the logistic function, an S-shaped curve: scores far below zero map to probabilities near 0, a score of exactly zero maps to 0.5, and scores far above zero map to probabilities near 1.
Classification is supervised learning whose target is a label from a fixed list. With two labels it is binary classification, and one label is picked as the positive class, the case you want to find. The scikit-learn user guide describes logistic regression as a linear model for classification rather than regression despite its name: the probabilities of the possible outcomes are modelled with a logistic function. The guide also notes that regularization, a penalty that keeps the weights small, is applied by default. For binary problems scikit-learn then predicts the positive class when the predicted probability is greater than 0.5, which is the same as the score being greater than 0.
Load the breast cancer data and choose the positive class
The scikit-learn breast cancer dataset describes 569 tumour samples with 30 numeric measurements each, such as the mean radius and the mean texture of the cell nuclei. Its documentation lists 212 samples as malignant and 357 as benign. Run this:
import pandas as pd
from sklearn.datasets import load_breast_cancer
data = load_breast_cancer(as_frame=True)
X = data.data
y = data.target
print(X.shape)
print(data.target_names.tolist())
print(y.value_counts().sort_index())
print(X.isna().sum().sum())
It prints:
(569, 30)
['malignant', 'benign']
target
0 212
1 357
Name: count, dtype: int64
0
Read the output. There are 569 rows and 30 feature columns, and no missing values. The target
holds 0 for malignant and 1 for benign, because the label names are listed in that order. That is
a trap for the careless: in scikit-learn the label 1 is treated as the positive class by default,
so using y as it comes would make “benign” the positive class and make the precision and recall in this chapter
measure the wrong thing. The project wants to find malignant cases, so the first move is to build a
target in which 1 means malignant:
from sklearn.model_selection import train_test_split
y_malignant = (y == 0).astype(int) # 1 = malignant (the case to catch), 0 = benign
X_train, X_test, y_train, y_test = train_test_split(
X, y_malignant, test_size=0.25, stratify=y_malignant, random_state=42
)
print(X_train.shape, X_test.shape)
print(y_test.sum(), "malignant and", (y_test == 0).sum(), "benign in the test rows")
(426, 30) (143, 30)
53 malignant and 90 benign in the test rows
stratify=y_malignant makes the split keep the same share of malignant rows in the training set
and the test set, which matters when one label is rarer than the other. random_state=42 fixes the
shuffle so you get the same split. The test set holds 143 rows: 53 malignant and 90 benign.
Why accuracy alone can mislead
Accuracy is the share of predictions that are right. Return to the analyst’s report. Here is
her “model” in code: a DummyClassifier, which the scikit-learn documentation describes as a simple
baseline to compare other classifiers against. With strategy="most_frequent" it ignores the
inputs and always predicts the most common label in the training rows.
from sklearn.dummy import DummyClassifier
from sklearn.metrics import accuracy_score, recall_score
always_benign = DummyClassifier(strategy="most_frequent").fit(X_train, y_train)
dummy_pred = always_benign.predict(X_test)
print("accuracy:", round(accuracy_score(y_test, dummy_pred), 3))
print("recall:", recall_score(y_test, dummy_pred))
accuracy: 0.629
recall: 0.0
That is the 62.9% from the report, and a recall of 0.0: not one of the 53 malignant rows was
found. The cause is class imbalance. When one label is common (here 90 of 143 test rows are
benign), a model that always predicts it gets a high accuracy without learning anything. This is why
a second picture helps: a smoke alarm that never rings is correct on every day without a fire, and
useless on the one day it matters. Any score for a classifier must therefore be read next to the
majority-class baseline, and next to a table that shows which rows were missed.
The confusion matrix: four kinds of outcome
Start with something small and invented. A spam filter is run on 100 emails, of which 20 really are spam. It flags 22 emails as spam: 18 of them truly are spam and 4 are ordinary mail. So it correctly flags 18 spam emails (true positives), wrongly flags 4 ordinary emails (false positives), misses 2 spam emails (false negatives) and correctly leaves 76 ordinary emails alone (true negatives). 18 + 4 + 2 + 76 = 100. A confusion matrix lays those four counts in a 2-by-2 table, rows for the true class and columns for the predicted class:
| Predicted not spam | Predicted spam | |
|---|---|---|
| Really not spam | 76 true negatives | 4 false positives |
| Really spam | 2 false negatives | 18 true positives |
The scikit-learn documentation defines the matrix this way: the entry in row i and column j
counts samples whose true label is the i-th class and whose predicted label is the j-th class.
For a binary problem with labels 0 and 1 that gives true negatives at row 0 column 0, false
positives at row 0 column 1, false negatives at row 1 column 0 and true positives at row 1 column 1.
Calling .ravel() on the matrix lists the four counts in the order tn, fp, fn, tp.
Now fit a real classifier. The pipeline below scales each feature and then fits a logistic
regression. Putting both in one Pipeline means the scaler learns its averages from the training
rows only, as chapter 4 taught. max_iter=1000 raises the limit on solver iterations from its
default of 100 so the solver has room to converge.
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix, precision_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
model.fit(X_train, y_train)
pred = model.predict(X_test)
cm = confusion_matrix(y_test, pred)
print(cm)
tn, fp, fn, tp = cm.ravel()
print("tn", tn, "fp", fp, "fn", fn, "tp", tp)
[[89 1]
[ 4 49]]
tn 89 fp 1 fn 4 tp 49
Read it. Of the 90 benign rows, 89 were correctly left alone and 1 was flagged by mistake. Of the 53
malignant rows, 49 were found and 4 were missed. The four counts add up to 143, the size of the
test set. Compare it with the matrix of the “always benign” model, which would show [[90 0] over
[53 0]]: an accuracy of 0.629 and a whole bottom row of misses.
Precision and recall: the two questions a matrix answers
A confusion matrix answers two different questions, and each has its own metric.
Precision asks: when the model raises the alarm, how often is it right? It is true positives divided by (true positives + false positives). In the spam example, 18 of the 22 flagged emails were spam, so precision is 18 / 22 = 0.818. Low precision means many false alarms: a mail filter with low precision buries real mail in the spam folder.
Recall asks: of the cases that really are positive, how many did the model find? It is true positives divided by (true positives + false negatives). In the spam example, 18 of the 20 spam emails were found, so recall is 18 / 20 = 0.9. Low recall means many missed cases: a screening test with low recall sends sick people home. The scikit-learn documentation frames precision as restraint (not calling negatives positive) and recall as coverage (turning up the positives). Compute both for the spam filter, then for the tumour classifier:
spam_tp, spam_fn, spam_fp, spam_tn = 18, 2, 4, 76
total = spam_tp + spam_fn + spam_fp + spam_tn
print(spam_tp / (spam_tp + spam_fp), spam_tp / (spam_tp + spam_fn), (spam_tp + spam_tn) / total)
0.8181818181818182 0.9 0.94
The third number is accuracy, 94 of 100. Now the breast cancer model:
tn, fp, fn, tp = confusion_matrix(y_test, pred).ravel()
print("accuracy:", round(accuracy_score(y_test, pred), 3))
print("precision:", round(precision_score(y_test, pred), 3))
print("recall:", round(recall_score(y_test, pred), 3))
print("by hand:", round(tp / (tp + fp), 3), round(tp / (tp + fn), 3))
accuracy: 0.965
precision: 0.98
recall: 0.925
by hand: 0.98 0.925
Accuracy is 96.5%, against 62.9% for the baseline, so the model has learned something. Precision of 0.98 is 49 / (49 + 1): nearly all alarms are right. Recall of 0.925 is 49 / (49 + 4): 4 of 53 malignant rows were missed. The two metrics disagree about how good the model is, and that disagreement is information the accuracy figure never showed.
Try it: from the matrix [[89 1] [4 49]], compute the share of benign rows that were correctly left
alone, 89 divided by (89 + 1). Check it against 0.989. It answers the question “how often is a
benign row cleared?” and is the recall of the benign class.
Predicted probabilities and the decision threshold
So far the model returned labels. Underneath, a logistic regression computes a probability for each
row, and predict_proba returns it. For a row with a probability of 0.035 the model is saying
“3.5% chance of malignant”, far from the alarm line. For a row at 0.999 it is nearly certain. The
decision threshold is the line between them. The scikit-learn guide on tuning the decision
threshold says that for binary classification the positive class is predicted when the probability
is greater than 0.5, or when the decision score is greater than 0, and that this cut-off is
hard-coded. It also points out that when the question is whether to classify a patient as having
cancer, it may be more beneficial to predict positive when the probability is much lower than 0.5.
import numpy as np
proba = model.predict_proba(X_test)[:, 1] # chance of class 1 (malignant)
print(proba[:6].round(3))
print(y_test.values[:6])
z = model.decision_function(X_test)[:6] # the score, before it becomes a probability
print(z.round(2))
print((1 / (1 + np.exp(-z))).round(3))
[0.999 0.004 1. 0. 0.035 0.004]
[1 0 1 0 0 0]
[ 7.4 -5.54 8.11 -17.67 -3.33 -5.62]
[0.999 0.004 1. 0. 0.035 0.004]
The first row has a score of 7.4, which the S-shaped function turns into 0.999, and it really is
malignant. The last printed line recomputes the probabilities from the scores with
1 / (1 + exp(-score)), and matches predict_proba exactly: the probability is the logistic
function of the score. A score of 0 would give 1 / (1 + 1) = 0.5, which is why “score above 0” and
“probability above 0.5” are the same rule.
Because the model already hands you probabilities, you can apply any threshold yourself and look at what each one costs:
print("threshold fp fn precision recall")
for t in [0.9, 0.5, 0.3, 0.1, 0.05]:
flagged = (proba > t).astype(int)
tn, fp, fn, tp = confusion_matrix(y_test, flagged).ravel()
print(f"{t:>9} {fp:>2} {fn:>2} {precision_score(y_test, flagged):>9.3f} {recall_score(y_test, flagged):>6.3f}")
threshold fp fn precision recall
0.9 0 10 1.000 0.811
0.5 1 4 0.980 0.925
0.3 1 2 0.981 0.962
0.1 6 1 0.897 0.981
0.05 11 0 0.828 1.000
Read the table from top to bottom. A high threshold of 0.9 makes the model cautious: it flags only rows it is very sure about, so there are no false alarms (precision 1.000) but 10 of 53 malignant rows are missed (recall 0.811). Lowering the threshold flags more rows. Misses fall from 10 to 0, and the false alarms rise from 0 to 11, so precision drops to 0.828. Lowering the threshold flags a superset of the rows flagged before, so true positives can only stay the same or rise, which is why recall never falls as you move down the table, while precision tends to fall because the extra rows include more benign ones. (At 0.3 precision edges up from 0.980 to 0.981 because the two extra rows flagged were both true positives; the tendency is not a law.)
There is no best threshold in general. In a cancer screen, a missed tumour is far costlier than an extra follow-up appointment, so a team might choose 0.1 and accept 6 false alarms to miss 1. For a filter that deletes email automatically, a false positive loses a real message and a team might choose a high threshold. The choice is a statement about the cost of each mistake. Checking it against the data is the job of the confusion matrix, which the next section uses.
With AI: check an assistant’s threshold against its confusion matrix
An AI assistant can write the thresholding code and explain it fluently. It does not know what a
missed tumour costs your team, and it often reports whichever number looks best. Suppose you ask it:
“Pick a decision threshold for the breast cancer classifier so that we are sure when we flag a
case.” It returns this, using the proba from above:
Assistant output
I chose a threshold of 0.9, so the model flags a tumour as malignant only when it is at least 90% confident.
flagged = (proba > 0.9).astype(int) print("precision:", precision_score(y_test, flagged)) print("accuracy:", round(accuracy_score(y_test, flagged), 3))Result: precision 1.0 and accuracy 0.93. Every flagged case is truly malignant, so this threshold is excellent. Recommended.
Run its code and the output matches what it claims. The flaw is not a calculation error; it is what the answer leaves out. The check you were taught is the confusion matrix and the recall: ask what this threshold implies for the rows that are truly malignant.
flagged = (proba > 0.9).astype(int)
print(confusion_matrix(y_test, flagged))
print("recall:", round(recall_score(y_test, flagged), 3))
print("missed:", int(((flagged == 0) & (y_test.values == 1)).sum()))
[[90 0]
[10 43]]
recall: 0.811
missed: 10
Try it first: use the matrix to say what the assistant did not. Then compare.
Check your work. The matrix shows 0 false positives, which is why precision is 1.0, but also 10 false negatives: 10 of the 53 malignant cases (recall 0.811) would never be flagged. Precision of 1.0 answers “when it flags, is it right?” and says nothing about the cases it never flags. The assistant’s wording, “sure when we flag”, was met literally and at a cost nobody asked it to weigh. Its accuracy of 0.93 is lower than the 0.965 you got at 0.5, so “excellent” and “recommended” are unsupported even on its own metric. A sound answer would show the matrix at several thresholds, as in the table above, and ask which kind of mistake your project can least afford. Whatever the assistant proposes, the check to run is the same: print the confusion matrix for that threshold and read the false-negative cell.
Three situations you will meet, and what they mean for your work
- A teammate shares a model with “97% accuracy” for detecting a fault that occurs in 3 of every 100 machines.
- A fraud team’s classifier flags so many purchases that reviewers cannot keep up, and most of the flagged purchases turn out to be genuine.
- A medical screening model is deployed with its default threshold, and a clinician reports that some cases it should have caught were never flagged.
| What you see | What it means | What to do |
|---|---|---|
| High accuracy on a rare event (situation 1) | A model that never flags a fault would score 97% as well | Compare with the majority-class baseline, then read recall for the fault class |
| Many flagged rows are wrong (situation 2) | Precision is low: too many false positives | Check the matrix; raise the threshold if reviewers’ time is the scarce resource |
| Cases missed (situation 3) | Recall is too low for the cost of a miss | Print the matrix at lower thresholds and pick the one whose false negatives you can accept |
Flashcards
Say the answer aloud before revealing it. Speaking it is what exposes the gaps that reading past a written answer hides.
What is the positive class, and why does the choice matter?
The positive class is the label the project is trying to find, such as malignant. Precision and recall are measured relative to it, so picking the wrong label as positive makes both answer the wrong question.
How does logistic regression turn inputs into a label?
It combines the inputs into one score, converts the score into a probability with the logistic function, and predicts the positive class when the probability is above the threshold, 0.5 by default.
What does `predict_proba` return, and how is it different from `predict`?
predict_proba returns the estimated probability of each class for each row, while predict
returns the final label chosen by applying the 0.5 threshold to those probabilities.
Why can a model with 62.9% accuracy be useless?
With imbalanced classes, a model that predicts the common label every time can score a high accuracy without finding any positive case. In the example it was right 62.9% of the time with a recall of 0.
What does the confusion matrix count, and where are the four cells?
It counts predictions against true labels. For labels 0 and 1, row 0 holds true negatives then false positives, and row 1 holds false negatives then true positives.
What is the formula for precision, and what question does it answer?
True positives divided by (true positives + false positives). It answers: when the model flags a row, how often is it right? Low precision means many false alarms.
What is the formula for recall, and what question does it answer?
True positives divided by (true positives + false negatives). It answers: of the rows that really are positive, how many did the model find? Low recall means many missed cases.
What happens to precision and recall when you lower the threshold?
More rows are flagged, so recall stays the same or rises, while precision tends to fall because more of the flagged rows are false positives. In the example, 0.5 to 0.1 moved recall from 0.925 to 0.981 and precision from 0.980 to 0.897.
Why did the assistant's threshold of 0.9 look good and still fail?
Its precision was 1.0 because there were no false positives, but the matrix showed 10 of 53 malignant cases missed (recall 0.811). Precision alone hides missed cases.
What does `stratify` do in `train_test_split`?
It splits the rows so that the training set and the test set keep the same share of each class as the whole data, which matters when one label is rare.
Model answer
The question: “You have built a classifier that finds malignant tumours. How do you decide whether it is good enough to use?” A strong answer hits five beats, in this order:
- Held-back rows — score on rows the model never trained on.
- Baseline — compare with a model that always predicts the common label.
- Confusion matrix — count true and false positives and negatives.
- Precision and recall — read both, relative to the positive class.
- Threshold — choose the cut-off by the cost of each kind of mistake.
“I would score on a test set the model has not seen, and compare with a majority-class baseline, because on imbalanced data a model that always predicts the common label can show a high accuracy and find nothing. Then I would print the confusion matrix, so I can see the false positives and the false negatives separately instead of one blended number. From it I would compute precision, how often a flag is right, and recall, how many real cases are found, both relative to the positive class I care about, here malignant. Finally I would treat the decision threshold as a choice: for a cancer screen a missed case costs more than a false alarm, so I would lower it from 0.5 and look at the matrix at each candidate, then pick the one whose misses the team can accept.”
Skip any of these five and the answer is incomplete. Without held-back rows the score flatters the model. Without a baseline an accuracy of 62.9% sounds acceptable. Without the matrix the misses are invisible. Without precision and recall there is no vocabulary for the two kinds of mistake. Without the threshold beat, the default of 0.5 is accepted as if it were a fact about the problem; that is the beat that is easiest to forget.
Why this matters
- Trusting a number. “Accuracy” on its own is a common flattering figure in classification reports. Asking “against what baseline, and what does the matrix show?” catches it.
- Matching the model to the cost. Screening, fraud, fault detection and spam filtering each weigh a miss and a false alarm differently, and the threshold is where you encode that.
- Reviewing AI-written code. An assistant can produce a threshold, a metric and a recommendation in one confident paragraph. The confusion matrix is the quickest way to see what the paragraph left out.
- Talking to non-specialists. Precision and recall translate into plain sentences, “when it flags a case it is right 98% of the time, and it finds 92.5% of the real cases”, that a manager can act on.
After this unit
You can now judge a classifier by more than one number. The next chapter keeps the classification setting and moves to models that make no straight-line assumption: decision trees, random forests and gradient boosting. It also teaches cross-validation and grid search, which let you choose a model’s settings fairly instead of from a single lucky split.
Quiz
Answers are not marked on this page yet. Work through the questions and check the written ones against the criteria printed with each question. The answer key is kept back for now.
Quiz — Classification in Python: Logistic Regression, the Confusion Matrix, Precision and Recall
Instructions: Eight multiple-choice questions. Pick one option per question. Work closed-book, then compare your letters with the answer key, which is held separately and holds the reasons.
1. [recall] Which description fits recall in a binary classification problem?
a) Of the rows the model flagged as positive, the share that truly are positive b) Of those rows that really are positive, the share the model managed to flag c) Of all the rows that were scored, the share given the correct class labels d) Of the rows the model flagged, the share that turned out to be false alarms
2. [application] A model is scored on 100 held-back rows and produces 70 true negatives, 10 false positives, 5 false negatives and 15 true positives. What is its precision?
a) 0.75, which is 15 out of the 20 rows that are truly positive b) 0.85, which is 85 out of all the 100 rows that were scored c) 0.88, which is 70 out of the 80 rows that are truly negative d) 0.60, which is 15 out of the 25 rows it flagged as positive
3. [scenario] A team’s classifier reports 90% accuracy on test rows, and 9 of every 10 of those rows are negative. A reviewer asks for one more check before anyone relies on the number. Which check is most useful?
a) Compare it with an always-negative model, then read the recall for the positive class b) Retrain it with a larger iteration limit so that the 90% figure climbs closer to 100% c) Accept it, because 90% is far above the 50% that a coin flip reaches on two labels d) Lower the threshold to 0.1 first, because accuracy rises whenever more rows are flagged
4. [application] A learner calls confusion_matrix(y_true, y_pred) on labels 0 and 1, where 1 is
the positive class, and gets [[50, 5], [8, 37]]. Which count is the false negatives?
a) The 5, in row 0 column 1, which counts negative rows wrongly flagged as positive b) The 37, in row 1 column 1, which counts positive rows that were correctly flagged c) The 8, in row 1 column 0, which counts positive rows that the model overlooked d) The 50, in row 0 column 0, which counts negative rows correctly left alone
5. [recall] With its default settings, when does a scikit-learn logistic regression predict the positive class for a row in a binary problem?
a) When the row’s score is the highest of all the scores in the test set b) When the predicted probability of the negative class tops 0.9 c) When the predicted probability of the positive class is above 0.5 d) When more than half of the input columns exceed their column averages
6. [scenario] A fraud team keeps the same trained model and the same test rows, but lowers its decision threshold from 0.5 to 0.1. What change should the team expect?
a) Recall holds steady or rises, while false positives usually rise as rows get flagged b) Recall falls, because the model now keeps only the cases it is most confident about c) Precision rises to 1.0, because each flagged row is now a more carefully chosen one d) Precision and recall stay unchanged, because the trained weights have not been altered
7. [recall] Why does the chapter pass stratify=y_malignant to train_test_split?
a) To scale every feature so that its average is 0 across the training rows b) To make sure that no single row can appear in both of the two sets c) To shuffle the rows into a fresh random order each time the code runs d) To keep the share of malignant rows about the same in both of the sets
8. [scenario] An assistant picks a threshold of 0.9 for a screening classifier and reports a precision of 1.0 for it, calling the result excellent. What should you do before accepting it?
a) Accept it, since a precision of 1.0 is the best value that the metric can reach b) Print the confusion matrix at that threshold and read the false negatives and recall c) Re-run it on the training rows, where a precision of 1.0 would be even more convincing d) Switch the positive class to benign so that the reported precision stays at 1.0
Want help building this with someone?
Tell us what you are working on and we will write back about a mentor-led cohort, live sessions or 1:1 training. It is only an enquiry: you choose whether to go further.
Ask about mentor-led trainingTechEazy Consulting training material — not affiliated with or endorsed by pandas, scikit-learn or any other project or company named in this course.