ML-Fundamentals - Lineare Regression - Exercise: Simple Linear Regression


Linear Regression is the Hello World of Machine Learning. In this exercise you will implement a simple linear regression (univariate linear regression), a model with one predictor and one response variable. The goal is to recap and practice fundamental concepts of Machine Learning. After the exercise, you should have a deeper understanding of what a Machine Learning model is and how do you train such a model with a data set (supervised learning). To achieve this, you will: 1. Calculate the cost and the gradient for concrete training data and θ\theta (pen & paper exercise) 2. Create your own data set 3. Implement a linear function as hypothesis (model) 4. Write a function to quantify your model (cost function) 5. Learn to visualize the cost function 6. Implement the gradient descent algorithm to train your model (optimizer) 7. Visualize your training process and results



You should have a basic knowledge of Machine Learning models, cost functions, optimization algorithms and also numpy and matplotlib. We will only recap these concepts for a better understanding and do not explain them in great detail. Suitable sources for acquiring this knowledge are:

Python Modules

By deep.TEACHING convention, all python modules needed to run the notebook are loaded centrally at the beginning.

# External Modules
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.axes3d import Axes3D

Exercises - Simple Linear Regression

Pen & Paper Exercise

Given the linear model:

hθ(x)=θ0+θ1xh_\theta(x) = \theta_0 + \theta_1 x

And the following concrete training data:

Dtrain={(0,1),(1,3),(2,6),(4,8)}D_{train} = \{(0,1),(1,3),(2,6),(4,8)\}

with each tuple (x,y)(x,y) denoting xx the feature and yy the target.


For θ0=1\theta_0 = 1 and θ1=2\theta_1 = 2 calculate:

  1. The cost:

JD(θ0,θ1)=12mi=1m(hθ(xi)yi)2J_D(\theta_0, \theta_1)=\frac{1}{2m}\sum_{i=1}^{m}{(h_\theta(x_i)-y_i)^2}

  1. The gradient J\nabla J, i.e. the partial derivatives:

J(θ0,θ1)θ0\frac{\partial J (\theta_0, \theta_1)}{\partial \theta_0}

J(θ0,θ1)θ1\frac{\partial J (\theta_0, \theta_1)}{\partial \theta_1}

Create a Data Set

First of all, you have to generate a data set Ω\Omega so you can evaluate your implementation. Ω\Omega consists of tupels (xi,yi)(x^i,y^i). Let xx and yy be two numpy arrays of equal-length mm. Create a linear function of mm data points in a given range [xmi,xmax][x_{mi}, x_{max}]. The xx values should be distributed equally over the defined interval. Add some Gaussian distributed noise to the corresponding yy values. Each response variable should differ from their ideal value by an additional δ\delta.

f(x)=a+bx+σ,with X={xRxminxxmax}f(x)= a + b * x + \sigma , \; with \ X=\left \{ x \in \mathbb{R} \mid x_{min} \leqslant x \leqslant x_{max} \right \}

An example data set could look like this plot (random seed 42 used):

# fixed random seed for testing

def linear_random_data(sample_size, a, b, x_min, x_max, noise_factor):
    '''creates a randam data set based on a lienar function in a given interval
        sample_size: number of data points
        a: coefficent of x^0
        b: coefficent of x^1
        x_min: lower bound value range
        x_max: upper bound value range
        noise_factor: strength of nosie added to y 
        x: array of x values | len(x)==len(y)
        y: array of y values corresponding to x | len(x)==len(y)
    raise NotImplementedError("You should implement this!")
x, y = linear_random_data(50, 0., 5., -10, 10, 5)
plt.plot(x,y, "rx")

Linear Hypothesis

A short recap, a hypothesis hθ(x)h_\theta(x) is a certain function that we believe is similar to a target function that we like to model. A hypothesis hθ(x)h_\theta(x) is a function of xx with fixed parameters θ\theta. The simplest kind of hypothesis is based on a linear equation with two parameters:

hθ(x)=θ0+θ1xh_\theta(x) = \theta_{0} + \theta_{1} * x

Implement hypothesis hθ(x)h_\theta(x) in the method linear_hypothesis and return it as a function.

def linear_hypothesis(theta_0, theta_1):
    ''' Combines given arguments in a linear equation and returns it as a function
        theta_0: first coefficient
        theta_1: second coefficient
        lambda that models a linear function based on theta_0, theta_1 and x
    raise NotImplementedError("You should implement this!")

Cost Function

A cost function JJ depends on the given training data DD and hypothesis hθ(x)h_\theta(x). In the context of the simple linear regression, the cost function measures how wrong a model is regarding its ability to estimate the relationship between xx and yy for specific θ\theta values. Later we will treat this as an optimization problem and try to minimize the cost function JD(θ)J_D(\theta) to find optimal θ\theta values for our hypothesis hθ(x)h_\theta(x). The cost function we use in this exercise is the Mean-Squared-Error cost function:


Implement the cost function JD(θ)J_D(\theta) in the method mse_cost_function. The method should return a function that takes the values of θ0\theta_0 and θ1\theta_1 as an argument.

Sidenote, the terms loss function or error function are often used interchangeably in the field of Machine Learning.

def mse_cost_function(x, y):
    ''' Implements MSE cost function as a function J(theta_0, theta_1) on given tranings data 
        x: vector of x values 
        y: vector of ground truth values y 
        lambda J(theta_0, theta_1) that models the cost function
    raise NotImplementedError("You should implement this!")
j = mse_cost_function(x, y)
print(j(2.1, 2.9))

Cost Function Visualization

After implementing a cost function, it is probably a good idea to visualize it to get from an abstract understanding to a more concrete representation. Use matplotlib and plot the cost function in two different ways. Create a contour plot that depicts a three-dimensional surface on a two-dimensional graph and plot the surface itself. Your visualization should consist of two subplots and have corresponding labeling, similar to the following example:

internet connection needed

def create_cost_plt_data(cost_func, interval, num_samples, x_offset=0., y_offset=0.):
    ''' Creates data for a 3D plot based on a given interval and a cost function
    The function creates two vectors t0 and t1 based on the 'interval' and number 
    of data point 'num_samples'. Using 'np.meshgrid' and the vectors two matrices 
    T0 and T1 are created that can be used as X  and Y during the plotting process. 
    Using the given 'cost_func' and the vector an additional matrix 'C ' is 
    created representing the cost for all data point combinations.
        cost_func: a function that is used to calculate costs C 
        interval: a scalar that defines the range [-interval,interval] data points 
                  are drawn from
        num_samples: number of data points drawn from the interval, equaly distributed 
        x_offset: shifts the interval by a scalar
        y_offset: shifts the interval by a scalar
        T0: a matrix representing a meshgrid for X values (Theta 0) 
        T1: a matrix representing a meshgrid for Y values (Theta 1)
        C: a matrix respresenting cost values        
    raise NotImplementedError("You should implement this!")

def create_cost_plt(T0, T1, Costs):
    ''' Creates a counter and a surface plot based on given data
        T0: a matrix representing a meshgrid for X values (Theta 0) 
        T1: a matrix representing a meshgrid for Y values (Theta 1)
        C: a matrix respresenting cost values 
    raise NotImplementedError("You should implement this!")
# create some data and plot it
T0, T1, C = create_cost_plt_data(mse_cost_function, 1000, 51, y_offset=5.)
create_cost_plt(T0, T1, C)

Gradient Descent

A short recap, the gradient descent algorithm is a first-order iterative optimization for finding a minimum of a function. From the current position in a (cost) function, the algorithm steps proportional to the negative of the gradient and repeats this until it reaches a local or global minimum and determines. Stepping proportional means that it does not go entirely in the direction of the negative gradient, but scaled by a fixed value α\alpha also called the learning rate. Implementing the following formalized update rule is the core of the optimization process:

θjnewθjoldαδδθjoldJ(θold)\theta_{j_{new}} \leftarrow \theta_{j_{old}} - \alpha * \frac{\delta}{\delta\theta_{j_{old}}} J(\theta_{old})

def update_theta(x, y, theta_0, theta_1, learning_rate):
    ''' Updates learnable parameters theta_0 and theta_1 
    The update is done by calculating the partial derivities of 
    the cost function including the linear hypothesis. The 
    gradients scaled by a scalar are subtracted from the given 
    theta values.
        x: array of x values
        y: array of y values corresponding to x
        theta_0: current theta_0 value
        theta_1: current theta_1 value
        learning_rate: value to scale the negative gradient 
        t0: Updated theta_0
        t1: Updated theta_1
    raise NotImplementedError("You should implement this!")

Using the update_theta method, you can now implement the gradient descent algorithm. Iterate over the update rule to find a θ0\theta_0 and a θ1\theta_1 that minimize our cost function JD(θ)J_D(\theta). This process is often called training of a machine learning model. During the training process create a history of all theta and cost values. You can use them later for evaluation. Implement a verbose argument that if true provides additional information during the process, e.g., final theta values after optimization or cost value at some iterations.

def gradient_descent(x, y, iterations=1000, learning_rate=0.0001, verbose=None):
    ''' Minimize theta values of a linear model based on MSE cost function
        x: vector, x values from the data set
        y: vector, y values from the data set
        iterations: scalar, number of theta updates
        learning_rate: scalar, scales the negative gradient 
        verbose: boolean, print addition information 
        t0: Updated theta_0
        t1: Updated theta_1
    raise NotImplementedError("You should implement this!")
cost_hist, t0_hist, t1_hist = gradient_descent(x, y, iterations=250, learning_rate=0.0003, verbose=True)

Model and Training Evaluation

Now visualize the training process by plotting the cost_hist as a curve. Also, create a plot that shows the decision boundary of your final hypothesis (model) inside your data. Your plots should look like:

internet connection needed

def evaluation_plt(cost_hist, theta_0, theta_1, x, y):
    ''' Plots a cost curve and the decision boundary
    The Method plots a cost curve from a given training process (cost_hist). 
    It also plots the data set (x,y) and draws a linear decision boundary 
    with the parameters theta_0 and theta_1 into the plotted data set.
        cost_hist: vector, history of all cost values from a opitmization
        theta_0: scalar, model parameter for boundary
        theta_1: scalar, model parameter for boundary
        x: vector, x values from the data set
        y: vector, y values from the data set
    raise NotImplementedError("You should implement this!")
evaluation_plt(cost_hist, t0_hist[-1], t1_hist[-1], x, y)

Optimize Hyperparameter

In machine learning, hyperparameters are parameters whose values are set before starting the training process of the model. The learning rate is a hyperparameter, and it is a crucial parameter in the context of optimization with first-order methods in supervised learning. It can easily happen that your model does not learn if you have chosen an unsuited learning rate. To find a suitable learning rate for your problem, you need to try different ones. Implement a function optimize_learning_rate that trains your model with different learning rates and plots the different cost histories. Try to identify edge cases, e.g., cases when the learning rate is too high or too low, to develop a better feeling for the learning rate problem. Your plot could look like this:

internet connection needed

def optimize_learning_rate(learning_rates, x, y):
    ''' Train a model with diffrent learning rates and plots the costs
        learning_rates: vector, learning rates used to train a linear model
        x: vector, x values from the data set
        y: vector, y values from the data set
    raise NotImplementedError("You should implement this!")
potential_lr = np.array([0.0001, 0.0007, 0.001, 0.007, .01, .0588, .05899])
optimize_learning_rate(potential_lr, x, y)

Summary and Outlook

During this exercise, fundamental elements of Machine Learning were covered. You should be able to answer the following questions:

  • What is a model using the example of a linear function as a hypothesis?
  • Who do you quantify a model?
  • What is the gradient descent algorithm and what is its used for in the context of Machine Learning?
  • Can you explain the concept of hyperparameters and name some?


Notebook License (CC-BY-SA 4.0)

The following license applies to the complete notebook, including code cells. It does however not apply to any referenced external media (e.g., images).

Exercise: Simple Linear Regression
by Christian Herta, Benjamin Voigt
is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.
Based on a work at

Code License (MIT)

The following license only applies to code cells of the notebook.

Copyright 2018 Christian Herta, Benjamin Voigt

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.