Linear Models & Optimization
Linear regression, regularization (L1/L2/Elastic Net), the closed-form OLS solution and its pitfalls, and gradient-based optimization.
30 questions
JuniorTheoryVery commonWhich assumptions does linear regression make, and which one invalidates its p-values?
Which assumptions does linear regression make, and which one invalidates its p-values?
Linearity in the parameters, independent errors, constant variance, roughly normal residuals. Heteroscedasticity or correlated errors leave coefficients unbiased but break the standard-error formula, so p-values need robust errors.
Common mistakes
- ✗Requiring the features themselves to be normal instead of the residuals
- ✗Treating every assumption as equally critical for prediction and inference
- ✗Not knowing robust standard errors repair inference under heteroscedasticity
Follow-up questions
- →Why does the central limit theorem make the normality assumption mild on large samples?
- →Which assumption breaks first on time-series data, and what does that do to inference?
JuniorTheoryVery commonHow is one linear regression coefficient read, and when does that reading break?
How is one linear regression coefficient read, and when does that reading break?
It is the change in the target when this feature grows by one unit and the other features stay fixed. Correlated features make coefficients unstable, even flipping signs, and different scales make magnitudes incomparable until standardized.
Common mistakes
- ✗Expecting the largest coefficient to mark the most important feature: a coefficient is per unit of its feature, so switching metres to millimetres shrinks it 1000 times; standardize first.
- ✗Expecting coefficients of correlated features to be stable: when two features move together, the model can shift weight between them, so their coefficients swing and can flip sign.
Follow-up questions
- →Why does a penalty applied to unscaled columns punish small-scale features hardest?
- →What does an inflated coefficient variance tell you about a pair of correlated columns?
JuniorTheoryVery commonWhy is a binary label fitted with logistic regression instead of linear regression?
Why is a binary label fitted with logistic regression instead of linear regression?
A linear fit is unbounded, so it predicts probabilities below zero or above one and is skewed by far-off points. Logistic regression squashes the score through a sigmoid into a log-odds model and trains on convex log-loss.
Common mistakes
- ✗Reading a raw linear score as a probability without any bounding
- ✗Thinking log-loss is picked for convenience rather than convexity
- ✗Assuming squared error on a sigmoid output trains just as well
Follow-up questions
- →What does the linear part of the model predict on the log-odds scale?
- →Why does squared error on a sigmoid output starve the gradient when a prediction is confidently wrong?
JuniorTheoryCommonWhat does this program print?
What does this program print?
1.87 0.8
Open full question →Common mistakes
- ✗Expecting
-1.87 -0.8:w - lr * dwsteps against the gradient; atw = b = 0every prediction is below its target, sodwanddbare negative and both parameters grow. - ✗Expecting
18.67 8.0: the step is the gradient timeslr, so the gradients-18.67and-8.0shrink tenfold before they are subtracted.
Follow-up questions
- →What happens to
wover many steps if the learning ratelris set to 1.0 here? - →Why do both gradients come out negative at the starting point
w = 0,b = 0?
JuniorTheoryCommonWhich modifications of gradient descent do you know?
Which modifications of gradient descent do you know?
Common variants: SGD with momentum (accumulates past gradients), AdaGrad (per-parameter adaptive step), RMSProp (AdaGrad with a decaying average against step collapse), Adam (momentum + RMSProp) and Adan. They differ in how they adapt the step size and smooth the gradient direction.
Common mistakes
- ✗Confusing optimizer variants with regularization techniques
- ✗Thinking Adam is unrelated to momentum and RMSProp rather than combining them
- ✗Believing RMSProp and AdaGrad are unrelated rather than RMSProp refining AdaGrad
Follow-up questions
- →What does momentum add over plain SGD?
- →Why does RMSProp fix AdaGrad's vanishing step-size problem?
JuniorTheoryCommonWhat does this program print?
What does this program print?
0 1
Open full question →Common mistakes
- ✗Expecting
0 0: the L1 penalty ofLassosets the coefficient of the second column, which does not help predicty, exactly to zero. - ✗Expecting
1 1: the L2 penalty ofRidgeshrinks every coefficient toward zero but never makes one exactly zero.
Follow-up questions
- →What happens to the first coefficient of
Lassoasalphakeeps growing? - →Why should the features be scaled before either penalty is applied?
JuniorTheoryCommonHow is linear regression usually solved in practice?
How is linear regression usually solved in practice?
On moderate data, with a direct least-squares solve via QR or SVD, never an explicit matrix inverse — that is what sklearn's LinearRegression does. When data outgrow memory, gradient methods take over: full-batch GD uses all samples per step, SGD one sample or a mini-batch and scales best.
Common mistakes
- ✗Computing the normal-equation inverse explicitly instead of a QR or SVD least-squares solve
- ✗Not distinguishing full-batch GD from stochastic/mini-batch SGD
- ✗Thinking SGD is only an approximation used when GD is unavailable
Follow-up questions
- →Why do solvers use QR or SVD instead of explicitly inverting X-transpose-X?
- →When would you prefer mini-batch SGD over full-batch GD?
JuniorTheoryCommonWhat does this program print?
What does this program print?
2.0 1.0
Open full question →Common mistakes
- ✗Expecting
2.0 6.0: the intercept isy.mean() - w * x.mean(), so the slope times the mean ofxis subtracted:6.0 - 2.0 * 2.5 = 1.0. - ✗Expecting
2 1becausexandyhold integers:.mean()always returns a float, sowandbare floats and print as2.0and1.0.
Follow-up questions
- →What would
wandbbecome if every value ofywere shifted up by 10? - →Why does this slope formula break when every value of
xis the same?
JuniorTheoryCommonWhat does a logistic regression coefficient of 0.7 on a feature mean?
What does a logistic regression coefficient of 0.7 on a feature mean?
Each one-unit rise in the feature, others held fixed, adds 0.7 to the log-odds of the positive class, so the odds multiply by exp(0.7) ≈ 2. How far the probability moves depends on where you are on the sigmoid.
Common mistakes
- ✗Reading the coefficient as a fixed change in probability — it is linear in log-odds, and the sigmoid flattens near 0 and 1, so one step moves the probability most near 0.5.
- ✗Treating the coefficient as a multiplier on the probability —
exp(coef)multiplies the odds p/(1−p), and only that ratio stays constant per unit of the feature.
Follow-up questions
- →How does standardizing the feature change the size of its coefficient and its reading?
- →What does a negative coefficient do to the odds, and what is exp of it?
JuniorTheoryCommonWhat does this program print?
What does this program print?
0.02 1
Open full question →Common mistakes
- ✗Expecting
0.98: the columns ofpredict_probafollowmodel.classes_, so column0holds the probability of class0; class1is in column1. - ✗Expecting
predictto return a probability: it returns a label, here1, because the probability of class1is above 0.5.
Follow-up questions
- →How do you get the probability of class
1for every row ofX_test? - →What does
model.classes_hold, and how does it set the column order?
JuniorTheoryCommonWhat does this program print?
What does this program print?
0.5 0.95
Open full question →Common mistakes
- ✗Expecting
0.0for a score of zero: the sigmoid of0is1 / (1 + 1) = 0.5, the point where the model sees both classes as equally likely. - ✗Expecting
0.05for a score of3: withnp.exp(-z)in the denominator a positive score gives a probability above 0.5;0.05would neednp.exp(z).
Follow-up questions
- →Which value of
xgives a probability of exactly 0.5 whenw = 2.0andb = -3.0? - →Why can the output of the sigmoid be read as a probability for any score?
JuniorTheoryCommonHow do you trade precision for recall in a logistic regression that is already trained?
How do you trade precision for recall in a logistic regression that is already trained?
predict labels a row positive when predict_proba gives it more than 0.5. Lower that threshold on the probabilities and more rows are flagged — recall rises or holds, precision usually drops — with no retraining.
Common mistakes
- ✗Retraining to change the precision–recall balance — the model already gives a probability per row, and moving the threshold on
predict_probashifts the balance with no newfit. - ✗Changing
Cto move recall —Csets the regularization strength; it changes the weights, not the 0.5 threshold that turns probabilities into labels.
Follow-up questions
- →How would you pick the new threshold so that it does not overfit the test set?
- →Why does lowering the threshold never reduce recall but can raise precision on some data?
JuniorTheoryCommonWhat is naive about naive Bayes, and why does it still classify well?
What is naive about naive Bayes, and why does it still classify well?
It assumes the features are independent within each class, which real features rarely are. It still classifies well since only the top class matters: double-counted evidence makes probabilities extreme but rarely changes the winner.
Common mistakes
- ✗Thinking the naive part is the bell-shaped (normal) distribution of the features: that is only
GaussianNB's choice for continuous data; every variant assumes features independent within a class. - ✗Expecting a false assumption to ruin the predictions: it skews the probabilities toward 0 or 1, but the decision needs only the top class, which usually stays the same.
Follow-up questions
- →Why can a badly calibrated score still produce the right class decision?
- →What does additive smoothing fix when a word is unseen for one class?
JuniorTheoryCommonHow do training and test error change as the degree of a polynomial regression grows?
How do training and test error change as the degree of a polynomial regression grows?
Training error keeps falling as the degree grows, while test error falls at first and then rises once the curve starts fitting noise. Pick the degree on validation data, and scale and regularize high-degree terms.
Common mistakes
- ✗Picking the degree with the lowest training error — a higher degree can always bend closer to the training points, so that choice ends in overfitting.
- ✗Choosing the degree on the test set — the test score then stops being an honest estimate, so tune the degree on a validation split or with cross-validation.
Follow-up questions
- →Why do x¹⁰ and x columns need scaling before regularization treats them fairly?
- →What does the validation curve over degree look like for an underfit and an overfit model?
JuniorTheoryCommonWhat does this program print?
What does this program print?
6
Open full question →Common mistakes
- ✗Expecting
5: by defaultinclude_bias=Trueadds a column of ones, so the columns are 1, a, b, a², a·b and b². - ✗Expecting
9from counting a·b and b·a apart: they are one product, andPolynomialFeaturesmakes one column for it.
Follow-up questions
- →Which columns disappear with
include_bias=False, and why doesLinearRegressionnot need them? - →How does the number of columns grow when a third input feature is added at the same degree?
JuniorTheoryCommonWhy can LinearRegression fit a curve once the feature transformer PolynomialFeatures expands x?
Why can LinearRegression fit a curve once the feature transformer PolynomialFeatures expands x?
The model w0 + w1·x + w2·x² is non-linear in x but linear in its weights, because x² enters it as one more feature column. So ordinary least squares fits it the same way it fits a straight line.
Common mistakes
- ✗Thinking a curved fit needs a non-linear optimizer — linear refers to the weights, and x² enters as a plain column, so least squares still has a closed-form solution.
- ✗Reading the pipeline as a different model class — it is still linear regression; only the feature matrix gained the columns x², x³ and so on.
Follow-up questions
- →How many feature columns does a degree-3 expansion of two input features produce?
- →Which model would be non-linear in its weights, and how is it fitted instead?
JuniorTheoryCommonWhat is regularization, and which kinds apply to linear models?
What is regularization, and which kinds apply to linear models?
Regularization fights overfitting by adding a weight-norm penalty to the optimization objective. For linear models: L1 (sum of absolute weights), L2 (sum of squared weights), and Elastic Net (a mix of L1 and L2). The penalty discourages overly large weights.
Common mistakes
- ✗Confusing regularization (a penalty term) with feature scaling or feature selection
- ✗Thinking L1 and L2 differ only in scale, not in their effect on sparsity
- ✗Believing Elastic Net is a separate algorithm rather than a weighted sum of L1 and L2 penalties
Follow-up questions
- →Which of L1 and L2 drives weights exactly to zero, and why?
- →Should the bias/intercept term be included in the penalty?
JuniorTheoryCommonHow do you read a residual plot, and what do a funnel shape and a curve mean?
How do you read a residual plot, and what do a funnel shape and a curve mean?
Plot residuals against predictions: a shapeless band around zero is healthy. A curve means the model missed a non-linear pattern; a funnel means the error spread grows with the prediction, and taking the log of the target often helps.
Common mistakes
- ✗Expecting a funnel and a curve to mean the same thing: a curve says the model's form misses a non-linear pattern, while a funnel says the error spread grows with the prediction.
- ✗Ignoring a curve because the overall metric looks fine: a good R-squared can hide a systematic pattern the model misses, and more data will not remove it.
Follow-up questions
- →Which assumption does the funnel shape specifically falsify?
- →Why does a log transform of the target often flatten a funnel?
JuniorTheoryCommonWhat does this program print?
What does this program print?
2.0 0.1
Open full question →Common mistakes
- ✗Expecting
2.0 2.0because the points lie exactly on a line: the penalty grows withalphaand pulls the slope toward zero even when the fit is perfect. - ✗Expecting
0.0for the strong model: the L2 penalty ofRidgeshrinks a coefficient but never makes it exactly zero, so it stays at0.1.
Follow-up questions
- →How does the intercept of
strongchange, given thatRidgedoes not penalize it? - →Which
alphawould you expect to work best on new data, and how would you choose it?
JuniorTheoryCommonWhat happens when this program runs?
What happens when this program runs?
fit raises ValueError: it needs a 2-D X shaped (n_samples, n_features)
Common mistakes
- ✗Expecting scikit-learn to reshape a 1-D
xitself:fitrefuses it withValueError: Expected 2D array; passx.reshape(-1, 1), one column with one row per sample. - ✗Expecting a
TypeErrorover integer data: scikit-learn convertsintarrays tofloaton its own; the only problem here is the missing second dimension ofX.
Follow-up questions
- →What shapes do
x.reshape(-1, 1)andx.reshape(1, -1)give here, and which one doesfitneed? - →Why may the target
ystay 1-D while the feature matrixXmust be 2-D?
MiddleTheoryCommonWhat does a generative model learn versus a discriminative one, and who wins on tiny data?
What does a generative model learn versus a discriminative one, and who wins on tiny data?
A generative model learns the joint distribution — class prior plus per-class feature distribution — and derives the posterior. A discriminative one fits the boundary directly. Naive Bayes hits its higher asymptotic error sooner and wins on tiny data.
Common mistakes
- ✗Swapping the two definitions and calling the boundary learner generative
- ✗Assuming the small-sample winner is also the large-sample winner
- ✗Believing a generative model must always be able to synthesize realistic inputs
Follow-up questions
- →Which of the two would you pick once labelled data become plentiful, and why?
- →What extra thing can a generative model do that a boundary learner cannot?
MiddleTheoryCommonWhat is the closed-form OLS solution, and why is it avoided in practice?
What is the closed-form OLS solution, and why is it avoided in practice?
Minimizing the squared error gives w = (XᵀX)⁻¹Xᵀy. It is avoided because inverting XᵀX is costly on many features, and XᵀX may be singular or ill-conditioned, so the inverse is impossible or numerically unstable. Adding λI fixes the conditioning; gradient methods are preferred.
Common mistakes
- ✗Misremembering the formula (wrong placement of the transpose or inverse)
- ✗Citing only the inversion cost and forgetting the singularity/ill-conditioning problem
- ✗Not knowing that regularization restores invertibility via
λI
Follow-up questions
- →What is the computational complexity of the matrix inversion involved?
- →How exactly does adding
λImakeXᵀXinvertible?
MiddleTheoryCommonWhy does penalizing the weight norm help fight overfitting?
Why does penalizing the weight norm help fight overfitting?
A symptom of overfitting is very large weights. With huge weights, two near-identical inputs differing by epsilon can yield wildly different predictions — the function is unstable. Penalizing the norm shrinks weights toward zero, giving a smoother, lower-variance function that generalizes better.
Common mistakes
- ✗Thinking the penalty improves the fit on the training set rather than restraining it
- ✗Not connecting large weights to output hypersensitivity on nearby inputs
- ✗Assuming any weight reduction helps, ignoring that the goal is a smoother decision function
Follow-up questions
- →What concretely is the symptom of overfitting that the penalty targets?
- →Does shrinking weights increase bias, and is that an acceptable trade?
MiddleTheoryCommonWhat is SGD with momentum, and when does it speed up convergence?
What is SGD with momentum, and when does it speed up convergence?
Momentum keeps an exponentially-weighted sum of recent gradients and steps along it, damping oscillations. It helps most on elongated (ill-conditioned) level curves: the gradient points across the valley, so plain SGD zig-zags, while momentum averages the swing out and moves along the valley.
Common mistakes
- ✗Describing momentum as a fixed direction rather than a decaying running average
- ✗Not naming elongated/ill-conditioned level curves as the case it helps most
- ✗Confusing the oscillation-damping effect with simply raising the learning rate
Follow-up questions
- →Why is the gradient perpendicular to the level curves, and why does that cause zig-zag?
- →How does Adam build on the momentum idea?
SeniorTheoryCommonWhy does L1 regularization produce sparse weights while L2 does not?
Why does L1 regularization produce sparse weights while L2 does not?
Geometrically L1's constraint is a diamond with corners on the axes; the loss level-set usually touches a corner, where a weight is 0. L2's is a circle with no corners. By gradient, L1's |∂R/∂w| is constant so descent reaches 0, while L2's shrinks as w→0 and weights stop short.
Common mistakes
- ✗Swapping the shapes — calling L1 the circle and L2 the diamond
- ✗Explaining only the geometry and missing the constant-vs-shrinking gradient argument
- ✗Claiming L2 also zeroes weights, just more slowly
Follow-up questions
- →At a corner of the diamond, what is true about the loss and penalty gradients?
- →Why is the L1 objective non-differentiable on the axes, and does that block descent?
JuniorTheoryOccasionalIn a support vector machine, what are the margin and support vectors, and what does C control?
In a support vector machine, what are the margin and support vectors, and what does C control?
The margin is the band between the boundary and the nearest points, and training maximizes its width. Support vectors are the points on or violating it — only they define the solution. Large C narrows the margin, small C widens it.
Common mistakes
- ✗Expecting C to cap the number of support vectors: C prices margin violations, and a smaller C widens the band, so more points fall inside it.
- ✗Reading a large C as stronger regularization, as with
alphain Ridge: a large C makes violations expensive, so the margin narrows.
Follow-up questions
- →Why does removing a non-support vector leave the fitted boundary unchanged?
- →Which value of C would you reach for when the training data are noisy?
MiddleDebuggingOccasionalWhy do logistic-regression coefficients blow up on separable data, and what stops it?
Why do logistic-regression coefficients blow up on separable data, and what stops it?
Under perfect separation the maximum-likelihood optimum does not exist — scaling the weights up pushes log-loss toward zero without reaching it, so they diverge and the solver stops only on its iteration cap. A penalty pins a finite solution.
Open full question →Common mistakes
- ✗Raising max_iter and treating the vanished warning as a fix
- ✗Blaming float overflow or feature scale instead of a non-existent optimum
- ✗Assuming perfect training accuracy means the fit is healthy
Follow-up questions
- →Why does raising the iteration cap make the printed coefficients larger, not stabler?
- →Besides a penalty, which other remedy bounds the estimate under separation?
MiddleTheoryOccasionalShould the bias/intercept term be included in the regularizer?
Should the bias/intercept term be included in the regularizer?
No. The intercept only shifts the hyperplane to where the data sits; it is not a weight on a feature. Penalizing it pulls the offset toward zero and stops the model from positioning the hyperplane well, so quality gets worse. By convention the bias is excluded from the penalty.
Common mistakes
- ✗Treating the intercept like any other weight that needs shrinking
- ✗Not realizing the bias positions the hyperplane rather than scaling a feature
- ✗Assuming including w0 is harmless when it usually degrades quality
Follow-up questions
- →What does the bias control geometrically that the feature weights do not?
- →How do libraries typically implement this exclusion in practice?
SeniorTheoryRareWhat is the computational complexity of inverting an n×n matrix?
What is the computational complexity of inverting an n×n matrix?
The standard algorithm (Gauss–Jordan / LU) is cubic, O(n³). Strassen-style multiplication gives about O(n^2.81), and asymptotically faster ones exist but carry huge constants and practical constraints, so they are rare. This cubic cost is why closed-form OLS is avoided.
Common mistakes
- ✗Saying inversion is
O(n²)by counting matrix entries rather than operations - ✗Believing fast algorithms like Strassen are used by default in production libraries
- ✗Confusing the cost of one matrix-vector multiply with the cost of full inversion
Follow-up questions
- →Why aren't sub-cubic algorithms used by default despite the better asymptotics?
- →How does this cost motivate gradient methods for large feature spaces?