Skip to content

Instantly share code, notes, and snippets.

@parmarsuraj99
Last active October 4, 2018 06:33
Show Gist options
  • Save parmarsuraj99/e6128416c1ce5491635881622e10f971 to your computer and use it in GitHub Desktop.
Save parmarsuraj99/e6128416c1ce5491635881622e10f971 to your computer and use it in GitHub Desktop.
Linear regression using sklearn models
#import libraries needed
import numpy as np
from sklearn import linear_model
if __name__=="__main__":
#load Dataset, here i am creating one for Single variable Linear regression
x = np.array([2, 4, 3, 6, 7, 6, 9, 10 , 12])
x=x.reshape(-1,1) #reshaping it
#slope of the line is 3 and intercept is 6
np.random.seed(18)
y = 4.5*x+3*np.random.uniform(0, 100, x.shape)*0.01
#Create an object for linear regression
linear = linear_model.LinearRegression()
#Train model
linear.fit(x, y)
print("Slope: ", linear.coef_)
print("Intercept: ", linear.intercept_)
'''
If you want to plot:
from matplotlib import pyplot as plt
plt.plot(x, linear.coef_*x+linear.intercept_, label='predicted')
plt.scatter(x, y, label='y')
plt.xlabel('X (independant)')
plt.ylabel('Ans (dependant)')
plt.legend()
plt.savefig('linear.png')
plt.show()
'''
#predict for test data
print("x=5 => y=", linear.predict([[5]]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment