Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
0004_OLSregression(2)
from pylab import plt
import numpy as np
def f(x):
return 3 * x ** 3 - 4 * x ** 2
x = np.linspace(-2, 4, 25)
y = f(x)
plt.figure(figsize=(10, 6))
a, b = np.polyfit(x, y, 1)
y_hat = a*x + b
a, b, c = np.polyfit(x, y, 2)
y_hat2 = a*x**2 + b*x + c
a, b, c, d = np.polyfit(x, y, 3)
y_hat3 = a*x**3 + b*x**2 + c*x + d
a, b, c, d, e = np.polyfit(x, y, 4)
y_hat4 = a*x**4 + b*x**3 + c*x**2 + d*x + e
plt.plot(x, y_hat, 'b-', label='degree=1');
plt.plot(x, y_hat2, 'y-', label='degree=2');
plt.plot(x, y_hat3, 'g-', label='degree=3');
plt.plot(x, y_hat4, 'o-', label='degree=4');
plt.plot(x, y, 'ro', label='Test data');
plt.legend();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment