Last active
October 4, 2018 06:33
-
-
Save parmarsuraj99/e6128416c1ce5491635881622e10f971 to your computer and use it in GitHub Desktop.
Linear regression using sklearn models
This file contains 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
#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