E ExamMaster

Machine Learning · Machine Learning Core

Linearity Assumptions

Logistic regression as the classification baseline after a continuous line — assumptions, the sigmoid map, and a tiny sklearn lab. Regularisation now lives in its own topic.

With a continuous line behind you, turn to class probabilities: a linear score passed through a sigmoid, the assumptions that break additivity, and a tiny logistic baseline you can re-run in the browser. Weight penalties are covered next, in Regularisation.

  • Machine Learning
  • Medium level
  • 7 concepts
  • 10 practice questions

1What linearity assumes

Picture a model that predicts a flat's monthly rent from two facts about it: how many bedrooms it has, and which floor it sits on. A linear model makes that prediction the simplest way imaginable — it starts from a base amount and then adds a fixed amount for each unit of each feature. Something like: rent = ₹20,000 base, plus ₹3,000 for every bedroom, plus ₹500 for every floor you go up. Those fixed per-unit amounts (the ₹3,000 and the ₹500) are called the model's coefficients, or slopes — one number per feature, and that number is the whole of what the model believes about that feature.

Hidden inside that recipe is a strong promise called additivity: each feature adds its own fixed amount regardless of what the other features are doing. Under this promise, an extra bedroom is worth exactly ₹3,000 whether the flat is on the ground floor or the twentieth. The features never talk to each other — the model just sums their separate contributions. That is what "linear" is really assuming, and it is a claim about the world that can simply be false.

Real rents break the promise all the time. Suppose an extra bedroom is worth little on the ground floor but a lot on a high floor, because spacious high flats are penthouses with a premium. Now the effect of bedrooms depends on floor — the two features combine, and that combined effect is called an interaction. Here is the part beginners miss: a plain linear model can never discover an interaction on its own, no matter how much data you give it. It only has one slope per column you handed it, so if no column represents "bedrooms and floor together", the penthouse premium has nowhere to live. (The next concept in this topic shows the fix: you create that column yourself.)

Figure. The whole model is one sum: a ₹20,000 base, plus ₹3,000 for every bedroom, plus ₹500 for every floor, each flowing in on its own arrow. That per-unit amount is the feature's coefficient, and additivity is the missing arrow: nothing connects bedrooms to floor, so each contributes its fixed amount no matter what the other is doing.

What core assumption does a linear model y = w1*x1 + w2*x2 + b make about feature contributions?
  1. All features must follow a standard normal distribution with mean zero
  2. Input features must be strictly non-negative integers
  3. Each feature contributes additively and with a constant per-unit effect regardless of other feature values
  4. The target variable must be bounded between 0 and 1

Linearity assumes that changing x1 by 1 unit changes y by w1, regardless of the current level of x1 or what value x2 takes.

2Traps, and the residuals that catch them

A second way the story goes wrong is outliers — individual rows whose values are wildly off the trend, often from a typo or a data-entry slip. The standard way of fitting the line, called least squares, picks the line that minimises the sum of squared misses: for each row it measures how far the prediction landed from the truth, squares that miss, and adds them all up. Squaring is the trap. A miss of 2 costs 4, but a miss of 20 costs 400 — a hundred times more. So one absurd row can dominate the total cost, and the fit will tilt the whole line toward that row just to shrink its enormous squared miss, distorting predictions for the many rows that were fine.

The third trap is collinearity: two feature columns that are near-duplicates of each other, like income in rupees and the same income in thousands. The data pins down their combined effect perfectly well, but it has no way to decide how to split the credit between the two — every split gives the same predictions. So the two coefficients can wander to enormous values with opposite signs, cancelling each other out. Predictions still look fine; it is the story "which feature mattered, and by how much" that has become meaningless. Whenever coefficients look absurd but accuracy looks normal, suspect near-duplicate columns.

How do you catch these failures in practice? Look at the residuals. A residual is just actual value minus predicted value, computed for each row — the amount the model missed by, positive when it underpredicted and negative when it overpredicted. The figure below plots each row's residual (vertical axis) against its fitted value, meaning the model's own prediction ŷ for that row (horizontal axis). If the linear story is honest, the misses are just random noise: a flat, patternless cloud hugging the zero line. A U-shaped bend means the straight line missed a curve in the data; a fan that widens to one side means the errors grow with the prediction. Any visible pattern is the residuals telling you the additive fixed-slope story is lying somewhere.

Figure. After a fit, plot residual against fitted value on a zero line through the middle. A healthy cloud is a flat random band around zero — no slope, no smile, no megaphone. A U or smile means the line missed a curve; a widening fan means variance grows with the prediction. Both say the additive constant-slope story is lying somewhere, even when predictions look mostly fine.

Assumption checks
AssumptionWhen it fails
Additive effectsTrue interaction not in the columns
Stable slopesOutliers dominate the squared loss
Independent columnsTwo features are near-duplicates

Five residuals, one hidden curve

Five flats from the rent spreadsheet, with one to five bedrooms. Their actual monthly rents, in thousands of rupees, are 23, 28, 35, 44 and 55. Least squares fits the line \hat{y} = 13 + 8 \cdot \text{bed}, where \hat{y} is the predicted rent in thousands and bed is the bedroom count. Compute every residual and say what the pattern tells you about the fit.

  • First get the model's own prediction \hat{y} for each flat by plugging its bedroom count into the line: 13 + 8 \cdot 1, 13 + 8 \cdot 2, 13 + 8 \cdot 3, 13 + 8 \cdot 4, 13 + 8 \cdot 521, 29, 37, 45, 53 — all in thousands of rupees
  • A residual is actual minus predicted — the amount the model missed by, positive when it underpredicted the rent and negative when it overpredicted. Subtract, flat by flat: 23 - 21, 28 - 29, 35 - 37, 44 - 45, 55 - 53+2, -1, -2, -1, +2
  • Read the five misses in bedroom order: positive at both ends, negative through the middle — the U shape from the residual plot. (Plotting against the fitted value \hat{y} instead gives the same order, because \hat{y} rises with bedrooms)a U shape, not a flat random cloud
  • The U says the straight line missed a curve. Look at the actual rents: each extra bedroom adds 5, then 7, then 9, then 11 thousand — the per-bedroom jump keeps growing, but a line can only charge one fixed slope, so it overshoots the middle flats and undershoots both ends. The fix is the topic's usual one, and the model stays linear in its parametersadd a \text{bed}^2 column and re-fit

Pro tip. These residuals sum to zero (2 - 1 - 2 - 1 + 2 = 0), and least squares guarantees that on every fit, honest or broken. Never read the total — the lie shows only in the ordered pattern of signs.

Two features are near duplicates. Predictions look fine, but their two coefficients are enormous and opposite in sign. What is going on?
  1. The model has overfitted, so the predictions are wrong too
  2. The features need scaling before the model is fitted
  3. The target column has been mislabelled
  4. The pair pins down their combined effect while leaving the split between them unidentified, so the individual numbers wander

When two columns move together the data cannot separate their contributions. Predictions stay stable because the pair cancels; the coefficients are the part you must not read.

3First, a linear score

So far the model predicted a number that can be anything — a rent of ₹26,000, say. Now change the question: is this email spam, yes or no? There is no amount to predict, only two classes, and what you actually want is a probability — a number between 0 and 1 that says how confident the model is that the answer is yes. Logistic regression is the standard first tool for this, and the surprise is how little it changes: it keeps the entire linear machinery and bolts one small squashing function onto the end.

The linear part first, symbol by symbol. The model computes a score z = w \cdot x + b. Here x is the row's features — for the spam question, things like how many links the email contains and how many times it says "free". w is the weights, one number per feature, exactly like the rent slopes: each weight says how strongly its feature pushes the verdict toward spam (positive weight) or away from it (negative weight). b is the bias, a starting score before any feature is looked at. And z, the result of the weighted sum, is the raw score. It can be any real number — 3.7, or −12 — which is the problem, because a probability must live between 0 and 1.

Figure. Exactly the rent machinery, pointed at spam: each feature is multiplied by its own weight and summed with the bias b to give the raw score z. Positive weights push the verdict toward spam, negative ones away. The catch sits in the last node: z can be any real number — 3.7, or −12 — and a probability must live between 0 and 1.

Reading z = w·x + b
SymbolWhat it isIn the spam example
xThe row's featuresLinks in the email, count of "free"
wWeights — one number per feature, like the rent slopesPositive pushes the verdict toward spam, negative away
bBias — a starting scoreCounted before any feature is looked at
zThe raw score the weighted sum producesAny real number — 3.7, or −12 — not yet a probability
In logistic regression, what is computed before applying the sigmoid activation function?
  1. A non-linear decision tree splitting threshold
  2. A standard linear combination score z = w^T * x + b
  3. A Euclidean distance matrix to all training cluster centroids
  4. An inverse Fourier transform of the feature matrix

Logistic regression first calculates a linear score z = w1*x1 + ... + b representing the log-odds, which is then mapped through the sigmoid function.

4The squash and its landmarks

The fix is the sigmoid function: \sigma(z) = 1/(1+e^{-z}), where e \approx 2.718 is the mathematical constant. You do not need to memorise why this formula, only what it does: it takes any real score and squashes it into the range between 0 and 1, so the output can honestly be read as "the probability that this email is spam". Feed in a huge positive score and e^{-z} shrinks toward zero, so the output creeps toward 1. Feed in a huge negative score and e^{-z} blows up, so the output creeps toward 0. The output never quite touches 0 or 1 — the model never claims absolute certainty.

Three landmark values anchor your intuition. At z = 0 — the features push neither way — the sigmoid gives exactly 0.5: a coin flip. At z = 2 it gives about 0.88; at z = -2, about 0.12. Notice the curve is steep near zero and nearly flat far from it: moving the score from 0 to 2 changes the probability a lot, while moving from 8 to 10 barely changes it, because the curve has already saturated near 1. Extra evidence matters most when the model is still unsure.

Figure. Adapted from undergrad_ml ml_linear_models/logreg. The linear score z = w·x + b is still a weighted sum; the sigmoid only squashes it into (0, 1). At z = 0 the probability is exactly 0.5 — the usual decision cut — and far from zero the curve saturates so ever-larger |z| barely moves p. Order of scores is preserved because the map is monotonic.

Sigmoid landmarks
Score zP(y=1)
-2≈ 0.12
00.50
2≈ 0.88
For the standard sigmoid function sigma(z) = 1 / (1 + e^-z), what is the output value when the linear score z = 0?
  1. 0.5, representing equal odds between the two binary classes
  2. 0.0, indicating complete certainty of the negative class
  3. 1.0, indicating complete certainty of the positive class
  4. -1.0, representing negative correlation with the target

When z = 0, e^-0 = 1, so sigma(0) = 1 / (1 + 1) = 0.5, the neutral boundary between classes.

5The boundary stays straight

Here is the point beginners trip on. The sigmoid's graph is a curved S-shape, so it feels like the model's dividing line between "spam" and "not spam" must be curved too. It is not. The usual rule is: predict spam when the probability exceeds 0.5, and the probability is exactly 0.5 precisely when z = 0. So the dividing line — called the decision boundary — is the set of feature values where w \cdot x + b = 0, and that is a linear equation: a straight line with two features, a flat plane with three. The S-curve lives in the graph of probability against score; the boundary lives in feature space, and it stays straight.

One last useful property: the sigmoid is monotonic, meaning a bigger score always produces a bigger probability, with no exceptions. So if one email scores z = 3 and another scores z = 1, the first is guaranteed to get the higher spam probability. When all you need is a ranking — say, sorting emails from most to least suspicious — the raw scores z already carry the full ordering, and the sigmoid changes none of it.

Plot the spam boundary from the weights

Suppose the fitted spam model lands on weight 0.5 per link, weight 1.0 per occurrence of "free", and bias b = -3, so an email's score is z = 0.5 \cdot \text{links} + 1.0 \cdot \text{free} - 3 — where links counts the links in the email and free counts how many times the word "free" appears. Find the decision boundary: every combination of the two counts where the spam probability is exactly 0.5. Then place two emails against it.

  • The probability is exactly 0.5 precisely when the score is zero, so the boundary is the equation 0.5 \cdot \text{links} + 1.0 \cdot \text{free} - 3 = 0a condition on the two counts
  • Solve it for the free count: \text{free} = 3 - 0.5 \cdot \text{links}the boundary as a line
  • Walk the line: links = 0, 2, 4, 6 gives free = 3, 2, 1, 0 — every 2 extra links lowers the tipping count of "free" by exactly 1, the same drop everywherea straight line, no bend anywhere
  • Email with 2 links and 3 "free": z = 0.5 \times 2 + 1.0 \times 3 - 3 = 1 + 3 - 3z = 1 — positive, so p > 0.5: spam side
  • Email with 2 links and 1 "free": z = 1 + 1 - 3z = -1 — negative, so p < 0.5: not-spam side

Pro tip. No e and no sigmoid appeared anywhere in this computation. The sign of z alone decides which side of 0.5 an email falls on, because the sigmoid is monotonic and crosses 0.5 exactly at z = 0 — the S-curve only decides how far from 0.5 the probability sits, never where the border runs.

The sigmoid's output curve is S-shaped, so a classmate says the logistic decision boundary in feature space must be curved too. What is true?
  1. They are right — a curved output implies a curved boundary
  2. The boundary sits where z = 0, and z is linear in the features, so the boundary is still a straight line
  3. The boundary shape depends on the threshold you pick
  4. There is no boundary, because the output is a probability

The sigmoid curves probability against z, not the feature space. All rows with z = 0 get probability 0.5, and that set is a line (or plane) in the features.

6Fixing broken additivity

Back to the rent model with the penthouse problem. The first concept showed the symptom: additivity — the promise that each feature adds a fixed amount on its own — is false, because an extra bedroom is worth more on a high floor than on the ground floor. You can see it in the residuals, the per-row misses (actual rent minus predicted rent): instead of scattering randomly, they cluster by combination — the model consistently underpredicts flats that are both large and high, and the misses line up with that specific pairing of features. That clustering is the diagnosis. Now the fix, and it is far less drastic than beginners expect.

The fix is: build the missing column yourself. Take each row, multiply its bedrooms value by its floor value, and store the result as a brand-new feature column — for a 3-bedroom flat on floor 10, the new column holds 30. This is called an interaction term (or product column). Then re-fit the same linear model with three feature columns instead of two: bedrooms, floor, and bedrooms × floor. The model gives the new column its own slope, just like any other column, and that slope is exactly where the penthouse premium can now live — the new column is large only when both bedrooms and floor are large, which is precisely the situation the old model could not express.

Figure. Additivity keeps a fixed bedroom slope at every floor: the dashed high-floor line stays parallel to ground. A bed-times-floor product is still one linear column, but it tilts the high-floor prediction so the lines fan — the penthouse premium the plain additive fit cannot invent.

The penthouse miss, and the column that fixes it
FlatAdditive fit predictsActual rentNew bed × floor column
2-bed, ground floor₹20,000 + ₹6,000 + ₹0 = ₹26,000₹22,000 — close2 × 0 = 0
2-bed, floor 10₹20,000 + ₹6,000 + ₹5,000 = ₹31,000₹35,000 — underpredicted2 × 10 = 20
3-bed, floor 10₹20,000 + ₹9,000 + ₹5,000 = ₹34,000Underpredicted worst — both large and high3 × 10 = 30 — large only when both are
How can a linear regression model capture a synergy where the effect of advertising depends on discount depth?
  1. By running Ordinary Least Squares with negative regularization strength
  2. By explicitly authoring an interaction feature multiplying advertising budget by discount rate
  3. By sorting the rows of the dataset in ascending order before fitting
  4. By removing all bias terms from the linear equation

Adding interaction features like x_ad * x_discount allows a linear model to capture multiplicative synergies while remaining linear in parameters.

7Still linear, and still overfittable

"But wait — isn't the model no longer linear if it contains a multiplication?" This is the subtlety worth slowing down for. "Linear" in linear model means linear in the parameters: the prediction is still a plain weighted sum of columns — (slope₁ × column 1) + (slope₂ × column 2) + (slope₃ × column 3) + base. The model neither knows nor cares that you built column 3 by multiplying two others; to the fitting procedure it is just one more column of numbers to assign one slope to. All the cheap, reliable machinery of linear fitting still applies. What changed is the vocabulary of columns you offered — and that part is your job, not the algorithm's. A linear model never invents a product feature; it happily fits one you author.

One warning before you go inventing columns freely. Every column you add is another dial the model can turn, and with enough dials a model can memorise the accidental quirks of your training data instead of learning the real pattern — that failure is called overfitting. The guard is to check the new column against data the model never trained on (a held-out validation set): if the interaction cuts error on the training rows but the validation error barely moves, the new column is memorising noise, not capturing a real premium. Techniques that deliberately restrain weights — regularisation — apply to interaction slopes like any others; they get a full treatment in the next topic. The steps strip below turns this into a routine: spot the residual cluster, author the column, verify it earns its keep on validation.

  1. Step 1Plot residuals vs each feature and vs plausible products (bed×floor, income×debt).
  2. Step 2Add the interaction or bucket column on train only; re-fit and compare validation error.
  3. Step 3If the new term barely moves validation but train jumps, you overfit — try stronger penalty or more data.

The penthouse premium, still a weighted sum

The additive rent fit — ₹20,000 base plus ₹3,000 per bedroom plus ₹500 per floor — predicted ₹26,000 for a 2-bed ground-floor flat that actually rents at ₹22,000, and ₹31,000 for a 2-bed tenth-floor flat that actually rents at ₹35,000. Author the missing column — bed × floor — and re-fit with three feature columns. Suppose the re-fit lands on base ₹18,000, slope ₹2,000 per bedroom, ₹100 per floor, and ₹600 per unit of the new bed × floor column. Compute the new predictions exactly the way the model does: build the column's value first, then take one plain weighted sum.

  • Build the new column for each flat — it is just a number in a new cell: 2-bed ground floor gives 2 \times 0 = 0; 2-bed tenth floor gives 2 \times 10 = 20column values 0 and 20
  • Predict the ground-floor flat as a plain weighted sum of three columns: 18000 + 2000 \times 2 + 100 \times 0 + 600 \times 0 = 18000 + 4000₹22,000 — matches the actual rent (the additive fit said ₹26,000)
  • Predict the tenth-floor flat the same way: 18000 + 2000 \times 2 + 100 \times 10 + 600 \times 20 = 18000 + 4000 + 1000 + 12000₹35,000 — matches the actual rent (the additive fit missed by ₹4,000)
  • Where the premium lives: the interaction column contributes 600 \times 20 = 12000 on the high flat and 600 \times 0 = 0 on the ground flat — large only when both features are₹12,000 vs ₹0
  • Linear-in-parameters check on a 3-bed tenth-floor flat: its column is 3 \times 10 = 30, and the same slope-times-column sum gives 18000 + 6000 + 1000 + 18000 — the fitting machinery never needed to know column 3 was built by a multiplication₹43,000

Pro tip. Every slope moved in the re-fit — base ₹20,000 → ₹18,000, bedroom ₹3,000 → ₹2,000, floor ₹500 → ₹100 — because the new column absorbed credit the old columns had been forced to carry. Never bolt an interaction term onto a fit's old coefficients; re-fit and let all of them settle.

Residuals cluster by bedroom-and-floor combinations, and a classmate concludes linear models simply cannot capture interactions. What is the actual fix?
  1. Switch to a neural network — interactions are beyond linear models
  2. Remove one of the two interacting features
  3. Add the product column (bed × floor) yourself — it gets its own slope and the model stays linear in parameters
  4. Raise the regularisation strength until the clusters disappear

A linear model never invents product features, but it happily fits one you author as a column. bed × floor is one extra column with its own slope, still linear in parameters.

Notes

  • Logistic regression with a runnable sklearn lab.
  • Logistic regression still computes a linear score z = w·x + b, then maps it through a sigmoid to a probability between 0 and 1.
  • Regularisation (L1/L2 and the C knob) is taught in the following topic.

Exam traps & shortcuts

  • Keep lab datasets under 2000 rows in the browser runtime.
  • Split train and test before fitting any model that sees labels.

Recap

This lesson in brief:

What linearity assumes
The core claim is additivity: each feature contributes a fixed slope, and interactions only appear if you invent them as columns.
Logistic regression
Logistic regression still computes a linear score z = w·x + b, then maps it through a sigmoid to a probability between 0 and 1.

Practise Linearity Assumptions

Reading is free and needs no account. Practice, mocks and progress live in the app.

  • 10 exam-style questions on this topic, with explanations
  • A 5-question practice set that ends the chapter
  • Timed mocks scored with the real marking scheme
  • Readiness tracked per topic, kept on your device
Continue with Google — freeNo card, no trial. Works offline once installed.