Polynomial Features
A straight line cannot describe every relationship between our measurements and the answer. Adding features such as an input squared gives the model more to work with while keeping its coefficients straightforward to fit.
13 sections · 10 questions · 4 coding challenges
The arrow keys move between sections too.
Could a Straight-Line Calculation Describe a Curve?
BOTIE
Least squares soon became a tool for fitting more than straight lines. Gergonne's 1815 work applied it to polynomial interpolation, connecting the selection of a formula with the way observations were taken. The coefficients could still be estimated through linear equations even though the resulting curve was not straight.
The key is to create extra measurements from an existing input: its square, its cube, or other chosen powers. We fit a coefficient for each. The model remains linear in those coefficients, while the prediction can curve as the original input changes. Each extra term buys flexibility, so we also have to check whether it describes a repeatable pattern or just follows noise.
Give a Straight-Line Model Something Curved to Read
A thrown ball rises and then falls. A straight line can rise or fall, but cannot follow both parts of the trajectory. Could another description of time give a simple model more useful shapes to work with?
Polynomial features create additional inputs from measurements we already have.
See the pattern a line misses
These illustrative points rise and then fall. A horizontal or sloping line leaves a systematic pattern of misses. The limitation is the available shape, not merely an unlucky tilt.
Vertical: Height
Horizontal: Time
The new inputs create the shape choices
We will now introduce powers and products as features, then show how a linear model chooses their coefficients. Linear in the coefficients does not require a straight graph in the original measurements.
The full experiments examine useful expansions, their storage cost, and the difference between fitting a sample and predicting new data.
Explore the full example
Compare the generated columns at different degrees. Relate each new power or product to the extra flexibility in the fitted curve.
Hollow rings are the seven people held back from every fit on this page. The curve is drawn only across the measured range, and at a high degree it leaves the frame between the people rather than staying near them.
Part 1. A Straight Line Through a Curved Relationship
1. Twenty-two people, and the shape weight really follows
We have twenty-two people measured three ways, height in centimetres, waist girth in centimetres, and weight in kilograms. The smallest is a child of 104 centimetres weighing 16.1 kilograms and the largest an adult of 191 centimetres weighing 81.3, and everyone in between is arranged along that span. Predicting weight from height is the obvious thing to want, and a straight line is the obvious way to want it.
There is a reason to expect trouble before any fitting happens. A person is roughly a solid of some height and some thickness, and the weight of a solid goes as a length times a girth squared, so weight against height alone should follow something nearer a cube than a line over a range this wide. Set the playground above to degree 1 and the straight line through these people scores 0.9620, which looks like an excellent fit, and it is the number I want to argue with first.
The line, on these twenty-two people
It reaches 0.9620 and leaves 548.33 as the total of its squared misses. Its guess for the 104 centimetre child is 7.80 kilograms, against a measured 16.1, so it is out by more than half the child’s weight at the very first person. At the other end it puts the 191 centimetre adult at 85.43 against a measured 81.3.
Keep in mind
2. The misses are not scattered, they have a shape
The thing worth looking at is what the fit leaves over. Each person’s miss is their measured weight less the weight the fit gives them, and if the fit has the shape right those misses should be scattered without order, some people above and some below with no relation to how tall they are.
Under the straight line they are not scattered. The two youngest people are above the line by 8.30 and 4.05 kilograms, then the six people from 118 to 149 centimetres are all below it, and the tall end climbs back above. That is a bow, and a bow in the misses is the fit telling us that the line is too straight for these people rather than that these people are noisy.
Add the squared column and the longest stretch on one side falls from six people to five, and the child the line put at 7.80 lands at 14.02. Add the cube as well and the longest stretch is three and the child lands at 16.67 against a measured 16.1.
Keep in mind
Part 2. Linear in the Coefficients, Not in the Columns
3. What the word linear was ever about
Here is the sentence the whole page turns on. A linear model is a weighted sum of its columns, and the thing it is linear in is the weights rather than the measurements. Nothing anywhere in the method says that a column has to be something a tape measure produced.
prediction = b₀ + b₁ c₁ + b₂ c₂ + … + b_k c_kRead that with c₁ standing for height and c₂ standing for height multiplied by itself, and the prediction is a quadratic in height while remaining an ordinary weighted sum of two columns. So we may compute the squared column ourselves, before anything is fitted, hand it over as though it were a measurement, and get a curve out of a method that only ever draws flat things.
weight = b₀ + b₁ × height + b₂ × height²Keep in mind
4. One extra column, and the same fit
So we compute one column, height times itself, put it beside height, and fit exactly as before. Nothing in the fitting changes. The same weighted sum is formed, the same squared misses are added up, the same system of equations is solved for the weights, and the only difference is that there are now three numbers to find rather than two.
What the extra column bought
The total of the squared misses falls from 548.33 to 307.18, a drop of 44 percent for one column. Adding the cube as well takes it to 225.56, and the score goes 0.9620, 0.9834, 0.9864. The fit is still a straight-line method throughout; what changed is what it was handed.
It is worth seeing the two fits side by side in the playground at the top. At degree 1 the line cuts through the young people and comes out under the tall ones; at degree 3 it follows the same sweep the people do. The 191 centimetre adult is still missed by 8.44 kilograms at degree three, and that is because he really is light for his height, which is a fact about him and not a shortcoming of the curve.
Keep in mind
5. Where the new columns are fixed
One detail decides whether the expansion is reproducible. Which columns exist, and in what order, has to be settled once, on the people the fit learns from, and then applied unchanged to anybody who arrives later. Otherwise a new person with a slightly different set of measurements would produce a slightly different set of columns, and the weights learned earlier would be multiplying the wrong things.
| the step | what it settles |
|---|---|
| look at the columns supplied | their names and their order, which is the order the terms will be written in. |
| choose the highest total degree | which is a decision made by the modeller and never by the data, as Part 6 argues. |
| list every term up to that degree | one per column to be built, named for the product that produced it, in ascending degree. |
| compute those terms for any later people | the same names in the same order, so a weight learned earlier keeps multiplying the same thing. |
Nothing is learned from the values here, only from the names, which makes this the lightest of the preparation steps here. Even so it is a step that has to be carried with the model, and the pipelines page is where the consequences of forgetting to carry it are measured.
Keep in mind
Part 3. Powers and Products
6. Every power and every product up to a chosen degree
With one measurement the expansion is just its powers. With two it is more than that, because two columns can be multiplied by each other as well as by themselves, and a term is any product of the two whose exponents add up to no more than the degree. At degree two over height and girth there are five such products.
height, girth, height², height × girth, girth²The table below is exactly what the fit is handed, four people and every column built from them, so each entry can be checked against the two numbers that produced it.
| column | built from | 150, 66 | 150, 96 | 180, 66 | 180, 96 |
|---|
The four columns of numbers are four people, written as their height and their girth. Every entry is a product of those two numbers and nothing else, so each one can be checked with a pencil.
One person, all five columns
The person 150 centimetres tall with a girth of 66 contributes 150 and 66 for the two measured columns, 22,500 for the square of the height, 9,900 for the product of the two, and 4,356 for the square of the girth. The person 180 tall with the same girth contributes 180, 66, 32,400, 11,880 and 4,356, so the two agree on the girth-squared column and on nothing else. That is what makes them separate columns.
Keep in mind
7. What a product says that no power can
The powers and the products are usually taught together as though they were the same idea, and they answer quite different questions. A power lets a column’s own effect vary nonlinearly. A product lets one column’s effect depend on another column, and no amount of squaring or cubing will give a fit that ability, since each power still contributes its own fixed amount to the answer.
To see it we need people whose two measurements do not move together, so here are twelve arranged deliberately, four girths at each of three heights. Since every girth appears at every height, knowing one measurement tells us nothing at all about the other.
…
What thirty centimetres of girth is worth
Read it straight off the twelve people. Going from a girth of 66 to a girth of 96 adds 44.50 kilograms at 150 centimetres, 49.30 at 165, and 54.80 at 180, because the same extra girth wraps a longer body. A fit with one coefficient for girth has to answer one number, and it answers 49.45 at all three heights, splitting the difference and being wrong at both ends. Add the product column and the fit answers 44.59, 49.45 and 54.31.
The totals say the same thing more bluntly. On those twelve people the pure powers leave 28.07 as the total of the squared misses and the powers with the products leave 1.83, so one extra column removes 93 percent of what was left, which is the largest reduction in the misses anywhere on this page. The column responsible holds nothing but each person’s height multiplied by their girth.
›Why one coefficient cannot vary
Write out what the fit says about girth in the two cases. In the first, the amount of weight attributed to a unit of girth is b₂, a single number decided once for everybody.
weight = b₀ + b₁ height + b₂ girthIn the second, collect the terms that carry girth and the coefficient of girth turns out to have height inside it.
weight = b₀ + b₁ height + (b₂ + b₃ height) girthThat bracket is the whole of the difference. The fit is still a weighted sum of columns and still linear in what it learns, and yet the effect of girth now moves with height, which is what the twelve people were measured to show.
Keep in mind
8. And what it says on people whose columns move together
That was a group built so the product would have something to say. Press the other button on the same widget and the twenty-two people come back, and there the two measurements agree with each other at 0.9886, since taller people in this crowd are also thicker. The product column earns almost nothing there. The pure powers leave 98.89 and the powers with the products leave 91.03, a gain of eight percent for a column that was worth a factor of fifteen a moment ago.
The reason is worth stating plainly, because it is easy to read the first measurement as a general claim about products. When girth is nearly a fixed multiple of height, the product of the two is nearly a multiple of height squared, and the squared column is already in the expansion. The product has nothing of its own left to say. So whether the cross terms are worth their columns depends on the data rather than on the method, and the quantity that decides it is how much the two columns already agree.
Keep in mind
Check yourself
Questions on Parts 1 to 3
Question 1 of 5
A score of 0.9620 for the straight line is evidence that the shape of the fit is right.
Part 4. What the Expansion Costs
9. The count, by degree and by how much was measured
Everything so far has been what the expansion buys. What it costs is columns, and the count rises faster than most people expect, because it counts the ways of choosing a degree’s worth of factors from the available measurements with repeats allowed.
columns = C(p + d, d) − 1In that, p is how many measurements were taken and d is the degree, and the one that is subtracted is the term where every exponent is zero, which is the constant and belongs to the fit’s intercept rather than to any column. Each cell below is a count read off an expansion that was actually built.
| measurements | degree 2 | degree 3 | degree 4 | degree 5 |
|---|---|---|---|---|
| 2 | 5 | 9 | 14 | 20 |
| 3 | 9 | 19 | 34 | 55 |
| 5 | 20 | 55 | 125 | 251 |
| 10 | 65 | 285 | 1000 | 3002 |
Columns produced, by how many measurements were taken and how high the degree goes.
Keep in mind
10. More columns than there are people
A count of columns turns into a hard limit as soon as it is put beside a count of people. A fit sets one number per column plus the intercept, and it cannot set more numbers than it has people to set them from, so the growth table is also a table of how many people each expansion demands.
Three measurements on twenty-two people
Suppose we had taken a third measurement from these people, their age. At degree three the three measurements make 19 columns, which is 20 numbers and comfortably inside twenty-two people. At degree four they make 34 columns, which is 35 numbers, and twenty-two people cannot pin down 35 numbers. The fit is refused rather than answered, and one step of the degree did it.
This is the practical reason to keep the degree low that has nothing to do with overfitting. Long before the fit becomes untrustworthy it becomes impossible, and on a wide table it becomes impossible at degree two, since ten measurements at degree two already ask for 66 numbers and most tables of ten measurements do not hold 66 rows to spare.
Keep in mind
Part 5. Where the Degree Stops Helping
11. The score on the fitted people can only improve
Suppose there are people enough. Then the degree is a dial that turns freely, and turning it up always improves the fit we can measure on the people we fitted, for a reason that has nothing to do with the data. Every column the higher degree adds is a new one, so the lower degree’s answer is still available to the higher one by setting the new weight to zero. Whatever the fit finds is therefore at least that good.
squared misses at degree d + 1 ≤ squared misses at degree dSo the score on the fitted people cannot fall as the degree rises, whatever the shape of the data, and a number that only ever improves cannot tell us when to stop.
Keep in mind
12. Where the two scores part company
The way to see what the degree is really doing is to keep people back. Seven of the twenty-two are held out of every fit on this page, leaving fifteen to fit on, and both scores are drawn against the degree below. The height column is put on a common scale before it is raised, for reasons Part 6 measures.
The two lines run together and then separate. The score on the fitted people climbs from 0.9620 to 0.9998, quietly and without interruption. The score on the seven held back rises to 0.9762 at degree four, drifts down to 0.9105 by degree nine, jumps back to 0.9785 at ten, and then leaves the picture, reading 0.3641 at degree eleven, −36.35 at twelve and −24,967 at fourteen. A score below zero means the fit is worse than answering everybody with the average weight.
The two ends of the sweep
At degree fourteen the fit has fifteen numbers to set and fifteen people to set them from, so it passes through every person it was shown, which is why its own score reads 0.9998. Between them it swings far enough that the 131 centimetre person, who weighs 27.6 kilograms, is answered −9,002.94, and the 137 centimetre person, who weighs 29.1, is answered −4,030.13. Both readings describe the same curve.
Keep in mind
13. The curve between the people
It helps to look at what the high-degree fit is actually doing, which the playground at the top of the page will draw. Take the degree slider past ten and the curve still passes close to every solid dot, since those are the people it was fitted to, and between them it climbs and dives off the top and bottom of the frame. The hollow rings are the people it was not shown, and they sit where the curve is not.
Nothing about that is a failure of arithmetic. A curve with fifteen numbers to set and fifteen points to pass through has exactly one way to do it, and the shape it takes between the points is not constrained by anything at all. Runge’s 1901 paper is about precisely that freedom, and it grows worse towards the ends of the range rather than better.
Keep in mind
14. A penalty makes a high degree survivable
The wild swings come from very large weights, some strongly positive and some strongly negative, cancelling almost exactly at the people and not at all between them. So the repair is to make large weights expensive, which is what a penalised fit does, and it is the reason the two ideas are usually taught in the same breath.
minimise Σ (miss)² + penalty × Σ b²Turn the penalty slider on the sweep above, or on the playground, and the third line is the same degrees with the weights shrunk. The effect at the top end is not subtle.
| degree | penalty | score, people it saw | score, people it did not |
|---|---|---|---|
| 4 | none | 0.9864 | 0.9762 |
| 4 | 0.1 | 0.9856 | 0.9675 |
| 14 | none | 0.9998 | −24967.20 |
| 14 | 0.001 | 0.9881 | 0.9631 |
| 14 | 0.1 | 0.9862 | 0.8901 |
The same expansions, with and without shrinkage, on the same seven held-back people.
A penalty of one thousandth takes degree fourteen from −24,967.20 to 0.9631, which is a working model built out of a fit that was ruinous a moment earlier. It does not quite reach the 0.9762 that degree four managed without any penalty at all, and the same penalty applied at degree four makes things slightly worse rather than better, 0.9675 against 0.9762. So the shrinkage is insurance. Where the degree was already sensible it costs 0.0087 of the second score, and where it was not it is worth about twenty-five thousand.
Keep in mind
15. Straight cuts need none of this
It would be dishonest to leave the impression that a curved relationship demands an expansion. A fit made of straight cuts on the raw height column can approximate a curved relationship too, by answering one weight for everybody below some height, another for the band above that, and so on, with no squared column anywhere. It approximates the curve with piecewise constant predictions, and the question is which of the two does better on these people.
On these twenty-two the expansion wins, and by a real margin. Its best setting is degree four at 0.9762 on the held-back seven, and the stepped fit’s best is a depth of three at 0.9502. That is what a smooth relationship should look like, since the steps pay for their flat tops on a curve that never stops rising, and each step spends people on deciding where to cut rather than on the shape.
The other column of the comparison goes the other way. The worst the stepped fit does across its depths is 0.6438, at a single cut, and the worst the expansion does across its degrees is −24,967. Both methods have one dial and both can have it set badly, and only one of them can be set badly enough to produce an answer that is thousands of times worse than saying nothing.
The steps also need no decision about scale, which the last Part measures, and they read a column that has not been touched at all.
Keep in mind
Part 6. Where the Expansion Stops Being Defined
16. The degree is a free choice, and nothing in the data makes it
Everything the method needs is supplied by the data except one number, and that one number is the whole of it. The degree is not estimated, not implied by the measurements, and not settled by any quantity computed from them. It is chosen before the fit and the fit then answers the question it was asked.
We could hope that the score on held-back people picks it out, which is the best available procedure and is still not a principle. That score is itself a measurement made on a handful of people and carries their noise, so it can prefer one degree to a neighbour for reasons that have nothing to do with either.
On this page’s seven held-back people it reads 0.9785 at degree ten, the highest reading anywhere in the sweep, and 0.3641 at degree eleven, and no property of the relationship between height and weight changes between those two settings.
What that reading is worth
Degree ten scoring above degree four is a fact about these seven people rather than about the relationship. The reading to take from a curve that jumps from 0.9785 to 0.3641 between neighbouring settings is that the instrument is too coarse to separate the settings, so the honest move is to take the lowest degree whose reading is near the best and treat the rest as noise.
The searching for a setting page is about that whole difficulty and measures how much the winner’s own score flatters it. What belongs here is only that the degree is exactly the kind of dial that page exists for, and that it has no setting a derivation could supply.
Keep in mind
17. The expansion is blind to what a column means
The expansion builds every product up to the degree, and it has no way of knowing what any of the columns are. Multiply a height in centimetres by a girth in centimetres and the result is an area, which is a quantity a person could reason about. Multiply a height by a code that happens to say which of four clinics a person attends, written as 1, 2, 3 and 4, and the result is arithmetic that means nothing whatever.
Both columns are built, both are handed to the fit, and both get a weight.
The table gathers four such cases. Two of them are failures of the mathematics rather than of taste, and they fail in opposite ways, one loudly and one without a sound.
| the case | what the method says |
|---|---|
| a column recorded as 0 or 1 | its square is itself, since 0 × 0 is 0 and 1 × 1 is 1, so the expansion produces the identical column twice. The fit then has two columns saying the same thing and no unique set of weights, since anything added to one can be taken from the other. Probed on eight people with a column recording whether each swims, the squared column comes back equal to the original value by value and the fit has no answer. |
| a column with a code standing for a category | the square and the products are perfectly well defined and mean nothing. Clinic 4 squared is 16 and clinic 2 squared is 4, so the expansion has decided that the gap between clinics 2 and 4 is four times the gap between clinics 1 and 2. Nothing refuses this, because nothing in the arithmetic can tell a code from a measurement. |
| a column that runs both negative and positive | its square folds the two sides together, so −3 and 3 both become 9 and the squared column cannot tell them apart. That is exactly right for a quantity whose effect is symmetric about zero and exactly wrong for one whose sign matters, and the expansion has no way to know which it has. |
| a column that never varies | every power of a constant is another constant, so each new column is a multiple of the fit’s own intercept and adds no direction at all. There is nothing for a weight to be, since the intercept can already produce whatever the constant column would have produced. |
Keep in mind
18. A column carries its unit into every power
The last difficulty is the one that connects back to the scaling pages, and it is much sharper here than it is there. A height of 191 centimetres cubed is 6,967,871, while the height itself is 191, so the two columns handed to the same fit differ in size by a factor of 36,481. Write the same heights in metres and the cube is 6.97 against 1.91, a factor of 3.6481. The people did not change.
Plain least squares does not feel it, and the widget shows why it is tempting to conclude there is no problem. A change of unit multiplies a column by a constant, a coefficient can divide by that same constant, and the fit lands in exactly the same place, 0.984072 in both readings. The moment a penalty is switched on it feels it severely, because the penalty is a statement about the size of the coefficients and the coefficients have just changed size by four orders of magnitude.
At a penalty of 100 the centimetre fit scores 0.977374 and the metre fit 0.703648, from the same people and the same instruction.
And where least squares does feel it
At degree fourteen on fifteen people the fit has one number for every person, so the exactly correct answer is a score of 1. Taken on the heights as measured, the largest number in the columns is 7.42 × 10³¹ and the fit reaches 0.987231, which is not close. Put on a common scale first, the largest number is 5,834 and it reaches 0.999808. Neither is exactly 1, and the gap between them is not a fact about people at all.
The stepped fit from section 15 reads 0.990159 in centimetres and 0.990159 in metres, identical to the last digit, because it only ever asks which side of a threshold a value falls on and a change of unit moves the value and the threshold together. That is a second advantage of the stepped fit, alongside the floor section 15 measured.
Keep in mind
19. Where the method runs out
The limits are worth gathering in one place. Each is a fact about what the expansion and the fit behind it can mean rather than a matter of taste, and they have the same shape as one another, a quantity one of the two steps needs and the data cannot supply.
| the case | what is undefined, or what must be decided |
|---|---|
| the degree itself | undetermined by anything measurable. It is chosen, and the best available procedure is to measure candidates on people held back, whose reading carries its own noise. Here that reading moves from 0.9785 to 0.3641 between neighbouring degrees. |
| more columns than people | there are more numbers to set than equations to set them by, so infinitely many answers fit the people exactly and nothing picks between them. Three measurements at degree four make 34 columns, which is 35 numbers, against 22 people. |
| exactly as many numbers as people | one answer, reached by passing through every person, so in exact arithmetic the misses are zero and say nothing about the fit. It is interpolation rather than estimation. On this page’s fifteen fitted people the score reads 0.9998 while the same curve answers −9,002.94 kilograms for a person who weighs 27.6. |
| fewer distinct values than the degree asks for | a column taking only three distinct heights spans three directions however many powers are built from it, so the fourth and fifth powers are new arithmetic and old information. Probed on ten people at three heights, degrees two, three, four and five all score 0.992417, identically. |
| a column coded 0 and 1 | its square is itself, so two identical columns arrive and the weights are not determined. The pair can be swapped in any proportion without changing a single prediction. |
| a column that never varies | all its powers are constant, so they add no direction the intercept did not already have, and nothing distinguishes one set of weights from another. |
| a person outside the measured range | defined and worthless. A polynomial has no limiting behaviour to appeal to, so beyond the last measurement it follows its highest power off to infinity in one direction or the other, and the degree decides which. The fit reports nothing to say it has left the range it was taught on. |
| columns on wildly different scales | least squares is untouched, and any statement about the size of the coefficients is not, because the coefficients change size with the units. The same shrinkage instruction produced 0.977374 and 0.703648 on the same people written two ways. |
Keep in mind
Check yourself
Questions on Parts 4 to 6
Question 1 of 5
Three measurements at degree four make 34 columns. Why can the twenty-two people not be fitted?
Try it with Botie
Build with Botie
Write and run Python