Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

13 - Regression and Interpolation

Data regression is a critical skill to determine correlations and potential causations between different variables in a system. In this lecture, we will learn how to use Python to perform regression and interpolation.

Regression is where you use the different functions you learned about in geometry and algebra to attempt to fit a curve to a set of data. The most common type of regression is linear regression where you attempt to fit a line to a set of data. The parameters for the curve are determined by minimizing the sum of the squares of the difference between the data and the curve. This is called the least squares method. For a linear regression, the parameters that are determined are the slope and intercept.

Below is an example of both a linear and a non-linear regression where first the data is imported and then operated on to obtain the independent variable (day of the year). Then the data is plotted and a curve is fit to the data. The same steps would be used for a linear regression.

First Example: Linear Regression

First generate the data and plot it

<Figure size 640x480 with 1 Axes>

Regression involves making an approximation to relate the independent variable (what you can control) to the dependent variable (what you measure). x is typically the independent variable and y is the dependent variable.

Once you have the data, there are multiple ways to obtain an estimate or approximation of the relationship between the variables. Here we’ll review multiple methods:

  • numpy.polyfit

  • scipy.optimize.curve_fit

  • scipy.optimize.minimize

  • (there are many other packages that you could use)

A. Numpy Polyfit

Numpy polyfit can be used to fit a polynomial to a set of data. The polynomial can be first order which is a linear regression or higher order. The higher the order, the more complex the curve can be. The polyfit function returns the coefficients of the polynomial. The coefficients can be used to plot the polynomial.

The slope is 0.496 and the intercept is 0.014
<Figure size 640x480 with 1 Axes>

Regression statistics can be calculated to the rsquared and the mape value which are measures of how well the regression line fits the data.

R2: R-squared

R-squared ranges from 0 to 1 with values closer to 1 indicating a better fit. It is calculated as 1 - (SSres/SStot) where SSres is the sum of the squares of the residuals and SStot is the total sum of the squares as given below.

The r-squared value is 0.966

MAPE Value (Mean Absolute Percent Error)

I like the MAPE value better than R-squared value as it indicates the total percent error. You could have a high R-squared value but still have a large error. The MAPE value is calculated as the sum of the absolute value of the difference between the data and the regression line divided by the sum of the data. The MAPE value is given below.

The MAPE value is 23.873%

Thus, using the predicted line relating x to y, the error you might expect in doing so is 23% (the MAPE value). Using the R-squared value, it’s not straightforward how you would make such a statement.

B. Scipy Optimize Curve Fit

Curve Fit is a scipy package that uses non-linear least squares to fit data to a function. It also generates a covariance matrix as detailed in the online documentation https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html.

The slope is 0.496 and the intercept is 0.014
The uncertainties in the two parameters is [0.00942515 0.05455338]

C. Scipy Optimize Minimize (A General Method)

Minimize is beneficial as you can use it for many different things not just regression. It is a general method that can be used to minimize a function. In this case, we are minimizing the sum of the squares of the difference between the data and the curve. The minimize function requires an initial guess for the parameters. Further information is here: https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html#scipy.optimize.minimize

message: Desired error not necessarily achieved due to precision loss. success: False status: 2 fun: 7.401305182224283 x: [ 4.957e-01 1.401e-02] nit: 3 jac: [ 4.905e-05 6.974e-06] hess_inv: [[ 6.583e-04 -3.192e-03] [-3.192e-03 1.996e-02]] nfev: 90 njev: 27

Second Example: Fit a Relationship (Non-Linear) to Sun Rise Data vs. Day of Year

The above data is from https://in-the-sky.org/. The data is of course a function of the longitude and latitude. For this data, it was latitude 43.26; longitude -86.02.

Loading...

Like most data sets, the data you import may not have the columns that you would like to have but you can generate the needed columns from the existing data. For example, the data we imported above reports the sunrise times for the given month and day. We’d like a column for the day of the year. We can use the datetime module to generate this column.

Note that you could program the day of year using if statements based on the month and day fields. However, the datetime module in pandas already has these tools.

<Figure size 640x480 with 1 Axes>

Note that the sunrise time is a string so when plotted, each string is sorted and then it’s plotted and given a tick mark. We’ll need to convert the times from a string of hr:min to a float of hours using the ‘datetime’ module.

200 9:14 201 9:14 202 9:14 203 9:14 204 9:14 ... 20 9:11 21 9:11 22 9:12 23 9:12 24 9:12 Name: SunRise, Length: 300, dtype: object

Notice the string function of split(‘:’) which splits the string into a list of strings based on the ‘:’ character. The first element of the list is the hour and the second element is the minute. We can then convert the hour and minute to a float of hours using the apply and lambda functions. An alternative way of doing this is below.

<Figure size 640x480 with 1 Axes>

The above plot looks like a period of the cosine function. Let’s plot a modified version of the cosine function to see if it fits the data.

<Figure size 640x480 with 1 Axes>

Our estimate based on our knowledge of the cosine function with scaling the amplitude and shifting the phase seems to fit the data well. We can use (1) the curve_fit function from the scipy.optimize module to fit the data to the cosine function and (2) minimizing the squared error with scipy minimize.

Method 1: Using the curve_fit function from the scipy.optimize module

The popt variable are the fitted parameters a,b,and c. The starred expression, *popt, is a way of unpacking the tuple into the variables popt[0], popt[1], popt[2], or a, b, and c in the cosFunc function.

The pcov variable is the covariance matrix and the diagonal elements are the variance of the parameters with the square root of the variance equal to the standard deviation of the parameters.

<Figure size 640x480 with 1 Axes>

Let’s also calculate the sum of the squared error for the fit as well as the mean absolute percent error (MAPE). The MAPE is a measure of the average percent error of the fit.

SSE = 4.3536151772476686
MAPE = 1.4491283240769897

So the mean absolute percent error is 1.4% which is pretty good. Another measure of the goodness of fit is the coefficient of determination or R2R^2 value.

R^2 = 0.9877915998692728

Method 2: Minimizing the squared error with scipy minimize

We can setup a function to calculate the sum of the squared errors and then use the scipy minimize function to minimize those errors.

  message: Optimization terminated successfully.
  success: True
   status: 0
      fun: 4.353615176985681
        x: [ 3.117e+00  9.964e+00  7.621e+00]
      nit: 7
      jac: [ 1.490e-06 -1.192e-07 -1.967e-06]
 hess_inv: [[ 1.410e-02  7.921e-02  5.370e-04]
            [ 7.921e-02  1.671e+01  7.408e-02]
            [ 5.370e-04  7.408e-02  1.998e-03]]
     nfev: 44
     njev: 11

Note the above minimize result (res) that is reported with the coefficients listed in the x variable (accessed with res.x) and the SSE function value of 4.35 (which agrees with the curve_fit function). There are also some jacobian and hessian information that we won’t discuss here but shows that the minimize function is using a gradient (or derivative) based method to minimize the SSE function.

Interpolation

Interpolation is getting a value at a different point than what is given in the data table. For example, below is a snapshot of a portion of the steam table. We would like an accurate estimate of the vapor pressure at 18.2 decgrees C.

We’ll use the scipy interpolator (1D) although there are many other options as described here.

VP at 18.2 C = 2.1105 kPa
VP at 18.2 C = 2.0899 kPa
2.3385, 2.3385, 2.3385