Logistic Regression in Python with scikit-learn
Answer yes/no questions with a probability: train LogisticRegression in a pipeline and read predict_proba.
- LogisticRegression in a scaling pipeline
- predict_proba and the 0.5 threshold
- Avoiding convergence warnings with max_iter
- 1
30 featuresScaled measurements - 2
weights . x + bWeighted sum - 3
sigmoid -> 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%.
StandardScaler()⚖️ Put all the evidence on the same scaleLogisticRegression()🧮 Weigh each piece of evidencepredict_proba(X)📈 Turn the total into a probabilitypredict(X)✅ Answer yes if the probability is above 0.5Logistic 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
make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))scales and trains in one step.- The model classifies 98.6% of the test tumours correctly.
predict_probareturns two columns: the probability of class 0 and of class 1.- 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
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]}")
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.
- Change random_state and see how much the score moves.
- Swap in another built-in dataset (wine, breast_cancer, digits) and rerun.
- Try a different model or hyperparameter and compare the scores.
Common mistakes
Training on unscaled features
The solver needs more steps and often stops with a ConvergenceWarning.
LogisticRegression().fit(X_train, y_train)
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.
- Logistic Regression Prediction Classify samples as 0 or 1 by passing a weighted sum through the sigmoid and comparing it to a threshold. Easy
- Perceptron Learning Algorithm Train the original perceptron, which updates its weights only when it makes a mistake. Medium
Tools for this lesson
- Linear and Logistic Regression in PythonFit a straight line with least squares, then turn a score into a probability with logistic regression.
- Jupyter Notebook Online: Run Python Cells in Your BrowserFree online Jupyter notebook: run Python cells with pandas, NumPy and Matplotlib, add Markdown text, open and download .ipynb files. No install, no account.
- pandas Online Compiler: Run pandas and NumPy in Your BrowserRun pandas and NumPy code online with nothing to install. NumPy, pandas, SciPy, Matplotlib and scikit-learn are ready in the free Python editor.