How to create a Linear Regression model in Sklearn

02.02.2021

Intro

Linear Regression is the most common starting point for Machine Learning models. In general, linear regression helps model a relation ship between a x or multiple x variables and a y. For example, we may want to predict housing prices (y) based on different properties (x's) of the houses (size, location, etc). In this article, we will see how to create a simple linear regression model using Sklearn.

Creating a Linear Regression Model

To create a Linear Regression model, we use the linear_model.LinearRegression clss from Sklearn. We start by creating an instance of the class, then supply and X (or X's) and a Y (the target) to the fit method. This will create a linear model (equation) for us. Once we have the fit model we can run predictions and score the model to see how well it performs.

import numpy as np
from sklearn import datasets, linear_model

x, y = datasets.load_diabetes(return_X_y=True)

# Only use the first X value
x = x[:, np.newaxis, 2]

model = linear_model.LinearRegression()

model.fit(x, y)

print(model.score())