Simple Linear Regression by Scikit

By | December 4, 2016
Share the joy
  •  
  •  
  •  
  •  
  •  
  •  

Suppose we have training set for y = 5 + 0.5 * x. Run below code we can find the coefficient(slope) and intercept

import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model

# y = 5 + 0.5 * x
x = [-10.0, -9.5, -9.0, -8.5, -8.0, -7.5, -7.0, -6.5, -6.0, -5.5, -5.0, -4.5, -4.0, -3.5, -3.0, -2.5, -2.0, -1.5, -1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5, 10.0]
y = [-1.7776247, 0.9721851, 2.8311658, -1.7664247, 2.0148739, 1.2848472, 4.9397416, 2.3675736, 3.7809385, 3.9241124, 1.8500219, 4.3446124, 4.7043888, 4.0020450, -1.7093026, 2.4250200, 8.3738445, 7.4809320, 4.7741648, 5.1719583, 6.5781468, 4.5257286, 4.7368501, 6.5144324, 7.0737169, 2.5072875, 5.7161262, 8.8050798, 7.9458498, 9.9034171, 6.6390707, 7.7411975, 6.1857891, 8.1798865, 11.2942560, 11.3548412, 8.6652006, 7.9644377, 10.0735000, 8.5496633, 7.5857769]
a = np.array(x).reshape(x.__len__(), 1)
b = np.array(y).reshape(y.__len__(), 1)

# Plot outputs
regr = linear_model.LinearRegression()

# Train the model using the training sets
regr.fit(a, b)

print regr.coef_    # slope
print regr.intercept_   # intercept

My code on github: LR 1 feature