continuous least squares polynomial in python

To perform continuous least squares polynomial regression in Python, we can use the numpy.polyfit function which fits a polynomial of degree n to a set of data points using the least squares method.

Here's an example code:

main.py
import numpy as np
from scipy.interpolate import make_interp_spline, BSpline

# Generate some sample data
x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 8, 20, 38, 62])

# Define the degree of the polynomial
poly_degree = 2

# Get the polynomial coefficients
poly_coeffs = np.polyfit(x, y, poly_degree)

# Generate the polynomial function
poly_func = np.poly1d(poly_coeffs)

# Plot the original data and the fitted polynomial
import matplotlib.pyplot as plt
x_new = np.linspace(x.min(), x.max(), 300)
y_new = poly_func(x_new)
plt.plot(x, y, 'o', x_new, y_new)
plt.show()
571 chars
23 lines

To make this a continuous curve, we can use the make_interp_spline function from Scipy to interpolate the data points with a B-spline. Here's the modified code:

main.py
import numpy as np
from scipy.interpolate import make_interp_spline, BSpline

# Generate some sample data
x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 8, 20, 38, 62])

# Define the degree of the polynomial
poly_degree = 2

# Get the polynomial coefficients
poly_coeffs = np.polyfit(x, y, poly_degree)

# Generate the polynomial function
poly_func = np.poly1d(poly_coeffs)

# Interpolate the data
spline_func = make_interp_spline(x, y, k=poly_degree)

# Generate a higher resolution x range
x_new = np.linspace(x.min(), x.max(), 300)

# Evaluate the fitted curve at the new x range
y_new = spline_func(x_new)

# Plot the original data and the fitted polynomial
plt.plot(x, y, 'o', x_new, y_new)
plt.show()
707 chars
29 lines

In this modified code, we first fit a polynomial of degree 2 to the data points, just like before. Then we use make_interp_spline to interpolate the data points with a B-spline. We specify the degree of the spline to be the same as the polynomial degree, so that the fitted curve is still a polynomial. Finally, we evaluate the fitted curve at a higher resolution x range and plot it along with the original data points.

gistlibby LogSnag