Monomials as basis functions
One of the simplest cases is to take monomials as basis functions — i.e., b 1 = 1, b 2 = x, b 3
= x
2
, b 4 = x
3
,.... In such a case, NumPy has built-in functions for both the determination of
the optimal parameters (namely, polyfit) and the evaluation of the approximation given a
set of input values (namely, polyval).
Table 9-1 lists the parameters the polyfit function takes. Given the returned optimal
regression coefficients p from polyfit, np.polyval(p, x) then returns the regression
values for the x coordinates.
Table 9-1. Parameters of polyfit function
Parameter Description
x
x coordinates (independent variable values)
y
y coordinates (dependent variable values)
deg
Degree of the fitting polynomial
full
If True, returns diagnostic information in addition
w
Weights to apply to the y coordinates
cov
If True, covariance matrix is also returned
In typical vectorized fashion, the application of polyfit and polyval takes on the
following form for a linear regression (i.e., for deg=1):
In [ 5 ]: reg = np.polyfit(x, f(x), deg= 1 )
ry = np.polyval(reg, x)
Given the regression estimates stored in the ry array, we can compare the regression result
with the original function as presented in Figure 9-2. Of course, a linear regression cannot