Precision and Recall
Part of the Supervised Learning section of Coddy's Machine Learning journey. Lesson 22 of 58.
Two questions grade a test's flu answers. Of its flu alarms, how many were right? Of the real flu cases, how many did it catch?
Precision answers the first: 42 of 45 alarms. Recall answers the second: 42 of 47 cases.
from sklearn.metrics import precision_score, recall_score
print(f"{precision_score(y_test, pred):.3f}")
print(f"{recall_score(y_test, pred):.3f}"):.3f always shows 3 decimals, so 0.9 would print 0.900. This prints:
0.933
0.894Choose by the costlier mistake. A missed flu case spreads, so this test needs recall. A spam filter that buries real mail needs precision.
Challenge
MediumA shop's filter hides reviews that look fake. The starter makes two versions from one model, strict_pred and eager_pred, and reads which mistake hurts more: missed (a fake stays up) or hidden (a real review vanishes).
- Print each filter's precision and recall, 3 decimals.
- Print the filter that makes fewer of that mistake, as below (for
missed:Fewer fakes missed: ...).
For another shop and hidden:
Strict: precision 0.900, recall 0.450
Eager: precision 0.640, recall 0.800
Fewer real reviews hidden: strictTry it yourself
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import precision_score, recall_score
# Which mistake hurts more: missed (a fake review stays up) or hidden (a real review is hidden)
worse = input()
# One row per review: 1 in fake means the review was written to order
reviews = pd.read_csv("reviews.csv")
features = ["words", "exclamations", "account_days", "user_reviews", "stars", "photo"]
X_train, X_test, y_train, y_test = train_test_split(reviews[features], reviews["fake"], test_size=0.25, random_state=0)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
model = LogisticRegression(max_iter=1000)
model.fit(X_train, y_train)
proba = model.predict_proba(X_test)[:, 1]
# Two filters from the same model: strict hides a review at a 0.7 chance of fake, eager at 0.3
strict_pred = proba >= 0.7
eager_pred = proba >= 0.3
# Write your code below
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Supervised Learning
1Your First Model
Learning from ExamplesTrain and Test SetsFit and PredictScoring a ModelRecap: Seed Sorter2Nearest Neighbors
How k-NN DecidesChoosing kDecision BoundariesScaling for NeighborsRecap: Wine Neighbors5Measuring Classifiers
The Confusion MatrixPrecision and RecallThe F1 ScoreImbalanced ClassesROC CurvesRecap: Screening Test11Project: Penguin Species
Meet the PenguinsPrepare the DataChoose a ModelTune the WinnerShip the ModelPractice on your own: Online Python compiler