KatInterview

Rank Predictors by Logistic Regression Coefficient Magnitude

Machine LearningModel answer
MediumModel answerMachine Learninglogistic-regressionfeature-importancenumpy

Last 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 shape n_features x n_samples. Each row is one predictor and each column is one observation.
  • feature_names: a list of n_features strings, where entry i names row i of X.
  • y: a length-n_samples array of labels, each 0 or 1.

Task

  1. Fit a binary logistic regression that predicts y from the predictors. The model must contain an intercept and must use no regularization (unless a penalty is explicitly requested, which it is not here).
  2. Rank the predictors by the absolute value of their fitted coefficients. The intercept does not take part in the ranking.
  3. 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.