Created
November 18, 2017 13:09
-
-
Save felipessalvatore/8bde04c5081bc73c73d2e14f329ef431 to your computer and use it in GitHub Desktop.
visual example of linear regression
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sklearn import linear_model | |
import numpy as np | |
import matplotlib.pyplot as plt | |
# generating fake linear data. | |
# Where x = square meter, y = house price | |
cond = False | |
while not cond: | |
x = np.linspace(90, 1200, 100) | |
delta = np.random.uniform(0.77, 1.7, x.size) | |
gamma = np.random.normal(0, 3, x.size) | |
y = delta*500*x + gamma*4500 | |
x = x.astype("float32") | |
x = x.reshape((x.shape[0],1)) | |
y = y.astype("float32") | |
y = y.reshape((y.shape[0],1)) | |
data = np.concatenate([x,y],axis=1) | |
cond = min(y)>0 | |
#fitting the model and saving the weights | |
lr = linear_model.LinearRegression() | |
lr.fit(x,y) | |
if lr.coef_.shape == (2,1): | |
w, b = lr.coef_[0][0], lr.coef_[0][1] | |
else: | |
w, b = lr.coef_[0][0], 0 | |
# ploting the prediction and saving the image | |
fig, ax = plt.subplots(1, 1, figsize=(8, 8)) | |
line1, = ax.plot(x[0:70], y[0:70], 'bo', label='Real data') | |
line2, = ax.plot(x, x * w + b, 'r', label='Predicted data') | |
plt.legend(handles=[line1, line2], loc=2) | |
ax.set_title('House prices prediction', | |
fontsize=20, | |
fontweight='bold') | |
ax.set_xlabel("m\u00b2", fontsize=20) | |
ax.set_ylabel('$', fontsize=20) | |
plt.savefig("house_prices.png") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment