Rank Predictors by Logistic Regression Coefficient Magnitude
Machine LearningModel answerLast updated
Fit an unpenalized binary logistic regression with an intercept on a features-by-samples matrix, then return the three predictors with the largest absolute coefficients.
You are building a small utility that tells an analyst which predictors matter most for a yes/no outcome.
Inputs
X: a 2D numeric array of shapen_features x n_samples. Each row is one predictor and each column is one observation.feature_names: a list ofn_featuresstrings, where entryinames rowiofX.y: a length-n_samplesarray of labels, each 0 or 1.
Task
- Fit a binary logistic regression that predicts
yfrom the predictors. The model must contain an intercept and must use no regularization (unless a penalty is explicitly requested, which it is not here). - Rank the predictors by the absolute value of their fitted coefficients. The intercept does not take part in the ranking.
- Return the names of the three predictors with the largest
|coefficient|. If two predictors have the same magnitude, the one that comes first in lexicographic order of name ranks higher.
Output
A list of 3 strings, ordered from largest to smallest |coefficient|.
What to cover in your answer
- How you handle the orientation of
X. - How you fit the model (a library call or your own optimizer) and which settings matter.
- How you make the ranking deterministic.
- What you would say about the meaning of the ranking, and about inputs that could break the fit.
- Time and space complexity, plus code.
Hints
Hint 1
Standard fitting routines expect one row per observation. Check which axis of `X` holds samples before you pass it in.
Hint 2
If you use a library, look at its defaults. Many logistic regression implementations apply an L2 penalty and cap the number of iterations, and either can change the coefficients you rank.
Hint 3
Build the sort key as a tuple of negative rounded magnitude and name. This gives descending magnitude with ascending-name ties without reversing the whole sort. Think about what happens when the data are perfectly separable or when a feature is constant.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task has three parts: orient the data, fit an unpenalized logistic regression with an intercept, and rank the coefficients deterministically.
1. Orientation
X is n_features x n_samples, but fitting routines expect n_samples x n_features, so transpose before fitting. This is the most common failure. It either raises a shape error or, if the matrix happens to be square, silently fits the wrong problem. Validate that len(feature_names) == X.shape[0] and len(y) == X.shape[1] to catch it early.
2. Fitting
The model is P(y=1 | x) = sigmoid(b0 + w·x). Maximize the log-likelihood
l(beta) = sum_i [ y_i * eta_i - log(1 + exp(eta_i)) ], with eta_i = a_i · beta and a_i = [1, x_i].
The negative log-likelihood is convex, so any stationary point is the global maximum-likelihood fit. The gradient is A^T (y - p) and the negative Hessian is A^T W A with W = diag(p(1-p)). Newton's method on this objective is IRLS. It needs no learning rate and typically converges in 5 to 25 iterations.
With scikit-learn, the settings that matter are:
penalty=None(or'none'on older versions). The default is L2 withC=1.0, which shrinks coefficients and can reorder the ranking.- A larger
max_iter. The default 100 can stop early on unscaled data.
from sklearn.linear_model import LogisticRegression
clf = LogisticRegression(penalty=None, fit_intercept=True, max_iter=10000)
coefs = clf.fit(X.T, y).coef_.ravel()
3. Ranking
Drop the intercept and sort with the key (-round(|w|, 10), name). This yields descending magnitude with ties broken by ascending name. Rounding matters because mathematically equal coefficients (for example, duplicated features) can differ in the last bits, which would stop the name tie-break from applying. Avoid sorted(..., reverse=True) on (abs, name), because it also reverses the name order.
Full solution (plain NumPy)
import numpy as np
def _log_sigmoid(z):
return -np.logaddexp(0.0, -z) # stable log(sigmoid(z))
def _loglik(A, y, beta):
eta = A @ beta
return np.sum(y * _log_sigmoid(eta) + (1 - y) * _log_sigmoid(-eta))
def fit_logistic_irls(Xs, y, max_iter=100, tol=1e-10):
n, p = Xs.shape
A = np.hstack([np.ones((n, 1)), Xs])
beta = np.zeros(p + 1)
ll = _loglik(A, y, beta)
for _ in range(max_iter):
prob = np.exp(_log_sigmoid(A @ beta))
grad = A.T @ (y - prob)
W = prob * (1 - prob)
H = A.T @ (A * W[:, None])
step = np.linalg.lstsq(H, grad, rcond=None)[0]
t = 1.0
while True: # backtracking line search
cand = beta + t * step
cand_ll = _loglik(A, y, cand)
if cand_ll >= ll - 1e-12 or t < 1e-8:
break
t *= 0.5
prev, beta, ll = ll, cand, cand_ll
if np.max(np.abs(t * step)) < tol or abs(ll - prev) < tol:
break
return beta
def top_features(X, feature_names, y, k=3):
X = np.asarray(X, dtype=float)
y = np.asarray(y, dtype=float).ravel()
if X.ndim != 2 or len(feature_names) != X.shape[0] or y.shape[0] != X.shape[1]:
raise ValueError("shape mismatch")
if not np.all(np.isin(y, (0.0, 1.0))) or np.unique(y).size < 2:
raise ValueError("y must be binary with both classes present")
beta = fit_logistic_irls(X.T, y)
coefs = beta[1:]
ranked = sorted(zip(feature_names, coefs),
key=lambda nc: (-round(abs(nc[1]), 10), nc[0]))
return [name for name, _ in ranked[:k]]
Using lstsq for the Newton step keeps it stable when A^T W A is ill-conditioned (collinear features, or p(1-p) collapsing toward 0). The log-sigmoid via logaddexp avoids overflow, and backtracking guarantees the likelihood never decreases.
Complexity
With n samples, p features, and k Newton iterations:
- Time:
O(k * (n p^2 + p^3))for the fit, plusO(p log p)for the sort. - Space:
O(n p)for the design matrix andO(p^2)for the Hessian.
Trade-offs and interpretation
- Scale dependence. Coefficients are on the raw feature scale, so a predictor measured in small units gets a large coefficient. The task asks for the fitted coefficients, so do not standardize. State that standardized coefficients would answer a different question: effect per standard deviation.
- Coefficient magnitude is not causal importance. Correlated predictors share or trade weight arbitrarily.
Edge cases
- Perfect or quasi-complete separation. The unpenalized MLE does not exist and coefficients diverge. The iteration cap keeps the output finite and the separating features will dominate. In production, add a small penalty or use Firth regression.
- Constant features. They are collinear with the intercept, so the coefficient is unidentifiable. The minimum-norm
lstsqstep keeps it near 0. - Duplicate features. Weight is split between the copies, so they tie in magnitude and the name rule decides.
- Fewer than 3 features. Return all of them, ranked.
- Single class in
y. The intercept diverges. Raise an error or document the behavior. - Input types. Cast lists and ints to float arrays.
Common mistakes
- Fitting on
Xinstead ofX.T. - Leaving the default L2 penalty on.
- Including the intercept in the ranking.
- Sorting by signed coefficient rather than absolute value.
- Using
reverse=Trueand thereby flipping the tie-break. - Using a naive
1 / (1 + exp(-z))that overflows for large|z|. - Skipping the rounding step before comparing near-equal magnitudes.