Skip to content

Instantly share code, notes, and snippets.

@michelkana
Last active January 30, 2021 19:32
Show Gist options
  • Save michelkana/99641bea8a5ef7a4fba194e18032827a to your computer and use it in GitHub Desktop.
Save michelkana/99641bea8a5ef7a4fba194e18032827a to your computer and use it in GitHub Desktop.
import numpy as np
import matplotlib.pyplot as plt
# Let's create a sample line
x = np.sort(np.random.uniform(-1.5, 4.0, 100))
y = -0.2*x + 0.9
# Let's add normal noise to the line
y = y + np.random.normal(0, 1, 100)
# Let's compute the intercept and slope of
# regression line
beta_1 = np.sum(np.multiply((x - np.mean(x)),(y - np.mean(y)))) / np.sum((x - np.mean(x))**2)
beta_0 = np.mean(y) - beta_1*np.mean(x)
# Let's plot the data and the regression line
plt.scatter(x,y, label='data')
plt.plot(x, beta_0 + beta_1*x, label='regression line', color='red')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.title('sample line with noise');
print('intercept: {0:.3f}'.format(beta_0))
print('slope: {0:.3f}'.format(beta_1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment