How to Implement Linear Regression With Stochastic Gradient Descent From Scratch With Python

The core of many machine learning algorithms is optimization.

Optimization algorithms are used by machine learning algorithms to find a good set of model parameters given a training dataset.

The most common optimization algorithm used in machine learning is stochastic gradient descent.

In this tutorial, you will discover how to implement stochastic gradient descent to optimize a linear regression algorithm from scratch with Python.

After completing this tutorial, you will know:

  • How to estimate linear regression coefficients using stochastic gradient descent.
  • How to make predictions for multivariate linear regression.
  • How to implement linear regression with stochastic gradient descent to make predictions on new data.

Let’s get started.

  • Update Jan/2017: Changed the calculation of fold_size in cross_validation_split() to always be an integer. Fixes issues with Python 3.
  • Update Aug/2018: Tested and updated to work with Python 3.6.
How to Implement Linear Regression With Stochastic Gradient Descent From Scratch With Python

How to Implement Linear Regression With Stochastic Gradient Descent From Scratch With Python
Photos by star5112, some rights reserved.

Description

In this section, we will describe linear regression, the stochastic gradient descent technique and the wine quality dataset used in this tutorial.

Multivariate Linear Regression

Linear regression is a technique for predicting a real value.

Confusingly, these problems where a real value is to be predicted are called regression problems.

Linear regression is a technique where a straight line is used to model the relationship between input and output values. In more than two dimensions, this straight line may be thought of as a plane or hyperplane.

Predictions are made as a combination of the input values to predict the output value.

Each input attribute (x) is weighted using a coefficient (b), and the goal of the learning algorithm is to discover a set of coefficients that results in good predictions (y).

Coefficients can be found using stochastic gradient descent.

Stochastic Gradient Descent

Gradient Descent is the process of minimizing a function by following the gradients of the cost function.

This involves knowing the form of the cost as well as the derivative so that from a given point you know the gradient and can move in that direction, e.g. downhill towards the minimum value.

In machine learning, we can use a technique that evaluates and updates the coefficients every iteration called stochastic gradient descent to minimize the error of a model on our training data.

The way this optimization algorithm works is that each training instance is shown to the model one at a time. The model makes a prediction for a training instance, the error is calculated and the model is updated in order to reduce the error for the next prediction. This process is repeated for a fixed number of iterations.

This procedure can be used to find the set of coefficients in a model that result in the smallest error for the model on the training data. Each iteration, the coefficients (b) in machine learning language are updated using the equation:

Where b is the coefficient or weight being optimized, learning_rate is a learning rate that you must configure (e.g. 0.01), error is the prediction error for the model on the training data attributed to the weight, and x is the input value.

Wine Quality Dataset

After we develop our linear regression algorithm with stochastic gradient descent, we will use it to model the wine quality dataset.

This dataset is comprised of the details of 4,898 white wines including measurements like acidity and pH. The goal is to use these objective measures to predict the wine quality on a scale between 0 and 10.

Below is a sample of the first 5 records from this dataset.

The dataset must be normalized to the values between 0 and 1 as each attribute has different units and in turn different scales.

By predicting the mean value (Zero Rule Algorithm) on the normalized dataset, a baseline root mean squared error (RMSE) of 0.148 can be achieved.

You can learn more about the dataset on the UCI Machine Learning Repository.

You can download the dataset and save it in your current working directory with the name winequality-white.csv. You must remove the header information from the start of the file, and convert the “;” value separator to “,” to meet CSV format.

Tutorial

This tutorial is broken down into 3 parts:

  1. Making Predictions.
  2. Estimating Coefficients.
  3. Wine Quality Prediction.

This will provide the foundation you need to implement and apply linear regression with stochastic gradient descent on your own predictive modeling problems.

1. Making Predictions

The first step is to develop a function that can make predictions.

This will be needed both in the evaluation of candidate coefficient values in stochastic gradient descent and after the model is finalized and we wish to start making predictions on test data or new data.

Below is a function named predict() that predicts an output value for a row given a set of coefficients.

The first coefficient in is always the intercept, also called the bias or b0 as it is standalone and not responsible for a specific input value.

We can contrive a small dataset to test our prediction function.

Below is a plot of this dataset.

Small Contrived Dataset For Simple Linear Regression

Small Contrived Dataset For Linear Regression

We can also use previously prepared coefficients to make predictions for this dataset.

Putting this all together we can test our predict() function below.

There is a single input value (x) and two coefficient values (b0 and b1). The prediction equation we have modeled for this problem is:

or, with the specific coefficient values we chose by hand as:

Running this function we get predictions that are reasonably close to the expected output (y) values.

Now we are ready to implement stochastic gradient descent to optimize our coefficient values.

2. Estimating Coefficients

We can estimate the coefficient values for our training data using stochastic gradient descent.

Stochastic gradient descent requires two parameters:

  • Learning Rate: Used to limit the amount each coefficient is corrected each time it is updated.
  • Epochs: The number of times to run through the training data while updating the coefficients.

These, along with the training data will be the arguments to the function.

There are 3 loops we need to perform in the function:

  1. Loop over each epoch.
  2. Loop over each row in the training data for an epoch.
  3. Loop over each coefficient and update it for a row in an epoch.

As you can see, we update each coefficient for each row in the training data, each epoch.

Coefficients are updated based on the error the model made. The error is calculated as the difference between the prediction made with the candidate coefficients and the expected output value.

There is one coefficient to weight each input attribute, and these are updated in a consistent way, for example:

The special coefficient at the beginning of the list, also called the intercept or the bias, is updated in a similar way, except without an input as it is not associated with a specific input value:

Now we can put all of this together. Below is a function named coefficients_sgd() that calculates coefficient values for a training dataset using stochastic gradient descent.

You can see, that in addition, we keep track of the sum of the squared error (a positive value) each epoch so that we can print out a nice message in the outer loop.

We can test this function on the same small contrived dataset from above.

We use a small learning rate of 0.001 and train the model for 50 epochs, or 50 exposures of the coefficients to the entire training dataset.

Running the example prints a message each epoch with the sum squared error for that epoch and the final set of coefficients.

You can see how error continues to drop even in the final epoch. We could probably train for a lot longer (more epochs) or increase the amount we update the coefficients each epoch (higher learning rate).

Experiment and see what you come up with.

Now, let’s apply this algorithm on a real dataset.

3. Wine Quality Prediction

In this section, we will train a linear regression model using stochastic gradient descent on the wine quality dataset.

The example assumes that a CSV copy of the dataset is in the current working directory with the filename winequality-white.csv.

The dataset is first loaded, the string values converted to numeric and each column is normalized to values in the range of 0 to 1. This is achieved with helper functions load_csv() and str_column_to_float() to load and prepare the dataset and dataset_minmax() and normalize_dataset() to normalize it.

We will use k-fold cross-validation to estimate the performance of the learned model on unseen data. This means that we will construct and evaluate k models and estimate the performance as the mean model error. Root mean squared error will be used to evaluate each model. These behaviors are provided in the cross_validation_split(), rmse_metric() and evaluate_algorithm() helper functions.

We will use the predict(), coefficients_sgd() and linear_regression_sgd() functions created above to train the model.

Below is the complete example.

A k value of 5 was used for cross-validation, giving each fold 4,898/5 = 979.6 or just under 1000 records to be evaluated upon each iteration. A learning rate of 0.01 and 50 training epochs were chosen with a little experimentation.

You can try your own configurations and see if you can beat my score.

Running this example prints the scores for each of the 5 cross-validation folds then prints the mean RMSE.

We can see that the RMSE (on the normalized dataset) is 0.126, lower than the baseline value of 0.148 if we just predicted the mean (using the Zero Rule Algorithm).

Extensions

This section lists a number of extensions to this tutorial that you may wish to consider exploring.

  • Tune The Example. Tune the learning rate, number of epochs and even the data preparation method to get an improved score on the wine quality dataset.
  • Batch Stochastic Gradient Descent. Change the stochastic gradient descent algorithm to accumulate updates across each epoch and only update the coefficients in a batch at the end of the epoch.
  • Additional Regression Problems. Apply the technique to other regression problems on the UCI machine learning repository.

Did you explore any of these extensions?
Let me know about it in the comments below.

Review

In this tutorial, you discovered how to implement linear regression using stochastic gradient descent from scratch with Python.

You learned.

  • How to make predictions for a multivariate linear regression problem.
  • How to optimize a set of coefficients using stochastic gradient descent.
  • How to apply the technique to a real regression predictive modeling problem.

Do you have any questions?
Ask your question in the comments below and I will do my best to answer.


Want to Code Algorithms in Python Without Math?

Machine Learning Algorithms From Scratch

Code Your First Algorithm in Minutes

…with step-by-step tutorials on real-world datasets

Discover how in my new Ebook:
Machine Learning Algorithms From Scratch

It covers 18 tutorials with all the code for 12 top algorithms, like:
Linear Regression, k-Nearest Neighbors, Stochastic Gradient Descent and much more…

Finally, Pull Back the Curtain on
Machine Learning Algorithms

Skip the Academics. Just Results.

Click to learn more.


62 Responses to How to Implement Linear Regression With Stochastic Gradient Descent From Scratch With Python

  1. Blessing Ojeme October 28, 2016 at 11:41 am #

    Thanks, Jason, for keeping it as simple and straight as it can be. The tutorial was quite helpful.

  2. Arvind Ganesh March 12, 2017 at 8:47 pm #

    Are you handpicking the coefficients so that you have something to go off of for training? Why don’t you just use random values for the coefficients, and then go directly into gradient descent?

    • Jason Brownlee March 13, 2017 at 7:41 am #

      In the final example (end of the tutorial), I use the initial coefficients of “0” and use SGD to search for coefficients that best fit the data.

  3. klaas March 18, 2017 at 10:24 pm #

    Hi Jason,

    this blog is really awesome and the more i read the more questions appear. Here for instance i don’t get why the wine dataset is actually labeled as regression problem? We have fixed class labels so it should be a categorical classification right?
    I would also like to know if you would recommend also standardizing the labels too or is it enough to do this with the features? Google is not totally clear about that so i prefer an expert’s opinion. Thanks

    • Jason Brownlee March 19, 2017 at 6:11 am #

      You could treat the problem as classification, try it and see (with a different algorithm).

      Standardization can help. Again try it on your problem and see.

  4. Nandhini April 9, 2017 at 4:54 pm #

    Hi Jason,
    Have a question on finding the optimal coeff? What I understood from the equation of Gradient Descent :
    coeff(0) = coeff(0) – l_rate *1\m*errors
    coeff(1) = coeff(1) – l_rate * 1\m * errors * X[i]
    where m is no.of training rows.

    But in the above code I couldn’t figure out 1\m part. Could you explain me whats wrong in my understanding of the gradient descent equation.

  5. Kirill April 13, 2017 at 1:40 am #

    Hi there Jason,
    The problem you solving here is searching for coefficients that fitting straight line to the data. But how to visualize the result of this algorithm, is it even possible?

    • Jason Brownlee April 13, 2017 at 10:06 am #

      Yes, you can feed in each possible input variable (x) to the learned model and collect the output variable (y), then plot the x,y points.

  6. Sri May 28, 2017 at 3:54 am #

    When dealing with many inputs(>3) how do we visualize the data, because in the wine quality dataset there are 11 features/inputs.

  7. Kay June 17, 2017 at 7:47 am #

    Hi Jason,

    I am working with a dataset with 6 columns per row, where the first 5 values (say, a,b,c,d,e) are input variables that produce the 6th value as an output (say, y). Now if I want to utilize SGD, as implemented above, to find a set of a,b,c,d,e that maximizes y (minimizes 1-y), how would I go about this? Thanks for your tutorials, they’re incredibly helpful for someone just starting out!

  8. Jason L June 20, 2017 at 6:23 am #

    Hi Jason,

    I’m applying your tutorial to a modeling scenario with 5 inputs, one output, input and output variable scale in the 10^4 to 10^5 range (it is a media modeling example estimating cost efficiency where we typically don’t normalize in pre-processing). In comparing your methods with the SKlearn linear regression, I’m finding that I can’t estimate the intercept very accurately using your method, and my coefficients and intercept all converge to some reasonably small and similar values, (initializing all coefficients as 0). When initializing the intercept term to be similar to the SKlearn linear regression intercept result, your method converges to exactly the result of SKlearn linear regression. Would you say that your method is dependent on the initialization of coefficients, and is this a phenomenon you’ve encountered before? I’m curious if I am overlooking something, or if this is dependent on the scale of the data, or if this is the result of the data having an apparently large intercept.

    • Jason L June 20, 2017 at 6:42 am #

      I also want to note that when comparing your method to SKlearn linear regression with no intercept, it is perfect.

    • Jason Brownlee June 20, 2017 at 6:44 am #

      Gradient descent is more suitable when you cannot use the linalg methods (like sklearn) that require all data to fit into memory.

      The GD method may need to be tuned on your problem, e.g. learning rate, batch size, etc.

  9. nenduru July 5, 2017 at 2:14 pm #

    Hi Jason

    thank you for these awesome tutorials,
    Are you initializing coef[0] and coef[1] = 0 in the below code?
    debugging through for loops is confusing

    coef = [0.0 for i in range(len(train[0]))]

  10. Mohit Garg August 10, 2017 at 12:05 am #

    Thank u so much sir for your efforts….
    Sir can u tell how to omit first row of csv file

    • Jason Brownlee August 10, 2017 at 6:58 am #

      Some ideas:

      – Delete it manually
      – Skip it when loading with read_csv
      – Load it then delete it from the dataframe using pandas or from the array using numpy later.

      I hope that helps as a start.

  11. mohit garg August 11, 2017 at 3:23 am #

    sir when i call ds.info its shows that it read it as a single column plzz can u tell how to fix this problem

    this is code:

    df=pd.read_csv(‘wine1.csv’)
    df.info()

    OUTPUT:
    class ‘pandas.core.frame.DataFrame’>
    RangeIndex: 4898 entries, 0 to 4897
    Data columns (total 1 columns):
    fixed acidity;”volatile acidity”;”citric acid”;”residual sugar”;”chlorides”;”free sulfur dioxide”;”total sulfur dioxide”;”density”;”pH”;”sulphates”;”alcohol”;”quality” 4898 non-null object
    dtypes: object(1)
    memory usage: 38.3+ KB

  12. Arthur Grisel-DAvy August 12, 2017 at 8:32 pm #

    Great tutorial thanks you.
    However i find myself stuck on a problem. One of the value of the wine dataset (total sulfur dioxide) if way greater than the others and it create an unstable situation where the error and the coefficient soar, switching from positive to negative, causing an overflow. I can’t even go through 200 lines of the dataset. I checked my code and copy past yours but nothing changed.
    Is this a classic issue ? Is there a simple solution ?

    • Jason Brownlee August 13, 2017 at 9:53 am #

      Sorry to hear that.

      Perhaps you can identify that example and remove it from the dataset?

  13. neha August 16, 2017 at 5:28 am #

    Hi Jason,
    I am working on Campaign Analysis and using Linear Regression following cross validation, SGD in Python.Previously applying Linear Regression using 80% train set and 20% test set i used to get the prediction and recommend in terms of the deciles, where as in this technique recommended by you how can i divide my dataset into deciles and recommend?

    • Jason Brownlee August 16, 2017 at 6:41 am #

      They are two different ways of estimating the skill of the model on unseen data.

      Use the approach that gives you the least biased estimates.

      • nehasharma August 16, 2017 at 5:43 pm #

        So if i adopt your approach of cross validation i am getting 5 rows of Coefficients as fold =5..For my final linear regression equation which coefficients should i choose in order to finalize my equation and then derive the decile split for recommendation?

  14. KUNAL SARKAR August 21, 2017 at 12:37 pm #

    Hi Jason,
    Here you are updating the weightages after every sample, but as per SGD it should be after a batch processing. Can you please explain?

  15. Shinichi September 2, 2017 at 8:29 pm #

    How can we add regularization in it, where, regularization norm is a general p-norm with 1<=p<=2 (p=1 being lasso and p=2 ridge)?

    • Jason Brownlee September 3, 2017 at 5:42 am #

      Update the loss function to take into account the magnitude of the combined coefficients.

      Sorry, I do not have worked example (yet).

  16. Ami Tabak October 25, 2017 at 11:38 pm #

    wont (minmax[i][1] – minmax[i][0]) will result in 0 division

    • Jason Brownlee October 26, 2017 at 5:29 am #

      Why?

      • Ami Tabak October 27, 2017 at 8:26 pm #

        File “C:/tutorials/pure-python-lessons/linear-regression/stochastic-regression-protect-nan.py”, line 37, in normalize_dataset
        row[i] = (row[i] – minmax[i][0]) / (minmax[i][1] – minmax[i][0])

        ZeroDivisionError: float division by zero

        The csv is

        7,0.27,0.36,20.7,0.045,45,170,1.001,3,0.45,8.8,6
        6.3,0.3,0.34,1.6,0.049,14,132,0.994,3.3,0.49,9.5,6
        8.1,0.28,0.4,6.9,0.05,30,97,0.9951,3.26,0.44,10.1,6
        7.2,0.23,0.32,8.5,0.058,47,186,0.9956,3.19,0.4,9.9,6
        7.2,0.23,0.32,8.5,0.058,47,186,0.9956,3.19,0.4,9.9,6

        • Jason Brownlee October 28, 2017 at 5:12 am #

          It suggests that perhaps one of your columns has all the same value. Perhaps you can remove this column?

          • Ami tabak October 28, 2017 at 5:12 pm #

            Hi Jason
            The data I used is from this page. You posted it as a wine quality stats.
            Indeed when I change it so the last column wont be unanimous the error no longer appears.

            But of course this can happen in other data sets.
            will it be correct to change the code to the following?

            def normalize_dataset(dataset, minmax):
            for row in dataset:
            for i in range(len(row)):
            if minmax[i][1] == minmax[i][0]:
            row[i] = 0
            else:
            row[i] = (row[i] – minmax[i][0]) / (minmax[i][1] – minmax[i][0])

          • Jason Brownlee October 29, 2017 at 5:51 am #

            Normally we would remove columns that have no information like the one you describe.

  17. Imtithal Saeed May 23, 2018 at 12:41 am #

    hi Jason,

    So why using stochastic gradient descent? rather than others ? for example gradient descent with sum squares?

    • Jason Brownlee May 23, 2018 at 6:27 am #

      The main reason is when the matrix of input data does not fit into memory meaning the linalg solution cannot be calculated.

  18. Prabhu June 4, 2018 at 3:36 am #

    ValueError: could not convert string to float: fixed acidity;”volatile acidity”;”citric acid”;”residual sugar”;”chlorides”;”free sulfur dioxide”;”total sulfur dioxide”;”density”;”pH”;”sulphates”;”alcohol”;”quality”

    • Jason Brownlee June 4, 2018 at 6:34 am #

      Looks like you are working with a different dataset that might need to be processed first.

    • Guardiana July 2, 2018 at 11:09 pm #

      Hey, I had the same problem. The Problem is the delimiter in the csv file. You just need to change line 11 from
      csv_reader = reader(file)
      to
      csv_reader = reader(file,delimiter=’;’)

  19. Guardiana July 3, 2018 at 12:48 am #

    Hi Jason,

    in Line 47, you fill you fold list with random indexed entries from the dataset. That means that some points will appear more than once in a fold, and that not every point is used, right? Wouldnt it be better to use every point?
    Thanks in advance!

  20. vince August 13, 2018 at 1:14 am #

    Hi Jason,

    I tried your example and all works well, however I tried to use the function to estimate the coefficients on a different dataset with negative relations between predictors and the target variable and this function does not seem to give any negative coefficients. I tried different learning rates but that is not it.

    Hope you can point me in the right direction where I go wrong here.

    The dataset I used is the mtcars dataset with disp and hp as examples of columns negatively correlated with mpg.

    • Jason Brownlee August 13, 2018 at 6:18 am #

      Perhaps try scaling the data before fitting the model?

  21. vincent August 23, 2018 at 2:26 pm #

    Hi Jason,
    Thank you for your awesome tutorials.
    I’m trying your SGD with my dataset. My dataset has 6 features a,b,c,d,e,f and g is target result which I have to predict. some rows in my dataset like this:
    a b c d e f g
    8 20 2 8 1 0 162401
    7 30 2 16 1 0 157731
    7 30 2 10 1 0 174087
    7 30 2 14 1 0 175439
    7 30 2 11 1 0 137424
    So, my problem here is if i normalize data like this tutorial, I must normalize g column, too. and after I have coefficients vector, how can i predict the result with my test data? because the value of elements in coef vector is very small. On the other hand, the actual result of g column is very large.

    • Jason Brownlee August 24, 2018 at 6:06 am #

      You must normalize test data as well, using the min/max from the training data.

  22. dohye September 11, 2018 at 10:08 pm #

    Hi, Jason. Thank you for your explanation.

    But I have one question. Could you tell me why are you using error instead of gradient?
    I’m looking forward your answer.
    Thank you 🙂

  23. Ken Stpnecipher September 24, 2018 at 2:50 pm #

    Jason where do you get the 0,148 number?

    We can see that the RMSE (on the normalized dataset) is 0.126, lower than the baseline value of 0.148 if we just predicted the mean (using the Zero Rule Algorithm).

    Thanks

    Ken

    • Jason Brownlee September 25, 2018 at 6:16 am #

      I ran an zeror on the dataset beforehand.

      Earlier in the tutorial I noted:

      By predicting the mean value (Zero Rule Algorithm) on the normalized dataset, a baseline root mean squared error (RMSE) of 0.148 can be achieved.

  24. Muath Kefayah October 19, 2018 at 7:02 pm #

    Hi Jason,

    In yours tutorial , what is the feature you considered as response variable (target) ?

    Thanks in advance

  25. sandy October 26, 2018 at 10:43 pm #

    why do not use sklearn models.why u use regular program code.is it there any difference between them and any complexity

    • Jason Brownlee October 27, 2018 at 6:01 am #

      I recommend using sklearn in general.

      I show how to code it from scratch as a learning exercise only.

Leave a Reply