Machine Learning with scikit-learn

Logistic Regression in Python with scikit-learn

Answer yes/no questions with a probability: train LogisticRegression in a pipeline and read predict_proba.

  • Intermediate
  • 3 min read
  • 1 runnable example
What you'll learn
  • LogisticRegression in a scaling pipeline
  • predict_proba and the 0.5 threshold
  • Avoiding convergence warnings with max_iter
One tumour
  1. 130 featuresScaled measurements
  2. 2weights . x + bWeighted sum
  3. 3sigmoid -> 0.969Probability of benign

From a score to a probability

The problem

Many questions have two answers: spam or not, pass or fail, malignant or benign. You want a model that gives not only the answer but also how sure it is.

Think of it like this

Logistic regression is like a doctor adding up the evidence for and against, then turning the total into a percentage. Lots of evidence one way gives a probability near 0 or 1; mixed evidence gives something close to 50%.

From weighing evidence to code
StandardScaler()⚖️ Put all the evidence on the same scale
LogisticRegression()🧮 Weigh each piece of evidence
predict_proba(X)📈 Turn the total into a probability
predict(X)✅ Answer yes if the probability is above 0.5
A weighted sum squeezed into a probability.
In one sentence

Logistic regression computes a weighted sum of the features and passes it through the sigmoid function, which turns any number into a probability between 0 and 1.

Key points

  1. make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)) scales and trains in one step.
  2. The model classifies 98.6% of the test tumours correctly.
  3. predict_proba returns two columns: the probability of class 0 and of class 1.
  4. Sample 2 has P(benign) = 0.559, just above 0.5, so it is a close call.

When should you use it?

  • Yes/no predictions where you also need a probability.
  • A fast, explainable baseline for classification.
  • Medical, credit and spam models where the threshold may be moved.

When not to use it

  • Predicting a number such as a price: use linear regression.
  • Strongly non-linear boundaries: try a random forest or an SVM with an RBF kernel.

Example code

Open in editor →
main.py
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = load_breast_cancer(return_X_y=True)  # 0 = malignant, 1 = benign
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)

# Scaling inside the pipeline: fitted on the training data only
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
model.fit(X_train, y_train)
print(f"Test accuracy: {model.score(X_test, y_test):.3f}")

# predict_proba gives [P(class 0), P(class 1)] for each row
probabilities = model.predict_proba(X_test[:5])
for row, (p0, p1) in enumerate(probabilities):
    label = model.predict(X_test[row:row + 1])[0]
    print(f"Sample {row}: P(benign) = {p1:.3f} -> class {label}, actual {y_test[row]}")
Get a Run button for this example

Result of running the code

Test accuracy: 0.986
Sample 0: P(benign) = 0.969 -> class 1, actual 1
Sample 1: P(benign) = 0.000 -> class 0, actual 0
Sample 2: P(benign) = 0.559 -> class 1, actual 1
Sample 3: P(benign) = 0.939 -> class 1, actual 1
Sample 4: P(benign) = 0.175 -> class 0, actual 0

Code explanation

make_pipeline chains StandardScaler and LogisticRegression, so fit scales the training data and trains the model in one step, and later calls scale new rows with the training statistics. max_iter=1000 gives the solver enough steps to converge without a warning. The model classifies 98.6% of the test tumours correctly. predict_proba returns two probabilities per row; the code prints P(benign), and predict picks class 1 when it is above 0.5, so sample 2 with 0.559 is a close call while sample 1 with 0.000 is certain.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Change random_state and see how much the score moves.
  2. Swap in another built-in dataset (wine, breast_cancer, digits) and rerun.
  3. Try a different model or hyperparameter and compare the scores.
Run in the Python compiler →

Common mistakes

Training on unscaled features

The solver needs more steps and often stops with a ConvergenceWarning.

Problem
LogisticRegression().fit(X_train, y_train)
Fix
make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)).fit(X_train, y_train)

Finished this lesson?

Mark it as learned to track your progress.

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges

Tools for this lesson