Learning path: Classify and Evaluate: Logistic Regression to Cross-Validation · Step 2 of 7
Logistic Regression in scikit-learn: predict, predict_proba and Softmax
Logistic regression as the last step of a scikit-learn pipeline on Rain in Australia: test accuracy, max_iter and ConvergenceWarning, predict vs predict_proba, then three Iris classes and softmax worked by hand.
What you will learn
- Put LogisticRegression at the end of a preprocessing pipeline
- Set max_iter so training converges
- Read predict, predict_proba and classes_ together
- Follow softmax by hand for three classes
Before you start
- Logistic Regression and the Sigmoid
- Train-Test Split and Data Leakage
- Pipelines and ColumnTransformer
Imagine a weather app that only says "rain". Do you cancel the picnic? You can't tell. Another app says "70% chance of rain", and now you can decide for yourself.
In scikit-learn, predict is the first app: it gives the answer. predict_proba is the second: it gives the chance behind the answer. Logistic regression gives you both. Let's use it to predict rain tomorrow on the Rain in Australia data, then handle three classes with Iris.
Load, then split first
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer, make_column_selector
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.linear_model import LogisticRegression
df = pd.read_csv("weatherAUS.csv")
df = df.dropna(subset=["RainTomorrow"])
X = df.drop(columns=["Date", "RISK_MM", "RainTomorrow"])
y = df["RainTomorrow"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42)
share = y_train.value_counts(normalize=True)
print(X.shape, X_train.shape)
print(share.round(2).to_dict())
(142193, 21) (113754, 21)
{'No': 0.78, 'Yes': 0.22}
A row with no answer can't teach anything, so rows with a missing RainTomorrow go. The split comes before any step sees the data, with stratify=y so both parts keep 22% rainy days. (Why, and why RISK_MM is dropped, is in Train-Test Split and Data Leakage.)
The preprocess step
This is the step from Pipelines and ColumnTransformer. Numbers get the median for gaps and are scaled; text columns get the most frequent value and are one-hot encoded. A ColumnTransformer sends each kind of column to its own steps.
num_cols = make_column_selector(dtype_include="number")
cat_cols = make_column_selector(dtype_exclude="number")
numeric_steps = Pipeline([
("impute", SimpleImputer(strategy="median")),
("scale", StandardScaler()),
])
categorical_steps = Pipeline([
("impute", SimpleImputer(strategy="most_frequent")),
("onehot", OneHotEncoder(handle_unknown="ignore")),
])
preprocess = ColumnTransformer([
("num", numeric_steps, num_cols),
("cat", categorical_steps, cat_cols),
])
Plug in LogisticRegression
The only new thing is the last step, called clf:
clf = LogisticRegression(max_iter=1000)
model = Pipeline([
("preprocess", preprocess),
("clf", clf),
])
model.fit(X_train, y_train)
acc = model.score(X_test, y_test)
print("Test accuracy:", round(acc, 3))
Test accuracy: 0.849
One fit on the train rows runs every step. One score on the raw test rows gives 0.849.
max_iter: how many steps training may take
Training turns the knobs step by step until they stop improving. max_iter caps the number of steps. Watch what happens with only 20:
import warnings
model.set_params(clf__max_iter=20)
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
model.fit(X_train, y_train)
print([x.category.__name__ for x in w])
model.set_params(clf__max_iter=1000)
model.fit(X_train, y_train)
print("steps used:", clf.n_iter_[0])
['ConvergenceWarning']
steps used: 42
Twenty steps aren't enough, so you get a ConvergenceWarning. With a cap of 1000, training stops by itself after 42 steps. So 1000 is a safe ceiling, not a cost.
predict vs predict_proba
Three days from the test set:
days = X_test.iloc[:3]
days[["Location", "Humidity3pm", "RainToday"]]
Location Humidity3pm RainToday
47620 Canberra 32.0 No
98297 MountGambier 74.0 No
120302 Perth 57.0 No
print(model.predict(days))
print(model.predict_proba(days).round(2))
print(model.classes_)
['No' 'Yes' 'No']
[[0.91 0.09]
[0.46 0.54]
[0.65 0.35]]
['No' 'Yes']
predict gives one label per day. predict_proba gives one column per class, and the columns follow classes_: No first, then Yes. Mount Gambier gets 0.54 for Yes. That's a close call.
The score before the squash is there too:
scores = model.decision_function(days)
print(scores.round(2))
[-2.28 0.16 -0.64]
Score, squash, decide inside the pipeline
This is exactly the score, squash, decide from Logistic Regression and the Sigmoid. Training found the knobs for you.
Three classes: Iris
What if the answer isn't yes or no? Iris has 150 flowers, four measurements each, and three types.
from sklearn.datasets import load_iris
from sklearn.pipeline import make_pipeline
iris = load_iris(as_frame=True)
Xi = iris.data
yi = iris.target_names[iris.target]
print(Xi.shape)
Xi_train, Xi_test, yi_train, yi_test = train_test_split(
Xi, yi, test_size=0.2, stratify=yi, random_state=42)
flower_model = make_pipeline(
StandardScaler(), LogisticRegression(max_iter=1000))
flower_model.fit(Xi_train, yi_train)
acc = flower_model.score(Xi_test, yi_test)
print("Test accuracy:", round(acc, 3))
(150, 4)
Test accuracy: 0.933
There's nothing extra to switch on. With three classes, scikit-learn uses the multinomial model by default.
Three scores, three chances
flower = Xi_test.iloc[[5]]
print(flower.values)
print(flower_model.classes_)
print(flower_model.decision_function(flower).round(2))
print(flower_model.predict_proba(flower).round(3))
print(flower_model.predict(flower))
[[6.3 3.3 4.7 1.6]]
['setosa' 'versicolor' 'virginica']
[[-2.15 1.47 0.68]]
[[0.018 0.676 0.306]]
['versicolor']
The model gives one score per class. Softmax turns them into chances: take e to the power of each score, then divide each by the total.
import numpy as np
z = flower_model.decision_function(flower)[0]
print("e**z :", np.exp(z).round(2))
print("total:", np.exp(z).sum().round(2))
print("share:", (np.exp(z) / np.exp(z).sum()).round(3))
e**z : [0.12 4.35 1.97]
total: 6.44
share: [0.018 0.676 0.306]
| Class | Score z | ez | Share of 6.44 |
|---|---|---|---|
| setosa | -2.15 | 0.12 | 0.018 |
| versicolor | 1.47 | 4.35 | 0.676 |
| virginica | 0.68 | 1.97 | 0.306 |
The three chances add up to 1, and the biggest wins: versicolor. With only two classes, softmax works out exactly like the sigmoid.
Common mistakes
- Ignoring a ConvergenceWarning. Raise
max_iter; the model stops early on its own when it's done. - Guessing the column order of
predict_proba. Checkclasses_. Here column 1 is Yes because the labels sort as No, Yes. - Reading
predictalone. A chance of 0.54 and a chance of 0.95 both print Yes. The chance tells you which answers are close calls.
Quick recap
| Call | Gives | Example |
|---|---|---|
predict | the label | Yes |
predict_proba | a chance per class, in classes_ order | [0.46 0.54] |
decision_function | the raw score | 0.16 |
max_iter=1000 | a safe cap on training steps | used 42 |
| Softmax | scores to chances for many classes | versicolor 0.676 |
Try it yourself
Print model.predict_proba(X_test.iloc[:10]) and count the close calls: days with a chance of rain between 0.4 and 0.6.
The notebook and the dataset are in the StudyEasy AI Community, free to join.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Logistic Regression and the Sigmoid: Score, Squash, Decide
Next →Why Accuracy Lies: The Confusion Matrix, Baselines and Type I/II Errors
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Linear Regression and the Cost Function: Draw a Line, Score It
Draw a straight line through six kids' ages and weights, measure every miss, and turn the misses into one score, the mean squared error. Then let np.polyfit find the line with the lowest score.
Gradient Descent Explained: Feel the Slope, Step Downhill
Instead of handing over the best line, let the computer walk to it: measure the slope of the cost, step downhill with a learning rate, repeat. Shown step by step on six kids' ages and weights.
Linear Regression in scikit-learn: Fit, Predict and Read the Price Tags
Predict a yearly medical bill with scikit-learn's LinearRegression: first from age alone, then from every column inside a pipeline. Each coefficient reads like a price tag, and smoker_yes is by far the biggest.
Regression Metrics: MAE, RMSE, R-squared and the Baseline to Beat
Score a regression model honestly: MAE, MSE and RMSE from four darts, then the insurance model on 268 test people, a DummyRegressor baseline to beat, R-squared and adjusted R-squared, and a residual plot.