One of the simplest models of machine learning is linear regression
When there is a linear relationship between the features and the target variable, all we need to find is the equation of the straight line in the multidimensional space

For example, we have  real estate sales data: apartment size, floor, area code, distance from school and our goal is to estimate the property price
If we found that this is a linear problem then all we need is to find the coefficients and the intercept, that is:

Price = [Apartment Size] * a1 + [Floor] * a2 + [Area Code] * a3 + [Distance from school] * a4 + intercept

It is a supervised learning problem so we have some real data to build the model from:

 Apartment Size Floor Area Code Distance from school Price 120 2 1 2 230000$100 1 2 1 170000$ …. … … … …

Linear regression algorithms:

There are many ways to find the coefficients and the intercept, you can use least squares or one of the optimisation methods like gradient decent

In this post we will use least squares:

Least Squares

Least Squares is method  a find the best fit line to data. It uses simple calculus and linear algebra to minimize  errors:

Lets start with a simple example with 2 dimensions only. We want to find the equation:

Y = mX + b

We have a set of (x,y) pairs, to find m and b we need to calculate:

ֿ

We will use python and Numpy package to compute it:

Create a simple test data:

Visualising the data:

Compute the slope (m):

Compute the bias (b)

print the results:

So we can write our predict function:

Lets draw a graph to see the best fit line:

Now lets write a function to generate linear regression model based on 2 vectors
use a closure to generate a function dynamically:

Now if we have 2 vectors X,Y and we want to create a linear model we use it:

The return value is the prediction function:

Draw a graph:

## Adding variables

We can use least squares with any number of variables. For example with 2 features:

F = a1*X1 + a2*X2 + b

To generate the model:

Tagged ,

## 3 thoughts on “Linear Regression With Numpy”

1. Nice overview

2. Hi,
Very clear concepts.
I have a doub. when you are using this (vec = np.arange(10))
Why are you using ´10´?
The arrange have 8 values.
really thanks.

3. Very nicely written example! Thank you.