Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Scan for outdated or missing drivers - takes under a minute3Clear out junk files and repair common Windows errorsiTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
Logistic regression is a supervised classification algorithm. It estimates the probability that an observation belongs to a class, then applies a decision threshold to turn that probability into a prediction.
It is a strong baseline for problems such as spam detection, customer churn, fraud screening, medical risk classification, and text categorization. It trains quickly, works well with large sparse feature sets, and produces coefficients that can be inspected. Its main limitation is equally important: the model is linear in the features you provide. It does not automatically discover arbitrary nonlinear patterns or feature interactions.
How logistic regression works
For binary classification, logistic regression first calculates a linear score:
z = β₀ + β₁x₁ + β₂x₂ + ... + βₚxₚ
That score is passed through the sigmoid function:
P(y = 1 | x) = 1 / (1 + e⁻ᶻ)
The sigmoid converts any real-valued score into a number between 0 and 1. That number is interpreted as the estimated probability of the positive class.
Popular on Amazon
In a typical binary classifier, scikit-learn’s default rule is to predict class 1 when the probability is greater than 0.5. The model’s underlying decision score uses the equivalent rule of a score greater than 0. This threshold is only a default; it should change when false positives and false negatives have different consequences.
The log-odds interpretation
Logistic regression is linear in the log-odds, not directly in the probability:
log(p / (1 - p)) = β₀ + β₁x₁ + ... + βₚxₚ
A coefficient tells you how much the log-odds change after a one-unit increase in its feature, while the other features remain constant. Exponentiating a coefficient gives the corresponding odds multiplier.
| Coefficient | Odds multiplier | Interpretation |
|---|---|---|
| 0 | e⁰ = 1 | No change in odds |
| 0.693 | About 2 | Odds approximately double |
| -0.693 | About 0.5 | Odds are approximately halved |
This interpretation only makes sense when the feature scale and encoding are meaningful. For example, a one-unit increase in annual income is not comparable to a one-unit increase in a standardized feature. Correlated predictors can also make individual coefficients unstable even when predictions remain useful.
Types of logistic regression
| Task | Use |
|---|---|
| Binary classification | Choose between two classes, such as fraud and legitimate. |
| Multinomial classification | Choose among three or more mutually exclusive classes, such as red, blue, or green. |
| One-vs-rest classification | Train one binary classifier for each class and compare their scores. |
Multinomial logistic regression directly models multiple mutually exclusive classes. One-vs-rest is an alternative approach that fits a separate binary model for each class. In current scikit-learn, solvers other than liblinear optimize the multinomial loss when there are at least three classes. liblinear handles binary classification and can be wrapped in OneVsRestClassifier when that strategy is required.
Ordered labels such as low, medium, and high should not automatically be encoded as 0, 1, and 2 and sent to ordinary logistic regression. That is an ordinal-classification problem and may require a model designed to use the ordering.
When logistic regression is a good choice
- The decision boundary is approximately linear in the selected features.
- You need fast training and prediction.
- You want a compact model that is relatively easy to inspect.
- Ranking or probability estimates are useful.
- Your data contains many one-hot encoded or sparse text features.
- You need a dependable baseline before trying more complex models.
It is a poor fit when the target depends on complex interactions or curved boundaries that are not represented in the inputs. You can add polynomial features, splines, transformations, or explicit interaction terms, but doing so increases feature count and can make interpretation harder. Tree-based models and neural networks may be more suitable when the structure is strongly nonlinear.
Building a model with scikit-learn
The following example uses a stratified 80/20 split and a regularized logistic classifier:
Also popular on Amazon
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.2,
random_state=0,
stratify=y,
)
model = LogisticRegression(
solver="lbfgs",
C=1.0,
max_iter=1000,
random_state=0,
)
model.fit(X_train, y_train)
class_predictions = model.predict(X_test)
probabilities = model.predict_proba(X_test)
scores = model.decision_function(X_test)
predict returns class labels. predict_proba returns estimated probabilities for each class, in the order stored in model.classes_. decision_function returns the raw decision score. The fitted coefficients are available in model.coef_, and the intercept is in model.intercept_.
Use a pipeline for preprocessing
Scaling, imputation, encoding, and feature selection should be fitted only on training data. A pipeline enforces that rule during both ordinary fitting and cross-validation:
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
model = make_pipeline(
StandardScaler(),
LogisticRegression(
solver="lbfgs",
C=1.0,
max_iter=1000,
random_state=0,
),
)
model.fit(X_train, y_train)
Do not use StandardScaler(with_mean=True) on a sparse matrix. Centering a sparse one-hot or text matrix generally converts it to dense form, potentially exhausting memory. For sparse input, use:
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →StandardScaler(with_mean=False)
Note about recent scikit-learn versions
In the current scikit-learn documentation, the penalty parameter is deprecated from version 1.8 and is scheduled for removal in 1.10. New code should follow the current API's recommendation of expressing the regularization choice through l1_ratio and C where supported:
| Regularization | Configuration |
|---|---|
| L2 | l1_ratio=0 |
| L1 | l1_ratio=1 |
| Elastic Net | 0 < l1_ratio < 1 |
| None | C=float("inf") |
Check the installed version's API before copying older examples that use penalty="l1", penalty="l2", or penalty=None. Existing code may continue to work during the deprecation period, but newly written code should be forward-compatible.
Regularization and the C parameter
Scikit-learn regularizes logistic regression by default. Regularization discourages excessively large coefficients, which can improve generalization and reduce the effect of noisy or redundant features.
C is the inverse of regularization strength:
- Smaller
Cmeans stronger regularization. - Larger
Cmeans weaker regularization. C=float("inf")represents an unpenalized model.
L1 regularization can reduce some coefficients exactly to zero, making it useful for sparse feature selection. L2 generally shrinks coefficients without eliminating as many of them. Elastic Net combines the two behaviors and is available with the saga solver.
Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Clear out junk files and repair common Windows errorsFree Scan →Select C using cross-validation rather than choosing it after inspecting the test set:
Also popular on Amazon
from sklearn.linear_model import LogisticRegressionCV
model = LogisticRegressionCV(
Cs=10,
cv=5,
solver="lbfgs",
scoring="neg_log_loss",
max_iter=1000,
random_state=0,
)
model.fit(X_train, y_train)
Choosing a solver
| Solver | Best use | Important limitation |
|---|---|---|
lbfgs |
General-purpose dense problems and multinomial classification. | Does not support L1 or Elastic Net. |
liblinear |
Small binary problems and L1 regularization. | Does not perform true multinomial classification. |
saga |
Large sparse data, L1, and Elastic Net. | Features should be approximately similarly scaled for fast convergence. |
sag |
Large datasets with suitable scaling. | Supports L2, not L1 or Elastic Net. |
newton-cholesky |
Cases where samples greatly outnumber features. | Hessian storage has quadratic memory dependence on features and classes. |
Scaling is particularly important for sag and saga. It often improves optimization for other regularized solvers as well. A convergence warning is not a harmless message to suppress: it means the optimizer may not have reached a satisfactory solution.
Thresholds: why 0.5 is not universal
A probability is not the same thing as a final business decision. If missing a positive case is expensive, you may accept more false positives by lowering the threshold:
positive_probability = model.predict_proba(X_test)[:, 1]
y_pred = (positive_probability >= 0.30).astype(int)
Choose the threshold using validation data or cross-validation predictions, not the final test set. Scikit-learn provides TunedThresholdClassifierCV for cross-validated threshold tuning and FixedThresholdClassifier for applying a selected threshold.
Recommended Free Tools
For example, a fraud team may prefer a threshold of 0.30 to send more transactions for review, while an automated system with expensive manual investigations may require a higher threshold. The correct value depends on error costs, capacity, and the consequences of each mistake.
How to evaluate logistic regression
Use metrics that match what the model will do in production:
| Metric | Useful for |
|---|---|
| Log loss | Assessing the quality of probability estimates. |
| ROC AUC | Measuring ranking performance across thresholds. |
| Average precision | Evaluating ranking in many imbalanced positive-class problems. |
| Precision, recall, F-score | Measuring a chosen positive-class trade-off. |
| Calibration curve | Checking whether predicted probabilities match observed frequencies. |
| Confusion matrix | Showing errors at one explicitly stated threshold. |
Accuracy can look impressive when one class dominates. A model that labels every transaction as legitimate could achieve 99% accuracy on a dataset with only 1% fraud while detecting no fraud at all. Always report the positive-class definition, class prevalence, threshold, and evaluation population.
Class imbalance
For imbalanced training data, scikit-learn can give greater weight to underrepresented classes:
model = LogisticRegression(
class_weight="balanced",
solver="lbfgs",
max_iter=1000,
)
The balanced weight for class j is calculated as:
n_samples / (n_classes * n_j)
Class weights alter the training objective. They do not automatically produce probabilities calibrated to the original population. If the model's probabilities will be used as risk estimates, check calibration on data representing the population in which the model will operate. Class weights are also multiplied by any sample_weight passed to fit.
Also popular on Amazon
Probability calibration
A classifier can rank cases correctly while producing poor probabilities. A calibrated model is one where predictions near 0.7 correspond, over many cases, to an observed positive rate near 70%.
Calibration is affected by regularization, model specification, class weighting, sampling, and changes between training and deployment data. When reliable probabilities matter, calibrate using held-out or cross-validated predictions:
from sklearn.calibration import CalibratedClassifierCV
calibrated_model = CalibratedClassifierCV(
estimator=model,
method="sigmoid",
cv=5,
)
calibrated_model.fit(X_train, y_train)
probabilities = calibrated_model.predict_proba(X_test)
Current scikit-learn calibration tools support sigmoid and isotonic calibration, along with temperature scaling through the calibration API. Do not fit the calibrator on the same observations used to fit the base classifier; that can produce overly extreme and biased probabilities.
Common problems and practical fixes
ConvergenceWarning
Common causes include badly different feature scales, too few iterations, a very large C, strongly correlated columns, perfect separation, or a solver that does not suit the data. Start with a pipeline, scale dense features, use with_mean=False for sparse data, and try a more suitable solver.
model = LogisticRegression(
solver="lbfgs",
C=0.1,
max_iter=2000,
tol=1e-4,
)
Inspect n_iter_ after fitting. Increasing max_iter may help, but it does not repair leakage, severe collinearity, poor scaling, or separation.
Perfect separation
Perfect separation occurs when a linear combination of features divides the classes completely. An unregularized statistical logistic model may try to send coefficients toward infinity rather than find finite estimates. Very large coefficients and probabilities extremely close to 0 or 1 are warning signs.
Check for target leakage, duplicated predictors, and rare categories. Regularization, combining sparse categories, collecting more data, or using a different model can help. Statsmodels reports this condition through PerfectSeparationError.
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteWindows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallDummy-variable trap and collinearity
With an intercept, including every one-hot column for a categorical variable creates exact linear dependence. Drop one reference category or use an encoder configured to avoid redundant columns. Strong but imperfect collinearity may not destroy predictive accuracy, but it makes coefficient magnitudes and signs difficult to interpret.
Also popular on Amazon
- Use scikit-learn to track an example ML project end to end
- Explore several models, including support vector machines, decision trees, random forests, and ensemble methods
- Exploit unsupervised learning techniques such as dimensionality reduction, clustering, and anomaly detection
- Dive into neural net architectures, including convolutional nets, recurrent nets, generative adversarial networks, autoencoders, diffusion models, and transformers
- Use TensorFlow and Keras to build and train neural nets for computer vision, natural language processing, generative models, and deep reinforcement learning
Preprocessing leakage
Fitting a scaler, imputer, encoder, feature selector, or calibrator on the complete dataset before cross-validation allows validation information into training. Put every learned preprocessing step inside a Pipeline.
Scikit-learn versus statsmodels
Scikit-learn's logistic regression is primarily prediction-oriented and regularized by default. Use it for production pipelines, cross-validation, sparse features, and predictive evaluation.
Statsmodels is often a better choice when you need coefficient tables, standard errors, likelihood-based tests, or confidence intervals:
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
import statsmodels.api as sm
X_with_intercept = sm.add_constant(X)
model = sm.Logit(y, X_with_intercept)
result = model.fit()
print(result.summary())
probabilities = result.predict(X_with_intercept)
Statsmodels expects the design matrix supplied by the caller, so sm.add_constant is important when an intercept is intended. Its unregularized likelihood estimates are not interchangeable with scikit-learn's default regularized estimates.
A practical checklist
- Define the positive class and the real cost of false positives and false negatives.
- Choose a split that reflects deployment. Use
stratify=yfor ordinary independent classification data, but use time-based or group-based splits for temporal data, repeated entities, or related observations. - Place scaling, encoding, imputation, and selection inside a pipeline.
- Choose a solver compatible with your data size, sparsity, number of classes, and regularization.
- Tune
Cand, if applicable,l1_ratiousing cross-validation. - Evaluate log loss, ranking, calibration, and threshold-specific errors rather than accuracy alone.
- Select the operating threshold on validation data.
- Check convergence, leakage, collinearity, calibration, and performance on the expected production population.
FAQ
Is logistic regression a regression algorithm or a classification algorithm?
In machine-learning practice, logistic regression is a classification algorithm. It estimates class probabilities using a linear model and the sigmoid function, rather than predicting an unrestricted continuous value.
Why does logistic regression need feature scaling?
Scaling is not mathematically mandatory for every solver, but it often improves optimization and makes regularization more comparable across features. It is especially important for the fast-convergence guarantees of the sag and saga solvers. Sparse matrices must be scaled with StandardScaler(with_mean=False).
Is a 0.5 probability threshold always correct?
No. 0.5 is scikit-learn's default binary threshold, not a universal rule. Lower or raise it according to error costs, review capacity, and the consequences of false positives and false negatives.
Free tools Windows power users keep installed
One-click scans. No signup required.
What is the difference between logistic regression in scikit-learn and statsmodels?
Scikit-learn focuses on predictive modeling and applies regularization by default. Statsmodels is commonly used for statistical inference, including standard errors, tests, confidence intervals, and coefficient summaries. Their estimates are not automatically interchangeable.
The Bottom Line
Logistic regression remains one of the most useful classification baselines because it is fast, compact, interpretable, and effective on linear and sparse feature spaces. Build it inside a leakage-safe pipeline, choose regularization and a solver deliberately, evaluate probabilities as well as class labels, and tune the decision threshold for the actual cost of errors. When the data contains strong nonlinear structure or the probabilities are used for high-stakes decisions, validate its assumptions and compare it with more flexible and calibrated alternatives.

