Skip to content

Instantly share code, notes, and snippets.

@ForteXX-2020
Created January 15, 2021 02:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ForteXX-2020/8a15e32c403c40fef7ac0351d2621807 to your computer and use it in GitHub Desktop.
Save ForteXX-2020/8a15e32c403c40fef7ac0351d2621807 to your computer and use it in GitHub Desktop.
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