Lecture 9: Regression analysis
Overview
Professor Saad distinguishes interpolation, which must pass through every data point, from regression, which fits a chosen model by minimizing prediction error, usually the sum of squared residuals. He demonstrates polynomial regression with NumPy's `polyfit` and `polyval`, then uses SciPy's `curve_fit` for user-defined models, including lake-bacteria decay, water's ion product, and temperature-dependent reaction rates.
Key takeaways
- Use interpolation when the curve must pass through every observation; use regression when noisy or scattered measurements should be represented by a trend rather than matched point by point.
- For n observations, a polynomial of degree n minus 1 can interpolate the data, while a lower-degree `numpy.polyfit` model performs least-squares regression.
- `numpy.polyfit` and `numpy.polyval` are suited to standard polynomial models; `scipy.optimize.curve_fit` supports custom model functions with the independent variable first and fitted parameters afterward.
- Whether regression is linear depends on how the unknown parameters appear: a quadratic in x is linear regression if its coefficients enter linearly, while a parameter inside an exponent creates nonlinear regression.
- Plot scattered measurements as markers rather than connected lines, and avoid judging fit quality by appearance alone; Professor Saad recommends standard error for nonlinear models and R-squared for linear models.
Chapters
- High-degree polynomial interpolants can oscillate or cross the x-axis between data points, producing unphysical results such as negative density.
- Professor Saad recommends cubic splines for most interpolation tasks, reserving straight-line interpolation for strictly linear data.
- An interpolant must pass through every data point; repeated x-values with different y-values can make the interpolation system singular.
- With n data points, the highest-degree standard polynomial interpolant has degree n minus 1; three points, for example, determine a quadratic.
- Interpolation and regression provide formulas for estimating values between observations, while integration answers cumulative questions such as total CO2 emissions over a time period.
- `polyfit` and `polyval` are highlighted as tools to revisit before applying polynomial fitting to regression.
- Field measurements often contain noise from sensors and other conditions, so an interpolant that forces a curve through every observation is a poor model.
- Regression is used to capture a trend and predict responses, such as estimating height from femur length when genetics, diet, and other factors add variation.
- The response variable is the measured y-value, and the independent variable or variables are the proposed predictors.
- Regression does not decide whether the relationship should be linear, exponential, sinusoidal, or logarithmic; the analyst chooses the model form.
- The fitting procedure estimates that model's parameters, such as the coefficients in a line or quadratic.
- For each observed x-value, the model produces a prediction that can differ from the measured y-value.
- A residual is the difference between a model prediction and the corresponding observed value.
- Least-squares regression chooses coefficients to minimize the sum of squared residuals across all data points.
- The lecture presents the L2 norm as the standard error measure and notes that other error definitions can yield different fits.
- `polyfit(x, y, degree)` performs a least-squares polynomial fit and returns coefficients ordered from the highest power to the constant term.
- For n data points, degree n minus 1 gives an interpolant; choosing a lower degree performs regression instead.
- A degree-1 fit uses a straight-line model, while degrees 2 and 3 use quadratic and cubic models.
- The demonstration loads `height versus femur.txt` with `numpy.loadtxt`, then separates the two columns into femur length and height arrays.
- Professor Saad advises plotting measurements as unconnected markers because joining scattered observations with lines can falsely imply continuity.
- The example uses 10 paired femur-length and height measurements to explore the relationship.
- A degree-1 `polyfit` estimates a straight-line relationship between femur length and predicted height.
- `numpy.linspace` creates 100 x-values over the observed range, and `polyval` evaluates the fitted coefficients for plotting.
- The fitted line is the least-squares best fit among straight lines, not a curve guaranteed to pass through any particular observation.
- Increasing the femur-height fit from degree 1 to degree 2 introduces a small quadratic coefficient and only slight curvature over the observed range.
- Plotting the quadratic over an implausibly wide femur-length range makes its curvature easier to see, but those extrapolated values are not physically realistic.
- Higher-degree polynomials can bend and oscillate more, so a visually closer fit is not automatically a better model.
- A quadratic or cubic model can still be linear regression when its unknown coefficients enter linearly, even though the curve is nonlinear in x.
- A model such as a combination of sine, cosine, and exponential basis functions is also linear in its coefficients if those coefficients are not transformed.
- A parameter such as beta inside an exponent, as in alpha times e to the beta x, makes the parameter-fitting problem nonlinear.
- `scipy.optimize.curve_fit` accepts a model function whose first argument is the independent variable and whose remaining arguments are parameters to estimate.
- The call also receives the observed x and y arrays, and returns optimal parameter values plus a covariance matrix.
- The fitted function can be evaluated by passing x-values followed by the fitted parameters, using Python argument unpacking such as `*popt`.
- The lake-organism model sums three exponential terms with fixed decay rates 1.5, 0.3, and 0.05, while fitting coefficients a, b, and c.
- The example pairs time measurements from 0.5 to 9 hours with observed bacterial counts, then uses `curve_fit` to estimate the three coefficients.
- The fitted function predicts approximately 1.8 million organisms at 5.3 hours.
- The water example models negative log base 10 of KW using A/T, B log base 10 of T, C times T, and D.
- Because A, B, C, and D enter linearly, the model produces a linear regression problem despite its reciprocal and logarithmic terms.
- The data are converted from KW to negative log10(KW) before fitting, so predictions on the plotted scale must be exponentiated appropriately to recover KW.
- The final example fits reaction rate K = K20 times theta to the power of T minus 20, where theta is a nonlinear parameter.
- Temperature measurements from 6 to 30 degrees Celsius and five reaction-rate observations are fitted with `curve_fit` to estimate K20 and theta.
- The lecture previews fit assessment: R-squared is presented as useful for linear models, while standard error is recommended for nonlinear models.
Transcript excerpt
0:03 Good day everyone. Good to be back. I'm hoping you had a chance to look at the interpolation lectures. And I just ask you to to think of one to three questions or more if you want about interpolation that you would ask someone as if you're giving a quiz. Do you have something for me? Max? >> My question was why is it important to use a polynomial regression fit above like degree two or three? >> Okay. Did you hear that? So why should we avoid using high order interpolant polynomial interpolants that are higher than three? Why?
0:57 Pardon me? There's another reason. They're really cheap to compute. I mean the system of equations for these for these interpolants is really is really cheap. It's a great question, Andy. Exactly, exactly. A polynomial has as many roots as its degree. So a fifth order polynomial has five roots. A 10th order polynomial has 10 roots. Now not all roots are going to be real, but if they're all real, it means it has to cross the x-axis 10 times. And so there's a high risk as you go to higher order polynomials
1:46 that your polynomial is going to try to cross the x-axis to go through a root in between any one of those points that you're interpolating in between. And what happens if you did the with the lecture with that density, you'll get a negative density or negative values, unphysical values. Great question. What's another question? Yes. >> Poly val >> Oh, when would it be more useful to use poly val versus cubic spline? Good questions. I should have you guys
2:35 do the quizzes for the for the rest of the class. When? Actually, I'm going to take a minute to think about this myself.
This is the start of the transcript. Save this video free for the whole transcript, searchable and time-coded.
In this course
Related notes
Summary, takeaways, and chapters were generated by AI from the video's transcript and may contain errors. The video belongs to its creator, Professor Saad Explains.