account for the sin part of the example function:
In [ 6 ]: plt.plot(x, f(x), ‘b’, label=‘f(x)’)
plt.plot(x, ry, ‘r.’, label=‘regression’)
plt.legend(loc= 0 )
plt.grid(True)
plt.xlabel(‘x’)
plt.ylabel(‘f(x)’)
Figure 9-2. Example function and linear regression
To account for the sin part of the example function, higher-order monomials are
necessary. The next regression attempt takes monomials up to the order of 5 as basis
functions. It should not be too surprising that the regression result, as seen in Figure 9-3,
now looks much closer to the original function. However, it is still far away from being
perfect:
In [ 7 ]: reg = np.polyfit(x, f(x), deg= 5 )
ry = np.polyval(reg, x)
In [ 8 ]: plt.plot(x, f(x), ‘b’, label=‘f(x)’)
plt.plot(x, ry, ‘r.’, label=‘regression’)
plt.legend(loc= 0 )
plt.grid(True)
plt.xlabel(‘x’)
plt.ylabel(‘f(x)’)
The last attempt takes monomials up to order 7 to approximate the example function. In
this case the result, as presented in Figure 9-4, is quite convincing:
In [ 9 ]: reg = np.polyfit(x, f(x), 7 )
ry = np.polyval(reg, x)
Figure 9-3. Regression with monomials up to order 5