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.
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:
- Making Predictions.
- Estimating Coefficients.
- 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.
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:
- Loop over each epoch.
- Loop over each row in the training data for an epoch.
- 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.
No comments:
Post a Comment