cat /en/linear-regression-with-scikit-learn/
MDN-119:35

Linear Regression with Scikit-learn

· Artificial Intelligence · 4 min read

An excerpt from the book Machine Learning con Python e Scikit-learn

In scikit-learn, the linear_model package provides the LinearRegression class, which implements this supervised model, used when the output variable is continuous and has a linear relationship with the input variables. It takes just a few simple lines of code:

from sklearn.linear_model import LinearRegression
regression_model = LinearRegression()
regression_model.fit(x_train, y_train)
y_pred = regression_model.predict(x_test)

With LinearRegression we create the linear regression object, with the fit method we train it on the training set data and, finally, with the predict method we make predictions on the test data.

Let us run a linear regression on the “California Housing” dataset. We start by importing the data:

from sklearn.datasets import fetch_california_housing
data = fetch_california_housing(as_frame=True)
import pandas as pd
df = pd.DataFrame(data.frame)
df.head()
Figure 4.4 - The California Housing dataset
Figure 4.4 – The California Housing dataset

The exploratory analysis of this dataset was already carried out in chapter 3, so we will not repeat it here. Let us simply display the main information about the variables:

df.info()

> <class 'pandas.core.frame.DataFrame'>
> RangeIndex: 20640 entries, 0 to 20639
> Data columns (total 9 columns):
> # Column Non-Null Count Dtype
> --- ------ -------------- -----
> 0 MedInc 20640 non-null float64
> 1 HouseAge 20640 non-null float64
> 2 AveRooms 20640 non-null float64
> 3 AveBedrms 20640 non-null float64
> 4 Population 20640 non-null float64
> 5 AveOccup 20640 non-null float64
> 6 Latitude 20640 non-null float64
> 7 Longitude 20640 non-null float64
> 8 MedHouseVal 20640 non-null float64
> dtypes: float64(9)
> memory usage: 1.4 MB

So we have a dataset of 20,640 rows, with all-numeric columns. We can already see that there are no missing values, but we can confirm this with:

# verifichiamo la presenza di valori missing
df.isnull().sum()

> MedInc 0
> HouseAge 0
> AveRooms 0
> AveBedrms 0
> Population 0
> AveOccup 0
> Latitude 0
> Longitude 0
> MedHouseVal 0
> dtype: int64

We split the dataset into two subsets containing the features (X) and the target variable (y):

X = df.drop(['MedHouseVal'], axis=1)
y = df['MedHouseVal']

We will make a first prediction without manipulating the available data; afterwards we will evaluate the results and try to improve them. Let us split the dataset into a training set and a test set:

from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2)
print(X_train.shape)
print(y_train.shape)
print(X_test.shape)
print(y_test.shape)

> (16512, 8)
> (16512,)
> (4128, 8)
> (4128,)

Now we can go ahead and train the linear regression algorithm using scikit-learn’s LinearRegression class:

from sklearn.linear_model import LinearRegression
lr = LinearRegression()
lr.fit(X_train, y_train)
> LinearRegression()

We make predictions on the test data:

Y_pred = lr.predict(X_test)

All that remains is to measure the performance of the algorithm. First, let us compute the main error metrics. We calculate the MSE:

from sklearn.metrics import mean_squared_error
# calcolo il MSE per il dataset di test

mse_tst = mean_squared_error(y_test, y_pred)
print(f"Il Mean Squared error del test set è : {mse_tst:.3f}")

> Il Mean Squared error del test set è : 0.521

And the R² score:

from sklearn.metrics import r2_score

# calcolo punteggio R2 per il dataset di test
r2_tst = r2_score(y_test, y_pred)
print(f"Il punteggio R2 del test set è : {r2_tst:.3f}")

> Il punteggio R2 del test set è : 0.600

Finally, let us compare the actual values with the predicted ones:

# confrontiamo l'output reale con quello previsto

plt.figure(figsize=(6, 4))
plt.scatter(y_test, predict)
plt.xlabel("Prezzi Reali")
plt.ylabel("Prezzi Previsti")
plt.title("Prezzi reali vs Prezzi previsti")
plt.show()
Figure 4.5 - Actual prices vs predicted prices
Figure 4.5 – Actual prices vs predicted prices

We can try to improve performance with a couple of observations. Putting into practice what we saw in the exploration carried out in chapter 3, let us remove the rows containing outliers:

from scipy import stats
import numpy as np
z_scores = stats.zscore(df)
abs_z_scores = np.abs(z_scores)
filtered_entries = (abs_z_scores < 3).all(axis=1)
df = df[filtered_entries]

Let us repeat the training and look at the new results:

X = df.drop(['MedHouseVal'], axis=1)
y = df['MedHouseVal']

X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2)
lr.fit(X_train, y_train)
predict = lr.predict(X_test)

mse_tst = mean_squared_error(y_test, predict)
print(f"Il Mean Squared error del test set è : {mse_tst:.3f}")

r2_tst = r2_score(y_test, predict)
print(f"Il punteggio R2 del test set è : {r2_tst:.3f}")

> Il Mean Squared error del test set è : 0.446
> Il punteggio R2 del test set è : 0.627

Want to learn more? Buy the book Machine Learning con Python e Scikit-learn on Amazon

Try it yourself

An interactive demo of the ideas in this article: you can use it right here on the page.

DEMO Gradient descent in 3D · about this demo · full screen ↗

Also try: Overfitting

Another interactive demo related to this page.

DEMO Overfitting · about this demo · full screen ↗