Showing posts with label curve fitting. Show all posts
Showing posts with label curve fitting. Show all posts

Wednesday, September 12, 2012

Finding the right model

Yogi Berra once said that “predictions are hard, especially when they are about the future”. Or maybe it was Niels Bohr who said it? Or Casey Stengel, or Mark Twain, or Sam Goldwyn, or Dan Quayle? Nobody is sure who first said it, because the past is also hard to predict.
I offer here one explanation of what makes prediction hard. It has to do with finding the right underlying model.
Which is the right model?
The population growth problem from 6th grade
The year was 1970. I was in sixth grade. The teacher gave us an exercise in looking for patterns which would (as a side effect) increase our awareness of the global population problem. We were given the data in the first two columns of the table at the right. Note that the years listed are for successive doublings of the world population. Our assignment was to compute the doubling time, shown in column three, and then predict the world population in the year 2020.
Year
World
Population
Doubling
time
4331 BC
50 million

1131 BC
100 million
3200
470 AD
200 million
1600[1]
1270 AD
400 million
800
1670 AD
800 million
400
1870 AD
1.6 billion
200
1970 AD
3.2 billion
100
Sixth grade assignment
We were supposed to notice that each successive doubling time is half the previous doubling time. The world population doubled between 1870 and 1970 (in 100 years), so the next doubling to 6.4 billion would require 50 years. According to the rule we determined in class, the world populations would reach 6.4 billion in 2020.
Well, the estimate was a bit off. We reached 6.4 billion in 2005. Clearly the prediction was not drastic enough. But wait…
Taking this a step further, we would expect that the world population would hit 12.8 billion in 2045, and 25.6 billion in July of 2057. In sixth grade, there was something unsettling about this. Of course, the idea of unrestrained population growth was alarming, but somehow I couldn’t help but think that there was something wrong there.
The ludicrousness of this prediction only occurred to me years later. According to the model, the doubling period would eventually reach the very short time span of nine months. Now, in order for the population to double in this amount of time, every woman on the planet, aged 1 to 101, would need to be pregnant, and must give birth to twins[2]! The next doubling would occur in only four and a half months, so all the twins would need to be pregnant when they are born... What a curious world our descendants will live in!
In the year 2081

In his book 2081, A hopeful View of the Human Future, Gerard K. O'Neill made an interesting historical observation. He looked at the typical speed when someone travelled. Here is his chart.

Mode
of travel
Top speed
1781
Stagecoach
6 MPH
1881
Train
60 MPH
1981
Jet
600 MPH
2081
??
6,000 MPH
He noted that every century, there has been a ten-fold increase in speed, so it would follow logically that in another century we will hop into our mass transit vehicles (whatever they may be) and speed off at eight times the speed of sound. Maybe that’s not unreasonable. If we are taking pleasure trips to the moon, then that might actually be rather slow.
Now if we take his formula further forward, we can see that in the year 2581, people will be regularly making trips at about ten times the speed of light. This stretches my credibility a little bit. I prefer to obey speed limits, especially when it comes to the speed of light. Clearly science fiction writers disagree with me on that.
If we go the other direction, we can see that O’Neill’s formula falls into ridiculousville almost immediately. His formula would predict that a typical speed of travel would be 0.6 MPH, about one-fifth of a person’s normal walking speed.
What we have here is another example of an inappropriate mathematical model being used to make predictions. We might as well play off the fact that the word “train” has half as many letters as “stagecoach”, and that “jet” as half as many letters as “train”. (Well… kinda.) The next big leap forward in travel will have 1.25 letters.
The exponential growth of energy usage
I had a sense of déjà vu when I took Environmental Geology in college. There was a homework question that was aimed at impressing on us the disastrous implications of unbridled exponential growth.
The problem stated that the annual world-wide energy usage had been increasing throughout the century at an annual rate of 5%. The problem went on to state that there is a theoretical upper bound on the total energy available if all the matter in the entire Earth is converted into energy. This upper bound is stated in Einstein’s formula e = mc2. Figures were given for the mass of the Earth and current energy usage, and the question was asked: In what year would our annual energy requirements equal the total available energy?
The answer we arrived at was only a few millennia away, perhaps the year 3500, or maybe 10,000, I honestly don’t remember. I do remember the next question, and the answer that I gave. The question was “What do you conclude?” I knew that the correct answer was “It is high time for us to get off our lazy butts and do something about the energy crisis, because in fewer than 100 generations there will be a million billion trillion people standing on the last crumb that is left of the Earth.
I knew that, but I was stubborn. My answer was “Nothing”. For some reason, I did not receive full credit for that answer. The university environment does not favor the creative mind. Or the lazy one, either.
My comeback
I had lost one point on a homework assignment that was worth 1% of my grade in the class. I should have just stopped right there, but I had a point to make. It was all about the principle of the thing. I spent hours and hours defending my short answer.
First, I amended my answer a little, from “nothing” to “nothing, because the answer depends a great deal on the underlying mathematical model that is assumed for the growth of energy usage”. Then, I got out my slide rule and did some curve fitting. I don’t have the original work. I am sure that the paper I wrote it out on has long since crumbled to dust. I will reproduce the salient aspects of it.
In this first graph, I show some data that I cooked up. The data is an exponential curve with the some added to it. In the graph, I also show the least squares fit of an exponential curve. This shows that the data can be approximated with an exponential curve that is increasing at 5.33% per year for 50 years.
Hypothetical energy usage, with exponential curve
I will take this to be a reasonable approximation of what energy usage data might look like. And, based on this data, a scientist or policymaker might come to the conclusion that energy usage is going up at a rate of about 5% per year. (Actually, the data I have dug up looks more chaotic than this. Wars and other catastrophes do a good job of being unpredictable.)
In this next graph, I show that same data, but this time it is approximated by a parabola. Looking at this curve fit, I don’t think I could testify in court that the data must be an exponential. A parabola doesn’t do too bad at fitting the data.
Hypothetical energy usage, with parabolic fit curve
Although, maybe the fit is not so good at the far left side? The parabola dips downward just a tiny bit in the first few years, and the data seems to be going upward. I can fix this fairly easily by using a cubic parabola, a third order polynomial. Just looking at the graphs, I can see no reason why someone would reject this fit over the fit of the exponential.
Hypothetical energy usage, with third order polynomial fit
Why stop at third order? Just for grins, I had a look at fitting the data with a fifth order polynomial. Once again, the fit looks pretty good.
Hypothetical energy usage, with fifth order polynomial fit
Why not try seventh order? Well, I did try it, and I think I will reject this one, maybe just for aesthetic reasons. The curve is a little bumpy. I am not sure the data has enough evidence to support those bumps.
Hypothetical energy usage, with seventh order polynomial fit
Taking a brief excursion back to ridiculousville, I tried using a 20th order polynomial to fit the data. Clearly the wiggles in this polynomial are not a true feature of the real data, but a feature of the noise. (Those who read my post on When regression goes bad will understand why this failed.
Hypothetical energy usage, with twentieth order polynomial fit
I did one last curve fit. This one starts with some reasonable assumptions about growth. An exponential curve is a reasonable approximation for growth of most physical things at the onset, but eventually in any real system, there has to be some saturation. Bunnies multiply, but eventually they run out of food.
For anything real, there has to be constrained growth. One commonly used model for this is the logistics curve. This curve shows initial exponential growth, but the growth gradually slows down as it approaches an asymptote. Once again, the fit looks fairly reasonable.
Hypothetical energy usage, with logistic curve  fit
The punch line
So far, all I have done is demonstrate that a number of curves can be bent around to look like a noisy exponential growth curve. At arm’s length, they all do a modest job at approximating the data that I provided. While some curves are somewhat better than others, there is no slam dunk best curve. Hang on to that thought, because the punch line is coming.
Each of the curves that I have fit to the data can be used to predict what the energy usage will be at some later date. I have gone through that exercise with each of these curves to yield a prediction about the energy usage in year 100 (50 years beyond the end of the data), and at year 500.
Model
Year 100
Year 500
Exponential
180.6
1.919 X 1011
Parabola
51.03
1337
Cubic
87.83
11,160
Fifth order
-10.30
-1.608 X 106
Sixth order
-4,978
-3.662 X 108
Seventh order
-39,700
-1.668 X 1010
Eighth order
-159,000
-3.798 X 1011
Fifteenth order
4.355 X 1010
5.756 X 1022
Twentieth order
-5.857 X 1013
-4.471 X 1029
Logistic
27.86
28.42
I hope you are saying wow. These equations all looked kind of similar from t = 0 to t = 50.  Even at t = 100, we have mega-ginormous disagreements on what the energy usage will be: anywhere from the silly value of -6 X 1013 up to the tremendous value of 4 X 1010. I think I can safely say that I have made my point. The underlying choice of model might not matter much for interpolation, but for extrapolation, the choice of model can change an estimate by many orders of magnitude.
Actually, the only model that did not give huge answers for the 500 year estimate is the logistic model, the mathematical equation that was designed to model constrained growth. Hmmm…
Conclusion
Considerable effort usually goes into finding an equation that fits the existing data. Often, a variety of equations are tried and the one that best fits the existing data is chosen.
This typical process omits a crucial step. That step getting to know the data, understanding the natural constraints, and looking at the forces that drive the values up or down. This knowledge should drive the choice of mathematical model.



[1] Little bit of trivia here... the year before 1 AD was 1 BC, rather than 0. The correct difference between these two years is thus 1600, rather than 1601.
[2] I assume that there are an equal number of men and women. If there is only a single, very busy man, the women can be spared having to have twins.

Wednesday, July 25, 2012

When regression goes bad


There is always a temptation, when one is using regression to fit a data set, to add a few more parameters to make the fit better. Don’t give into the temptation!

Temptation
In the case of polynomial regression, this might be the delectable temptation of adding one more degree to the polynomial. If y(x) is approximated well by a weighted sum of 1, x2, and x3, then (one could reasonably assume) adding x4 and x5 will only make the fit better, right? Technically, it can’t make the fit worse, but in most real cases, the fit to the data will be improved with every predictive term that is added.
If one is doing multiple linear regression, the same thing applies. Let’s say, for example, one is trying to determine a formula that will predict tomorrow’s temperature. It would be reasonable to use the temperature today and yesterday as predictors. It might reduce the residuals to add in today’s humidity and the wind speed. The temperature from surrounding areas might also improve the fit to historical data. The more parameters are added, the better the fit.
There is, of course, a law of diminishing returns. At some point, each additional parameter may only reduce the residual error by a miniscule amount. So, simply from the standpoint of simplicity, it makes sense to eliminate those variables that don’t cause a significant improvement.
But there is another reason to be parsimonious. This reason is more than a matter of simple convenience. Adding additional parameters has the potential of making regression go bad!
A simple regression example
Let’s say that we wanted to use regression to fit a polynomial to a Lorentzian1  function:

Equation for a Lorentzian
This function is fairly well behaved, and is illustrated in the graph below.

Plot of the Lorentzian
Oh… there’s a question in the back. “Why would someone want to do polynomial regression to approximate this? Isn’t it easy enough just to compute the formula for the Lorentzian directly?” Yes, it is. I am using this just as an example. This is a way for me to get data that is nice and smooth and where we don’t have to worry about the noise, and we can be sure what the data between the data points looks like.
The plot above shows knot points at integer locations, -5, -4, -3 … 4, 5. We will use these eleven points as the data set that that feeds the regression. In the graph below, we see what happens if we use a fourth order polynomial to approximate the Lorentzian.

Fourth-order polynomial fit to the Lorentzian
While the overall shape isn’t horrible, the fourth order polynomial shown is red, is a bit disappointing. Elsewhere it is not quite as bad, but at zero, the polynomial predicts a value of 0.655, whereas it should be 1.000.
What to do? Well, the natural response is to add more terms to the regression. Each term will bring the polynomial closer to the knot points. In fact, since there are eleven data points to go through, we know that we can find a tenth order polynomial that will fit this exactly. Clearly this is a good goal, right? Trying to drive the residual error down to zero, right? Then we will have a polynomial that best matches our Lorentzian curve, right?
I should hope that I have done enough foreshadowing to suggest to the reader that this might not be the best course of action. And I hope that the repetitive use of the italicized word “right” at the end of each question was a further clue that something is about to go wrong.

A tenth-order polynomial fit to the Lorentzian
And wrong it did go. We see that the graph of the tenth-order polynomial function did an absolutely fabulous job of approximating the Lorentzian at the knot points. It goes right through each of those points. We also see that the fit in the region from -1 to +1 the fit2  is not too bad. However, as we go further away from zero, the fit gets worse and worse as it oscillates out of control. Between 4 and 5, the polynomial traces out a curve that is just plain lousy. Linear interpolation would have been so much better. Something went bad, and it wasn’t last week’s lox in the back of the fridge.
Let’s make this example a bit more practical. Often when we are doing regression, we are not interested in predicting what happened between sample points, but rather we ultimately want to predict what will happen outside the range. Interpolation is sometimes useful, but we often want extrapolation. In the weather prediction example, I want to know the weather tomorrow so I can plan a picnic. I don’t usually care about what the temperature was an hour ago.
If we look out just outside the range in our example, things get really bad. No… not really bad. It gets really, really bad. I mean awful. I mean “Oh my God, we are going to crash into the Sun” bad. The graph below shows what happens if we extend the approximation out a little bit – just out to -8 and +8. Just a few points beyond where we have data. How bad could that be?

A tenth-order polynomial fit to the Lorentzian, extended to -8 to +8
The observant reader will note that the scale of the plot was changed just a tiny bit. The polynomial approximation at x=8 is -8669.7. I asked “how bad could it be?” Well, if this model is going to predict tomorrow’s temperature to be anything below eight thousand degrees below zero, I am going to give up my plans for a picnic and party like crazy tonight because all the beer in my fridge will be frozen tomorrow.
What went wrong?
In this example, there were two things that caused this regression to go horribly wrong. The first is that I tried to push regression farther than it should be pushed. Under no conditions should anyone use regression with that many parameters when you only have eleven data points3. People who do that should be sent away to have a picnic somewhere where it is eight thousand degrees below zero. I am going to make the bold statement that, even if you have 11,000 data points, you should be very careful about using eleven parameters in your regression.
The second thing that went wrong is that the mathematical model used to fit the data was not so good. The Lorentzian function does something that polynomials are just not good at – it has an asymptote. Polynomials just aren’t good at asymptotes. The only polynomial that comes close to having a vertical asymptote of zero is the polynomial that is identically zero everywhere. And that polynomial is just plain boring. Even if we were a bit more reasonable about the order of the polynomial that we used, we would never get a good approximation of the Lorentzian out in the tails by using polynomials.
This underscores the importance of taking the time to understand your data, to get to know its needs, and especially its aspirations for the future, in order for you to use a function that might be able to successfully approximate the true underlying function. 
1. This is function goes by quite a long list of names, since it was invented independently for different reasons. Someday I will write a blog explaining this function’s fascinating history.
2. For the benefit of the astute and persnickety reader, I realize that I am using the word “fit” incorrectly. The term should be applied strictly to just how the approximating function behaves at the points used in the regression. It would have been more appropriate for me to have said “fit to the original function”.
3. Ok… My statement here is too strong. A discrete Fourier transform is a regression, although we don’t normally think about it that way. Many folks, myself included, have successfully avoided Siberian consequences using a DFT that has as many parameters as data points. (But they still have to deal with Gibb’s phenomena.) I apologize to anyone who just stuck their mukluks into their picnic basket.