← Part of Lysen · lysen.org
Lysen ML
← All algorithms Shared · all of supervised learning

Bias and variance

The problem it solves: every chapter on this site ends with a dial. k in K-nearest neighbours, the depth of a tree, the penalty on a regression. They look like four unrelated settings and they are not. They are the same dial, and this page is what it does. Turn it one way and the model is too simple to be right. Turn it the other and it is too eager, and learns the noise along with the pattern. There is no setting where both problems go away, which is why it is a trade rather than a bug.

What to read first: any one chapter. This page names k, depth and lambda and assumes you have turned at least one of them and seen a score get worse. If you have read K-nearest neighbours, §3a there is this whole page compressed into a single integer, and module 4 comes back to it.

Turns up as choosing kpruning a treehow much penaltyhow many featureswhen to stop trainingwhether more data would help

Running example for the whole page: two solar panels on a roof, logging what they make across the day. There is a true curve, the output the panels are physically capable of at each moment, which rises through the morning, peaks a little after one, and falls away. Nobody can see it. What the logger records is that curve plus whatever the weather did, because a cloud passing at half past eleven takes a bite out of the reading and no model that has ever been written can predict a cloud. Fifty readings a day, and the noise is about 55 W on a peak of around 810 W.

Why this example and not a real one: everything on this page needs the true curve, and on real data you never have it. Here it is generated, so the page can do the one thing a textbook can only assert: measure bias and variance directly, by fitting the same model to forty different days and looking at where the answers land. Module 2c is about what you do instead when the truth is not available, which is always.

01

Intuition: fit it again on a different day

Here is the move that makes the whole subject visible, and almost nobody does it, because in real life you only get one dataset and you fit your model once.

Fit it forty times. Forty different days, fifty readings each, same panels, same true curve, different clouds. Then draw all forty fitted curves on top of one another and look at what the model did.

1a Forty days, forty curves

the true curve, which nobody can see the forty fitted models their average one day's readings
…how far the average sits from the truth …how far the forty sit from each other
…

The slider is polynomial degree, the simplest flexibility knob there is: 1 is a straight line, 2 a single curve, 9 a curve that can change its mind nine times across the day. Module 4 shows that k, depth and lambda all behave exactly like this one.

Walk the slider from 1 to 9 slowly and watch the two failures arrive one after the other.

  • At 1, all forty curves sit on top of each other. Change the day, change the clouds, change every single reading, and you get back more or less the same straight line. The model is completely stable and completely wrong: it is a line, the truth is a hump, and no amount of data will ever make a line into a hump. That is bias. It is the error you would still have if you had infinite data.
  • At 9, the forty curves are all over the plot. Each one chases its own day's clouds, so no two agree, and most of them are doing something ridiculous in the early morning where the readings happen to be thin. On average they are about right, which is the frustrating part. Individually they are anything at all. That is variance. It is how much the answer depends on which day you happened to get.

You only ever get one of those forty curves. You do not get to see the spread, and nothing in the output tells you it exists.

1b One moment, forty answers

Pick a single moment in the day and ask all forty models what the panels are making. Forty numbers come back. Lay them on a line next to the truth and the two errors stop being metaphors.

Drag along the plot to move the moment. The slider above still controls how flexible the models are.

bias…
spread…
…

Bias is the gap between the truth and the middle of the cluster. Variance is the width of the cluster. They are separate quantities and a model can be bad at either one without being bad at the other, which is the entire reason they get separate names. Both bars are drawn against the same 320 W scale, so their lengths are comparable.

Set the model to degree 1 and drag through the day. The cluster stays tight and marches a long way from the truth, badly wrong in different directions at different hours. Set it to 9 and the cluster balloons, especially near the ends of the day where the readings run out. Somewhere in between there is a setting where the cluster is both near the truth and not too wide, and finding it is the whole job.

CuriousCould you just use the average of the forty?

You have probably already noticed that the amber average curve is better than almost every individual curve it is made of, especially at high degree. That is not a trick of the drawing. Averaging leaves the bias exactly where it was and divides the variance by roughly the number of models, so if variance is your problem, averaging is close to a free fix.

And yes, you can actually do it. You do not have forty days, but you can fake them by resampling the one day you have, fitting a model to each resample, and averaging the results. That is bagging, and a random forest is bagging applied to decision trees, with an extra twist that makes the individual trees disagree more so the averaging has more to work with. The tree chapter builds one at the end, and you can watch the averaging happen.

Which explains something that looks strange from the outside. A single deep tree is one of the highest-variance models in common use, and a forest of five hundred deep trees is one of the most reliable. Nothing was done about the bias. Five hundred noisy answers were averaged, and the noise mostly cancelled.

The price is the one named on the comparison page: you can read a single tree and you cannot read five hundred.

02

Where the error actually comes from

Take the squared error of a model, averaged over every day it could have been fitted on, and it splits into exactly three pieces. This is not a rule of thumb. It is an identity, and it is the reason the two words get used together.

expected error = bias² + variance + noise // and nothing else
  • Bias² is how far the average model is from the truth. Being too simple to represent the shape.
  • Variance is how far the individual models are from their own average. Being too sensitive to which day you got.
  • Noise is the cloud. It belongs to the world rather than to the model, no model can touch it, and it does not move when you turn the dial.

2a The three pieces, measured

Because the truth is known here, all three can be computed rather than argued about. The chart stacks them, so the height of the whole stack is the error you would actually get.

bias² variance noise, the cloud
…bias², at this setting …variance …noise, always
…

Degree 1 runs off the top of the chart. Its bias² is roughly … times the whole stack at the best setting, and drawing it to scale would flatten everything else into a line. That it does not fit is the point.

Read it left to right and the handover is obvious. On the left the stack is nearly all coral: the model is wrong in a way that has nothing to do with luck. Coral collapses fast, the total comes down with it, and for a few settings in the middle the stack is almost all noise, which is as good as it gets. Then violet starts climbing and the total goes back up, this time for the opposite reason.

The grey band never moves. That is the part of this problem that is not about modelling at all. Fifty-five watts of cloud is in the data whatever you fit, and a model that reports an error below it on held-out readings has not beaten the weather, it has made a mistake somewhere in how it was scored.

2b The floor, and what it means to be near it

The best achievable error here is the noise on its own. In the units the panels are measured in, that is about … W of typical miss, forever, on the best model anybody will ever fit to this data. At the best setting on the chart the model gets to about … W.

That gap, the small difference between the floor and the best you managed, is the total of bias and variance you did not remove. It is the only part worth working on, and knowing how big it is stops you spending three weeks chasing an improvement that was never available.

Most people have never worked out their noise floor and have no idea whether they are three points away from it or thirty.

CuriousWhy is bias squared but variance is not?

Because they are already the same kind of thing, and writing it the other way would double-count.

Bias is a distance: the average prediction is 180 W below the truth. Squaring it turns a distance into an area, which is what has to happen for it to be added to an error that is itself squared. Variance is already an average of squared distances by definition, so it arrives pre-squared and needs nothing done to it.

If the notation annoys you, the honest fix is to take the square root of the whole sum at the end, which puts everything back into watts. That is exactly what RMSE is, and it is why the rest of this page quotes errors in watts rather than in watts squared. The identity only holds before the square root, which is the one inconvenient fact about it: you cannot add up three RMSEs and get the total.

CuriousCan you measure any of this on real data?

No, and this is the most important sentence on the page.

Splitting the error into bias and variance needs two things you will never have outside a simulation. It needs the true curve, to measure bias against, and if you had that you would not be fitting a model. And it needs many independent datasets, to measure variance across, and if you had those you would have concatenated them and used the lot.

So bias and variance are not a diagnostic. They are a vocabulary: a way of naming the two ways a model can be wrong, so that when you see a symptom you know which of the two it points at, and therefore which fixes are even worth trying.

What you can measure is the gap between training error and held-out error, which is a shadow of variance, and the height of the held-out error, which is a shadow of bias plus the noise floor. Two numbers you can get from any dataset in about a minute. Module 3 is entirely about reading them, and every practical instinct on this page comes from that pair rather than from the identity above.

03

Reading the gap, which is the part you can actually do

Two numbers, available on any dataset. Training error, scored on the readings the model was fitted to. Held-out error, scored on readings it has never seen. Everything practical about this page comes from looking at the two together, and almost nothing comes from looking at either one alone.

3a The two curves against flexibility

training error held-out error the gap the noise floor
…training error, W …held-out error, W …the gap
…

This slider and the one in module 1 are the same dial: move either and every chart on this page follows, so you can scroll up and see what the forty curves looked like at any setting here.

Three readings, and between them they cover almost every situation you will meet.

  • Both errors high, and close together. The model is not even fitting the data it was given. It is too simple, and the honest description is that it has not learned yet. Underfitting. More data will not help, because the model is already failing on data it can see.
  • Training error low, held-out error much higher. The model has fitted the clouds. It looks superb on the readings it memorised and falls apart on new ones. Overfitting, and the width of the gap is your best available look at variance.
  • Both errors low, and close to the floor. Stop. You are done, and the remaining error is weather.

The trap is quoting only the first number. Training error falls forever as you add flexibility, all the way to zero if you let it, so it can be driven to any value you like and it measures nothing except how hard you tried. On its own it is not a weak signal, it is an anti-signal: the lower it goes without the held-out number following, the worse things are getting.

3b The diagnostic that tells you what to do next

The chart above needs you to refit at every setting. There is a second chart that answers a different and more useful question, and it is the single most valuable thing on this page: hold the model fixed and vary how much data it gets. These are learning curves, and they tell you whether more data would help before you go and collect it.

training error held-out error the noise floor
…where the two curves settle …held-out minus training, at 700
…

Both curves flat and high, sitting together. Bias. Collecting more data is money spent on nothing, and the model has to change instead. The gap can even come out slightly negative here, which is not a bug: a model this wrong misses the readings it was fitted to by about as much as it misses new ones.

A gap that is still closing as you go right. Variance. More data is genuinely the fix, and the curve tells you roughly how much more before it stops paying.

This is the chart to draw before anybody is asked to go and label another ten thousand rows. It costs one afternoon, it uses data you already have, and it answers a question that otherwise gets settled by whoever is most confident in the meeting.

CuriousWhy does training error keep falling, even when the model is getting worse?

Because the model is being scored on the answer sheet it was fitted to, and every extra degree of freedom is another chance to bend towards a point it has already seen.

Take it to the extreme and it stops being mysterious. Give a polynomial as many coefficients as there are readings and it will pass exactly through every single one of them, training error zero, a perfect score. It has not learned anything about sunlight. It has memorised fifty numbers, including the cloud at half past eleven, and it will say something absurd about any moment in between.

K-nearest neighbours does the same thing more honestly at k = 1, where the nearest reading to a stored reading is itself and the training error is exactly zero by construction. KNN §3a has that as a live demonstration, and it is the cleanest example on the site of a perfect score meaning nothing at all.

04

The same dial, in every chapter

Everything so far used polynomial degree, because it is the easiest flexibility knob to picture. Now the payoff. Here are four completely different models on the same solar readings, each with its own knob, each fitted live. They have nothing mechanically in common. A polynomial is a weighted sum, KNN stores rows and averages the nearest ones, a tree cuts the day into blocks, ridge is a polynomial with a penalty bolted on.

Look at the four charts before you read another word.

Polynomial degreemore flexible to the right →
KNN: k← more flexible to the left
Tree: maximum depthmore flexible to the right →
Ridge: penalty λ← more flexible to the left
training error held-out error the best setting on each the noise floor
Four models, four knobs, one shape. In every panel the blue line walks steadily downhill as the model is allowed more freedom, and in every panel the teal line comes down and bottoms out. Three of the four then climb back up. The tree flattens instead, and for an honest reason: on fifty readings it runs out of points to split before it runs out of depth, so past its best setting the extra depth buys nothing and costs nothing. The best settings land at ….

Two of those dials run backwards, and this is the most common way people get confused about the whole subject. Degree and depth measure flexibility directly: bigger is more flexible. k and lambda measure restraint: bigger is simpler. A large k averages over half the day, and a large penalty crushes the coefficients towards zero. So the U in those two panels is mirrored, and "turn it up" means opposite things depending on which chapter you happen to be reading.

Worth naming the underlying quantity, since the knobs are all proxies for it. What actually varies is how many genuinely independent things the model is able to say. A degree-9 polynomial has ten coefficients. A KNN regressor with 50 readings and k = 2 has about 25 independent local averages. A depth-6 tree has up to 64 leaves, each free to take its own value. Flexibility is roughly a count of the answers a model can give, and every knob on this page is a way of setting that count.

Which is also why the evaluation page's step 6 turned out to be about the same quantity from a different direction. There, counting the distinct probabilities a classifier can emit told you the resolution of its ROC curve. Here, counting the distinct things a regressor can say tells you where it sits on this U. Same count, two consequences.

Chapter

KNN, §3a

k = 1 scores a perfect 100 percent on the data it stored, and worse on unseen fruit than any larger k short of the extreme. The gap between those two numbers is this page's variance, in one integer.

Chapter

Linear regression, §4b

Lambda, the penalty. Slide it up and the model stops chasing its own tail. That is variance being bought down at the cost of bias, priced explicitly.

Chapter

Logistic regression, §4c

Perfect separation sends the weights to infinity. An unbounded model with nothing holding it back is the far right of this chart with the axis removed.

Chapter

Evaluation, step 6

A tree grown until its leaves are pure. Every leaf is a memorised block, which is why its probabilities collapse and its ROC curve does too.

CuriousThen why do enormous neural networks work at all?

A fair question, and the U above genuinely does not describe them. A modern network can have more parameters than there are examples in its training set, which is the far right of every chart on this page, and by the argument so far it should be useless. It is not.

What people find when they keep pushing right is double descent. Held-out error rises exactly as promised, peaks around the point where the model has just enough capacity to fit the training data perfectly, and then, as capacity keeps growing past that point, falls again, sometimes below the first dip. The classic U is real and it is the first half of a wider curve nobody drew until recently.

The rough explanation is that once a model can interpolate the training data in many different ways, the fitting procedure gets to choose among them, and gradient descent has a quiet preference for the smoothest of those solutions. The capacity stops being spent on contortion and starts being spent on having somewhere gentle to land. That preference is itself a form of restraint, so it is not that regularisation stopped mattering, it is that it moved out of the penalty term and into the optimiser.

Two things this does not change. The noise floor is still the floor. And on the small tabular data every chapter of this site uses, you are firmly on the first descent, where the U is the whole story and pushing right just makes things worse.

05

What actually fixes each, and what does not

The reason the vocabulary earns its place: the two problems have almost opposite cures, so applying the wrong one is not merely wasteful, it makes things worse.

5a More data, and the thing it cannot touch

The most expensive fix in the industry, and the most often applied without checking. Here it is on three models, all fitted to the same panels.

degree 1, too simple degree 5, about right degree 9, too complex the noise floor
…degree 1, held-out W …degree 5 …degree 9
…

Drag it to the right end. Two of the three lines walk down onto the floor and stop there. The coral line does not move, because a straight line is a straight line whether you fit it to twelve readings or six hundred.

More data buys down variance and does nothing whatsoever about bias. The degree-9 model goes from hopeless to essentially optimal, because all that was ever wrong with it was that it did not have enough evidence to pin down its own flexibility. The degree-1 model is exactly as wrong at six hundred readings as at twelve, because what is wrong with it is not a shortage of evidence, it is that it is the wrong shape.

Which gives the rule worth carrying out of this page: before commissioning more data, draw the learning curve. If the two lines have already met, more data is a purchase with a guaranteed return of zero, and the honest thing to tell whoever is paying is that the model needs changing, not feeding.

5b The rest of the toolkit, sorted by what it treats

If the problem isReach forBecauseWhat it costs
Too much bias · both errors high and sitting together
Underfitting A more flexible model, or the same one with the dial turned up The shape it can draw does not include the shape of the answer. Variance, immediately. You are walking rightwards along the U on purpose.
Underfitting Better features The cheapest flexibility there is. A squared term, an interaction, a ratio somebody in the domain already knows matters. Your time, and the risk of inventing features that only work on this sample.
Underfitting Less penalty, less pruning, train for longer The restraint you added is now the binding constraint rather than the noise. Nothing, until it becomes the other problem.
Too much variance · training error low, held-out error far above it
Overfitting More data The only fix on this list that costs no accuracy anywhere. §5a. Money and time, and it is often simply unavailable.
Overfitting Regularisation: a penalty, a depth limit, a larger k Restraint. It refuses the model the freedom it was using to chase noise. Bias, deliberately. That is the trade, priced and visible on the dial.
Overfitting Averaging several models: bagging, a random forest Variance divides by roughly the number of models. Bias stays exactly where it was. Compute, and the readability of a single model.
Overfitting Fewer features Every column is a direction the model can wander in, and a column carrying nothing is pure variance. Bias, if you drop one that mattered.
Neither · held-out error sitting on the noise floor
You are finished Stop, and go and work out what the error costs The residual is weather. No model reaches under it and every hour spent trying is an hour lost. Nothing, and most people never take it.

Notice how the two halves mirror each other. Nearly every entry under one heading appears under the other with the sign flipped, which is what it means for this to be a trade rather than a problem with a solution.

CuriousHow do you actually choose the setting, without cheating?

Cross-validation, and then one honest number at the end.

Split the training data into five parts. For each candidate setting, fit on four and score on the fifth, rotating until each part has had a turn as the scorer, and average the five. Take the setting with the best average. That is the whole procedure, and it reuses your data five times over without ever scoring a model on a row it was fitted to.

The part people skip: the held-out set you used to choose is no longer held out. Try thirty settings against the same validation split and you will find the one that suits that split, which is overfitting one level up, with the same shape and none of the warning signs. The defence is a third split that gets looked at exactly once, after everything is settled, and whose number is the one you report.

And a rule of thumb that costs nothing: when two settings are within noise of each other, take the simpler one. Five folds of a small dataset produce scores that wobble by more than people expect, and a difference of half a watt between degree 5 and degree 6 is a coin toss. The simpler model will be steadier on data neither of you has seen.

06

Prompting AI: getting a diagnosis rather than a suggestion

This is the topic where an assistant is most likely to be confidently unhelpful, for a specific and predictable reason. Ask it why your model is not working and it will produce a list: try regularisation, try more features, try tuning the hyperparameters, try a different model, try more data. Every item on that list is a real technique. The list is still useless, because half of it treats bias and half of it treats variance, and applying the wrong half makes the model worse.

It produces the list because you gave it a symptom with no measurements attached, and a list is the only honest response to that. The fix is to hand over the two numbers.

"My model isn't performing well. How do I improve it?"

What you typically get back

Six suggestions in a numbered list, ordered by how often they appear in blog posts rather than by anything about your situation. Regularisation and "collect more data" will both be on it, which is notable, because those two treat the same problem and the first one treats it by making the model simpler while the second treats it by leaving the model alone. There is no way to follow both. And "try a more complex model" will be on the same list, which treats the opposite problem.

no training errorno held-out errorno noise floortreats both problems at onceno learning curve

Three habits, all cheap, all specific to this page.

  • Always give both numbers, never one. A held-out score alone cannot be diagnosed and neither can a training score. The pair is the entire signal, and either one on its own invites a guess.
  • Say what your noise floor is, or say that you do not know. Without it, nobody can tell whether you are near the limit or miles from it, and an assistant will cheerfully help you chase an improvement that does not exist.
  • Ask for the diagnosis first and the fix second. The order matters more here than anywhere else on the site, because a fix proposed before a diagnosis has a roughly even chance of pointing the wrong way.

One thing to watch for in generated code specifically. An assistant asked to "plot the learning curve" will often produce a plot of loss against training epoch, which is a different chart with a similar name, and answers a different question: it tells you when to stop training, not whether more data would help. What §3b needs is error against training set size, which in scikit-learn is learning_curve rather than anything to do with epochs. Both are useful. They are not substitutes, and the phrase "learning curve" is used for both by people who mean only one.

07

Beyond AI: the bottom of the curve is not a decision

Every chart on this page has a lowest point, and it is tempting to treat finding it as the end of the work. It is not, for a reason no amount of cross-validation will surface: the lowest point minimises the average squared error, and almost nobody actually wants that.

Squared error says a miss of 200 W is sixteen times worse than a miss of 50. It says being over and being under are the same. For these panels that might be fine. If the forecast is being used to decide whether to draw from the battery, being 200 W over is a flat battery at nine in the evening and being 200 W under is a slightly conservative afternoon, and those are not the same event at all. The dial has a different best setting under that description, and no chart on this page knows it.

7b The judgment calls no search makes for you

The big one

Simple is not a consolation prize

This page frames simplicity as a cost: you accept bias to buy down variance. In a system that has to run for years, simplicity is also a benefit that never appears in any error metric. A simpler model is easier to explain when somebody challenges it, degrades more gracefully when the world shifts under it, and fails in ways somebody can recognise at three in the morning.

A model two watts worse and five times easier to reason about is very often the right choice, and the cross-validation score will never say so. That is a judgment about the organisation that has to live with it, not about the data.

Judgment call

What an error costs, in each direction

The bottom of the U is the bottom under squared error. If over-predicting and under-predicting have different consequences, the setting you want is somewhere else, and finding it means writing the cost down first.

Judgment call

How much of the answer sheet you have spent

Every setting you compare uses up a little of your validation set's honesty. Thirty comparisons against one split, and the winner is partly a winner of that split. Nothing warns you, and the final number is the one you will quote.

Data reality

Whether tomorrow is drawn from today

All of this assumes the held-out readings come from the same world as the training ones. Panels degrade, trees grow, a neighbour builds an extension. When the world moves, the error rises for a reason that is neither bias nor variance, and this entire page is quiet about it.

Responsibility

Who absorbs the variance

A high-variance model is not equally unreliable for everyone. It is least reliable where the data was thinnest, which is usually wherever the smallest group was. The average error looks fine and the people at the edges carry the whole of it.

The useful way to hold all of this: bias and variance are not scores to optimise. They are the two questions to ask about any model that is not working well enough, in the right order, with two numbers you can get in a minute. Is it failing on the data it can already see, or only on data it cannot? Almost everything you should do next follows from which of those is true, and almost nothing follows from the error on its own.