# Linear Regression Model

### Linear regression can be very useful in many business situations. The author has walked you through how to create a linear regression model.

· AI Zone · Opinion
Save
5.95K Views

Linear regression is a machine learning technique that is used to establish a relationship between a scalar response and one or more explanatory variables. The first scaler response is called a target or dependent variable while the explanatory variables are known as a response or independent variables. When more than one independent variable is used in the modeling technique we call it multiple linear regression.

Independent variables are known as explanatory variables as they can explain the factors that control the dependent variable along with the degree of the impact. This can also be calculated using ‘parameter estimates’ or ‘coefficients’.

Coefficients are tested for statistical significance with the help of confidence intervals built around them which also aids model robustness. The elasticity is based on the coefficient. They can describe the extent to which a certain factor explains the dependent. Adding to this, a negative coefficient can be interpreted to have a negative or an inverse relation with the dependent variable and a positive coefficient can be said to have a positive influence.

### Application of Linear Regression

1. Insights on consumer behavior
2. Understanding business factors influencing profitability
3. Estimates or forecasts
4. marketing effectiveness, pricing, and promotions strategies
5. Assess and minimize risk in portfolios
6. Understand important factors leading to the customer default

A very broad overview of the important steps needed to build a linear regression model could be

1. Feasibility of application of regression technique on the data set
2. Preparing the data to make it ready for regression
3. Build the regression model and test its accuracy
4. Save the model for future prediction
5. Deploy and maintain/monitor the model

### Techniques to Build a Linear Regression Model

We can build a linear regression model by using any of the below techniques

1. Gradient Descent
2. Ordinary Least Square(OLS)

The process of minimizing a function with the help of gradients of the cost function is called gradient descent(GD). The understanding of the form of the cost and its derivative is important in order to understand the path which needs to be followed. In machine learning parlance, this can be done using a very similar concept known as stochastic gradient descent(SGD). This is also responsible for minimizing the error of the model on training data.

Predictions are made by the model based on each training instance shown to the model. This results in error calculation which is propagated/updated in the next prediction which helps to reduce the error.

The ordinary least squares method is a technique for estimating unknown parameters in a linear regression model with the help least square method. It aims to minimize the sum of squares of the differences between the observed and the predicted points.

The applicability of the OLS technique is based on certain assumptions. Hence it is a good practice to check the assumptions of OLS before we apply it to build the linear regression model. The assumptions of OLS are mentioned below

1. Linear relationship - the relationship between the independent and dependent variables is linear
2. Multivariate normality - all variables to be multivariate normal
3. No or little multicollinearity - there is little or no multicollinearity in the data.  Multicollinearity is the phenomenon when the independent variables are highly correlated with each other
4. No auto-correlation - There is little or no autocorrelation in the data.  Autocorrelation can be experienced when the residuals are not independent of each other
5. Homoscedasticity - Residuals exhibit homoscedasticity. Homoscedasticity describes a situation in which the error term is the same across all values of the independent variable

### Build a Linear Regression Model from Scratch

Let's build a linear regression from scratch using a publicly available data set using both OLS and SGD techniques in python.

There are a lot of ways/libraries to build a linear regression model in python, but we will mostly concentrate on scikit learn library, pandas, and NumPy mainly to develop the same.

Sharing some of the screenshots during data wrangling, model building, and model saving activities.

#### 1. Importing the necessary Python libraries

Python

x

1
`# Enabling print for all lines`
2
`from IPython.core.interactiveshell import InteractiveShell`
3
`InteractiveShell.ast_node_interactivity = "all"`

Python

`xxxxxxxxxx`
1
10

1
`# Importing the necessary libraries`
2
`import pandas as pd`
3
`import numpy as np`
4
`from pandas import Series, DataFrame`
5

6
`import matplotlib.pyplot as plt`
7
`from matplotlib import rcParams`
8
`%matplotlib inline`
9

10
`import seaborn as sns`

#### 2. Loading the Data Set

Boston Housing Data

`Description:`

This dataset contains information collected by the U.S Census Service concerning housing in the area of Boston Mass. It was obtained from the StatLib archive (http://lib.stat.cmu.edu/datasets/boston), and has been used extensively throughout the literature to benchmark algorithms. However, these comparisons were primarily done outside of Delve and are thus somewhat suspect. The dataset is small in size with only 506 cases.

The data was originally published by Harrison, D. and Rubinfeld, D.L. 'Hedonic prices and the demand for clean air', J. Environ. Economics & Management, vol.5, 81-102, 1978.

`Dataset Naming:`

The name for this dataset is simply boston. MEDV is the variable which we are trying to predict

`Miscellaneous Details:`

• Origin- The origin of the boston housing data is Natural
• Usage- This dataset may be used for Assessment
• Number of Cases- The dataset contains a total of 506 cases
• Order- The order of the cases is mysterious
• Variables- There are 14 attributes in each case of the dataset. They are:
• CRIM - per capita crime rate by town
• ZN - proportion of residential land zoned for lots over 25,000 sq.ft.
• INDUS - proportion of non-retail business acres per town.
• CHAS - Charles River dummy variable (1 if tract bounds river; 0 otherwise)
• NOX - nitric oxides concentration (parts per 10 million)
• RM - average number of rooms per dwelling
• AGE - proportion of owner-occupied units built prior to 1940
• DIS - weighted distances to five Boston employment centres
• RAD - index of accessibility to radial highways
• TAX - full-value property-tax rate per 10,000 dollars
• PTRATIO - pupil teacher ratio by town
• B - 1000(Bk - 0.63)^2 where Bk is the proportion of blacks by town
• LSTAT - % lower status of the population
• MEDV - Median value of owner occupied homes in 1000s
Python

`xxxxxxxxxx`
1

1
`# Loading the data set from Python`
2
`from sklearn.datasets import load_boston`
3
`boston = load_boston()`
4
`type(boston)`

Output:

`sklearn.utils.Bunch`
Python

`xxxxxxxxxx`
1

1
`# Converting the inbuilt data(independen) into data frame`
2
`df = pd.DataFrame(boston.data, columns=boston.feature_names)`
3

4
`# Converting the target into a series`
5
`df['target'] = pd.Series(boston.target)`

#### 3. Having a look at the different variables from the data set

Input:

Python

`xxxxxxxxxx`
1

1
`# Having a look at the first few observations in the data and basic data properties`
2
`df.head()`
3
`df.shape`
4
`df.info()`

Output:

#### 4. Insights from the data set

Input:

Python

`xxxxxxxxxx`
1

1
`# Checking the statistical properties of the variables`
2
`df.describe().T`

Output:

Input:

Python

`xxxxxxxxxx`
1

1
`# Check for column wise missing values`
2
`df.isnull().sum()`

Output:

Input:

Python

`xxxxxxxxxx`
1

1
`# Building the box`
2
`rcParams['figure.figsize'] = 20,5`
3
`df.boxplot(color=dict(boxes='r', whiskers='r', medians='r', caps='r'))`
4

5
`# sns.set(rc={'figure.figsize':(6,6)})`
6
`# sns.set_style("whitegrid")`
7
`# sns.boxplot(data=df, orient="h", palette="Set2")`

Output:

Input:

Python

`xxxxxxxxxx`
1

1
`# Finding and plotting the correlation for the independent variables`
2
`sns.set(rc={'figure.figsize':(14,5)})`
3
`ind_var = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO', 'B', 'LSTAT']`
4
`# df[ind_var].corr()`
5
`sns.heatmap(df[ind_var].corr(), cmap=sns.cubehelix_palette(20, light=0.95, dark=0.15));`

Output:

Input:

Python

`xxxxxxxxxx`
1

1
`# Building a pair plot to understand the relationship between independent and dependent variables`
2
`sns.pairplot(df, x_vars = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM'], y_vars = ['target']);`
3
`sns.pairplot(df, x_vars = ['AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO', 'B', 'LSTAT'], y_vars = ['target']);`

Output:

From the above pair plot, we can conclude

• RM and MEDV have a shape like that in a normally distributed graph
• AGE is skewed to the left and LSTAT is skewed to the right
• TAX has a large amount of distribution around the point 700

#### 5. Building the model using scikit learn

Input:

Python

`xxxxxxxxxx`
1

1
`# Separating out the independent and target data`
2
`X = df.iloc[:,:-1]`
3
`y = df.iloc[:,-1]`

Input:

Python

`xxxxxxxxxx`
1

1
`# Spitting the data into train and test`
2
`from sklearn.model_selection import train_test_split`
3
`X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state=113)`
4

5
`# Checking the shape of the four parts of the data after split`
6
`X_train.shape, X_test.shape`
7
`y_train.shape, y_test.shape`

Output:

`((404, 13), (102, 13))`
`((404,), (102,))`

Input:

Python

`xxxxxxxxxx`
1

1
`# Building the linear regression model using sklearn`
2
`from sklearn.linear_model import LinearRegression`
3
`regressor = LinearRegression()`
4

5
`# Fitting the train data to the model`
6
`model = regressor.fit(X_train, y_train)`

#### 6. Prediction using the model and scoring the model

Input:

Python

`xxxxxxxxxx`
1

1
`# Making predictions on test data using the above model`
2
`y_pred = model.predict(X_test)`

Python

`xxxxxxxxxx`
1

1
`# Lets try to see the model accuracy/score on the training data`
2
`model.score(X_train, y_train)`
3

4
`# Lets try to see the model accuracy/score on the test data`
5
`model.score(X_test, y_test)`

Output:

`0.7345219949558541`
`0.7505954479592696`

Input:

Python

`xxxxxxxxxx`
1
11

1
`from sklearn.metrics import mean_absolute_error, mean_squared_error, explained_variance_score`
2
`import math`
3

4
`mae = mean_absolute_error(y_test, y_pred)`
5
`mse = mean_squared_error(y_test, y_pred)`
6
`rmse = math.sqrt(mse)`
7
`mv = explained_variance_score(y_test, y_pred)`
8

9
`print("Mean Absolute Error is", round(mae,1))`
10
`print("Root Mean Squared Error is", round(rmse,1))`
11
`print("Variance explained by model", round(mv*100,1), "%")`

Output:

```Mean Absolute Error is 3.4
Root Mean Squared Error is 5.0
Variance explained by model 75.1 %```

Input:

Python

`xxxxxxxxxx`
1

1
`# Linear regression coefficient and intercept. We can build the regression equation using the below parameter`
2
`model.coef_`
3
`model.intercept_`

Output:

`array([-1.14331280e-01,  3.30399664e-02,  2.19911151e-02,  1.93047806e+00,       -1.53459876e+01,  4.11678898e+00, -5.20475977e-03, -1.26111638e+00,        3.52665352e-01, -1.37375084e-02, -1.01521476e+00,  9.98692962e-03,       -4.90950094e-01])`
`33.54862614612348`

#### 7. Saving the model locally

Input:

Python

`xxxxxxxxxx`
1
10

1
`# Saving the model`
2
`import pickle`
3

4
`filename = 'boston_regression_model.sav'`
5
`pickle.dump(model, open(filename, 'wb'))`
6

7
`# Loading the model from disk`
8
`loaded_model = pickle.load(open(filename, 'rb'))`
9
`result = round(loaded_model.score(X_test, y_test)*100,2)`
10
`print("Moel accuracy is", result, "%")`

Output:

`Model accuracy is 75.06 %`

### Conclusion:

To summarize, linear regression can be very useful in many business situations however it can also have limited applicability in certain scenarios as it can work only when the dependent variable is continuous in nature. To learn more about the best machine learning course, you can click on the link.

Topics:
linear regression, tutorial, ai, ml, ai ml, machine learning

Opinions expressed by DZone contributors are their own.

Comments