Comparing Two Classifiers: Logistic Regression vs. Support Vector Machines (SVM)
Logistic Regression models conditional class probabilities via the sigmoid function and minimizes binary cross-entropy (log loss), yielding calibrated probabilities and interpretable linear weights. Support Vector Machines minimize hinge loss with an L2 margin penalty to find a maximum-margin hyperplane, supporting non-linear boundaries via kernel functions while requiring Platt scaling for probability estimates.
Study Card: Comparing Two Classifiers: Logistic Regression vs. Support Vector Machines (SVM)
Direct Answer
Logistic Regression and Support Vector Machines (SVMs) are both foundational supervised classifiers that solve convex optimization problems in their linear forms, yet they differ in objective functions, geometric focus, and non-linear extensibility:
- Objective & Geometry: Logistic Regression models by minimizing log loss (binary cross-entropy), meaning every training sample influences the fit (though confident well-classified points contribute exponentially decaying gradients). A linear SVM minimizes hinge loss plus (for ), maximizing the geometric margin and depending only on the support vectors near or inside the margin.
- Probabilities: Logistic Regression natively outputs well-calibrated probabilities, whereas standard SVMs output uncalibrated margin scores (
decision_function);SVC(probability=True)fits post-hoc Platt scaling via internal cross-validation. - Non-linearity: SVMs seamlessly learn non-linear boundaries through the kernel trick (e.g., RBF), whereas Logistic Regression requires explicit feature engineering or basis/kernel expansions.
Key Terms
- Sigmoid Function: , mapping linear logits to probabilities in .
- Maximum-Margin Hyperplane: The separating boundary that maximizes distance to the nearest points (support vectors) of each class.
- Log Loss vs. Hinge Loss: Log loss smoothly penalizes all miscalibrated predictions; hinge loss assigns zero loss once a point lies cleanly beyond the margin ().
- Kernel Trick: Computing inner products in a high-dimensional (even infinite-dimensional, for RBF) feature space via without explicitly forming coordinates.
- Regularization (): In both
LogisticRegressionandSVCin scikit-learn, is the inverse regularization strength—smaller enforces stronger regularization (wider margin / smaller weights), while larger fits training points more tightly.
Example
Consider classifying curved, non-linearly separable data such as two interleaving half-moons. Standard Logistic Regression (or a linear SVM) can only draw a single straight line, leaving many points misclassified. Using an SVM with an RBF kernel maps the inputs implicitly into a higher-dimensional space where a linear separator corresponds to a smooth non-linear curve in the original 2D space. Conversely, on high-dimensional sparse text features where classes are nearly linearly separable and calibrated risk probabilities are needed, L2-regularized Logistic Regression is fast, interpretable, and hard to beat.
Code Implementation
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_moons
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
# Generate non-linearly separable moons dataset
X, y = make_moons(n_samples=500, noise=0.2, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
)
# Always scale features for SVMs and regularized Logistic Regression
logreg = make_pipeline(StandardScaler(), LogisticRegression(C=1.0, random_state=42))
logreg.fit(X_train, y_train)
accuracy_logreg = accuracy_score(y_test, logreg.predict(X_test))
svm_rbf = make_pipeline(StandardScaler(), SVC(kernel='rbf', C=1.0, probability=True, random_state=42))
svm_rbf.fit(X_train, y_train)
accuracy_svm = accuracy_score(y_test, svm_rbf.predict(X_test))
print(f"Logistic Regression Accuracy: {accuracy_logreg:.4f}")
print(f"SVM (RBF Kernel) Accuracy: {accuracy_svm:.4f}")
# Side-by-side decision boundary comparison
x_min, x_max = X[:, 0].min() - 0.5, X[:, 0].max() + 0.5
y_min, y_max = X[:, 1].min() - 0.5, X[:, 1].max() + 0.5
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02), np.arange(y_min, y_max, 0.02))
grid = np.c_[xx.ravel(), yy.ravel()]
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
for ax, model, title in [
(axes[0], logreg, f"Logistic Regression (Acc={accuracy_logreg:.2f})"),
(axes[1], svm_rbf, f"SVM with RBF Kernel (Acc={accuracy_svm:.2f})"),
]:
Z = model.predict(grid).reshape(xx.shape)
ax.contourf(xx, yy, Z, cmap=plt.cm.RdBu, alpha=0.35)
ax.scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap=plt.cm.RdBu, edgecolors='k')
ax.set_title(title)
ax.set_xlabel("Feature 1")
ax.set_ylabel("Feature 2")
plt.tight_layout()
plt.show()
Related Concepts
- Bias-Variance Tradeoff: Linear Logistic Regression has higher bias and lower variance on non-linear data; RBF SVMs with large and large reduce bias at the risk of overfitting (high variance).
- Computational Scaling: Dual kernel SVMs scale roughly to with sample count , making linear models or stochastic solvers (
SGDClassifier,LinearSVC) preferable on massive datasets. - Outlier Sensitivity: Because Logistic Regression log loss grows roughly linearly for badly misclassified points whereas hinge loss also grows linearly beyond the margin, both are much more robust to outliers than squared error—though SVM margins can still shift if outliers become support vectors.
- Model Interpretability: Logistic Regression coefficients directly express log-odds changes per unit feature change, whereas RBF SVMs are harder to interpret directly.