# Gradient descent

**Gradient descent** is a first-order iterative optimization algorithm for finding the minimum of a function. To find a local minimum of a function using gradient descent, one takes steps proportional to the *negative* of the gradient (or approximate gradient) of the function at the current point. If, instead, one takes steps proportional to the *positive* of the gradient, one approaches a local maximum of that function; the procedure is then known as **gradient ascent**.

Gradient descent is also known as **steepest descent**. However, gradient descent should not be confused with the method of steepest descent for approximating integrals.

## Contents

## Description[edit]

Gradient descent is based on the observation that if the multi-variable function is defined and differentiable in a neighborhood of a point , then decreases *fastest* if one goes from in the direction of the negative gradient of at , . It follows that, if

for small enough, then . In other words, the term is subtracted from because we want to move against the gradient, toward the minimum. With this observation in mind, one starts with a guess for a local minimum of , and considers the sequence such that

We have a monotonic sequence

so hopefully the sequence converges to the desired local minimum. Note that the value of the *step size* is allowed to change at every iteration. With certain assumptions on the function (for example, convex and Lipschitz) and particular choices of (e.g., chosen either via a line search that satisfies the Wolfe conditions or the Barzilai-Borwein^{[1]} method shown as following),

convergence to a local minimum can be guaranteed. When the function is convex, all local minima are also global minima, so in this case gradient descent can converge to the global solution.

This process is illustrated in the adjacent picture. Here is assumed to be defined on the plane, and that its graph has a bowl shape. The blue curves are the contour lines, that is, the regions on which the value of is constant. A red arrow originating at a point shows the direction of the negative gradient at that point. Note that the (negative) gradient at a point is orthogonal to the contour line going through that point. We see that gradient *descent* leads us to the bottom of the bowl, that is, to the point where the value of the function is minimal.

### Examples[edit]

Gradient descent has problems with pathological functions such as the Rosenbrock function shown here.

The Rosenbrock function has a narrow curved valley which contains the minimum. The bottom of the valley is very flat. Because of the curved flat valley the optimization is zig-zagging slowly with small step sizes towards the minimum.

The "Zig-Zagging" nature of the method is also evident below, where the gradient descent method is applied to .

### Limitations[edit]

For some of the above examples, gradient descent is relatively slow close to the minimum: technically, its asymptotic rate of convergence is inferior to many other methods. For poorly conditioned convex problems, gradient descent increasingly 'zigzags' as the gradients point nearly orthogonally to the shortest direction to a minimum point. For more details, see the § Comments below.

For non-differentiable functions, gradient methods are ill-defined. For locally Lipschitz problems and especially for convex minimization problems, bundle methods of descent are well-defined. Non-descent methods, like subgradient projection methods, may also be used.^{[2]} These methods are typically slower than gradient descent. Another alternative for non-differentiable functions is to "smooth" the function, or bound the function by a smooth function. In this approach, the smooth problem is solved in the hope that the answer is close to the answer for the non-smooth problem (occasionally, this can be made rigorous).

## Solution of a linear system[edit]

Gradient descent can be used to solve a system of linear equations, reformulated as a quadratic minimization problem, e.g., using linear least squares. The solution of

in the sense of linear least squares is defined as minimizing the function

In traditional linear least squares for real and the Euclidean norm is used, in which case

In this case, the line search minimization, finding the locally optimal step size on every iteration, can be performed analytically, and explicit formulas for the locally optimal are known.^{[3]}

For solving linear equations, this algorithm is rarely used, with the conjugate gradient method being one of the most popular alternatives. The speed of convergence of gradient descent depends on the ratio of the maximum to minimum eigenvalues of , while the speed of convergence of conjugate gradients has a more complex dependence on the eigenvalues, and can benefit from preconditioning. Gradient descent also benefits from preconditioning, but this is not done as commonly.^{[why?]}

## Solution of a non-linear system[edit]

Gradient descent can also be used to solve a system of nonlinear equations. Below is an example that shows how to use the gradient descent to solve for three unknown variables, *x*_{1}, *x*_{2}, and *x*_{3}. This example shows one iteration of the gradient descent.

Consider the nonlinear system of equations

Let us introduce the associated function

where

One might now define the objective function

which we will attempt to minimize. As an initial guess, let us use

We know that

where

The Jacobian matrix is given by

Evaluating and at yields

Thus

and

Now, a suitable must be found such that . This can be done with any of a variety of line search algorithms. One might also simply guess , which gives

Evaluating the objective function at this value, yields

The decrease from to the next step's value of is a sizable decrease in the objective function. Further steps would reduce its value further, until an approximate solution to the system was found.

## Comments[edit]

Gradient descent works in spaces of any number of dimensions, even in infinite-dimensional ones. In the latter case, the search space is typically a function space, and one calculates the Fréchet derivative of the functional to be minimized to determine the descent direction.^{[4]}

The gradient descent can take many iterations to compute a local minimum with a required accuracy, if the curvature in different directions is very different for the given function. For such functions, preconditioning, which changes the geometry of the space to shape the function level sets like concentric circles, cures the slow convergence. Constructing and applying preconditioning can be computationally expensive, however.

The gradient descent can be combined with a line search, finding the locally optimal step size on every iteration. Performing the line search can be time-consuming. Conversely, using a fixed small can yield poor convergence.

Methods based on Newton's method and inversion of the Hessian using conjugate gradient techniques can be better alternatives.^{[5]}^{[6]} Generally, such methods converge in fewer iterations, but the cost of each iteration is higher. An example is the BFGS method which consists in calculating on every step a matrix by which the gradient vector is multiplied to go into a "better" direction, combined with a more sophisticated line search algorithm, to find the "best" value of For extremely large problems, where the computer-memory issues dominate, a limited-memory method such as L-BFGS should be used instead of BFGS or the steepest descent.

Gradient descent can be viewed as applying Euler's method for solving ordinary differential equations to a gradient flow.

## Computational examples[edit]

### Python[edit]

The gradient descent algorithm is applied to find a local minimum of the function , with derivative . Here is an implementation in the Python programming language.

```
# From calculation, it is expected that the local minimum occurs at x=9/4
cur_x = 6 # The algorithm starts at x=6
gamma = 0.01 # step size multiplier
precision = 0.00001
previous_step_size = 1
max_iters = 10000 # maximum number of iterations
iters = 0 #iteration counter
df = lambda x: 4 * x**3 - 9 * x**2
while previous_step_size > precision and iters < max_iters:
prev_x = cur_x
cur_x -= gamma * df(prev_x)
previous_step_size = abs(cur_x - prev_x)
iters+=1
print("The local minimum occurs at", cur_x)
#The output for the above will be: ('The local minimum occurs at', 2.2499646074278457)
```

### Scala[edit]

Here is an implementation in the Scala programming language

```
import math._
val curX = 6
val gamma = 0.01
val precision = 0.00001
val previousStepSize = 1 / precision
def df(x: Double): Double = 4 * pow(x, 3) - 9 * pow(x, 2)
def gradientDescent(precision: Double, previousStepSize: Double, curX: Double): Double = {
if (previousStepSize > precision) {
val newX = curX + -gamma * df(curX)
println(curX)
gradientDescent(precision, abs(newX - curX), newX)
} else curX
}
val ans = gradientDescent(precision, previousStepSize, curX)
println(s"The local minimum occurs at $ans")
```

### Clojure[edit]

The following is a Clojure implementation:

```
(defn df [x] (- (* 4 x x x) (* 9 x x)))
(defn gradient-descent [thresh iters gamma x df]
(loop [prev-x x
cur-x (- x (* gamma (df x)))
iters iters]
(if (or (< (Math/abs (- cur-x prev-x)) thresh)
(zero? iters))
cur-x
(recur cur-x
(- cur-x (* gamma (df cur-x)))
(dec iters)))))
(prn "The minimum is found at: " (gradient-descent 0.00001 10000 0.01 6 df))
;; This will output: "The minimum is found at: " 2.2499646074278457
```

one could skip the precision check and then use a more general functional programming pattern, using reduce:

```
(defn gradient-descent [iters gamma x df]
(reduce (fn [x _]
(- x (* gamma (df x))))
x
(range iters)))
(prn "The minimum is found at: " (gradient-descent 10000 0.01 6 df))
;; This will output: "The minimum is found at: " 2.249999999999999
```

The last pattern can also be achieved through infinite lazy sequences, like so:

```
(defn gradient-descent [n-iters gamma x df]
(nth (iterate (fn [x] (- x (* gamma (df x)))) x)
n-iters))
(prn "The minimum is found at: " (gradient-descent 10000 0.01 6 df))
;; This will output: "The minimum is found at: " 2.249999999999999
```

### Java[edit]

Same implementation, to run in Java with JShell (Java 9 minimum): `jshell <scriptfile>`

```
import java.util.function.Function;
import static java.lang.Math.pow;
import static java.lang.System.out;
double gamma = 0.01;
double precision = 0.00001;
Function<Double,Double> df = x -> 4 * pow(x, 3) - 9 * pow(x, 2);
double gradientDescent(Function<Double,Double> f) {
double curX = 6.0;
double previousStepSize = 1.0;
while (previousStepSize > precision) {
double prevX = curX;
curX -= gamma * f.apply(prevX);
previousStepSize = abs(curX - prevX);
}
return curX;
}
double res = gradientDescent(df);
out.printf("The local minimum occurs at %f", res);
```

### Julia[edit]

Here is the same algorithm implemented in the Julia programming language.

```
cur_x = 6;
gamma = 0.01;
precision = 0.00001;
previous_step_size = 1;
df = (x) -> 4x^3 - 9x^2;
while previous_step_size > precision
prev_x = cur_x;
cur_x -= gamma * df(prev_x);
previous_step_size = abs(cur_x - prev_x);
end
println("The local minimum occurs at $cur_x");
```

### C[edit]

Here is the same algorithm implemented in the C programming language.

```
#include <stdio.h>
#include <stdlib.h>
double dfx(double x) {
return 4*(x*x*x) - 9*(x*x);
}
double abs_val(double x) {
return x > 0 ? x : -x;
}
double gradient_descent(double dx, double error, double gamma, unsigned int max_iters) {
double c_error = error + 1;
unsigned int iters = 0;
double p_error;
while(error < c_error && iters < max_iters) {
p_error = dx;
dx -= dfx(p_error) * gamma;
c_error = abs_val(p_error-dx);
printf("\nc_error %f\n", c_error);
iters++;
}
return dx;
}
int main() {
double dx = 6;
double error = 1e-6;
double gamma = 0.01;
unsigned int max_iters = 10000;
printf("The local minimum is: %f\n", gradient_descent(dx, error, gamma, max_iters));
return 0;
}
```

The above piece of code has to be modified with regard to step size according to the system at hand and convergence can be made faster by using an adaptive step size. In the above case the step size is not adaptive. It stays at 0.01 in all the directions which can sometimes cause the method to fail by diverging from the minimum.

### JavaScript (ES6)[edit]

Here is an example of gradient descent against randomised values, squareMeter and price, written in JavaScript, using ECMAScript 6 features:

```
// adjust training set size
const M = 10;
// generate random training set
const DATA = [];
const getRandomIntFromInterval = (min, max) =>
Math.floor(Math.random() * (max - min + 1) + min);
const createRandomPortlandHouse = () => ({
squareMeter: getRandomIntFromInterval(0, 100),
price: getRandomIntFromInterval(0, 100),
});
for (let i = 0; i < M; i++) {
DATA.push(createRandomPortlandHouse());
}
const _x = DATA.map(date => date.squareMeter);
const _y = DATA.map(date => date.price);
// linear regression and gradient descent
const LEARNING_RATE = 0.0003;
let thetaOne = 0;
let thetaZero = 0;
const hypothesis = x => thetaZero + thetaOne * x;
const learn = (x, y, alpha) => {
let thetaZeroSum = 0;
let thetaOneSum = 0;
for (let i = 0; i < M; i++) {
thetaZeroSum += hypothesis(x[i]) - y[i];
thetaOneSum += (hypothesis(x[i]) - y[i]) * x[i];
}
thetaZero = thetaZero - (alpha / M) * thetaZeroSum;
thetaOne = thetaOne - (alpha / M) * thetaOneSum;
}
const MAX_ITER = 1500;
for (let i = 0; i < MAX_ITER; i++) {
learn(_x, _y, LEARNING_RATE);
console.log('thetaZero ', thetaZero, 'thetaOne', thetaOne);
}
```

### MATLAB[edit]

The following MATLAB code demonstrates a concrete solution for solving the non-linear system of equations presented in the previous section:

```
% Multi-variate vector-valued function G(x)
G = @(x) [
3*x(1) - cos(x(2)*x(3)) - 3/2 ;
4*x(1)^2 - 625*x(2)^2 + 2*x(2) - 1 ;
exp(-x(1)*x(2)) + 20*x(3) + (10*pi-3)/3];
% Jacobian of G
JG = @(x) [
3, sin(x(2)*x(3))*x(3), sin(x(2)*x(3))*x(2) ;
8*x(1), -1250*x(2)+2, 0 ;
-x(2)*exp(-x(1)*x(2)), -x(1)*exp(-x(1)*x(2)), 20 ];
% Objective function F(x) to minimize in order to solve G(x)=0
F = @(x) 0.5 * sum(G(x).^2);
% Gradient of F (partial derivatives)
dF = @(x) JG(x).' * G(x);
% Parameters
GAMMA = 0.001; % step size (learning rate)
MAX_ITER = 1000; % maximum number of iterations
FUNC_TOL = 0.1; % termination tolerance for F(x)
fvals = []; % store F(x) values across iterations
progress = @(iter,x) fprintf('iter = %3d: x = %-32s, F(x) = %f\n', ...
iter, mat2str(x,6), F(x));
% Iterate
iter = 1; % iterations counter
x = [0; 0; 0]; % initial guess
fvals(iter) = F(x);
progress(iter, x);
while iter < MAX_ITER && fvals(end) > FUNC_TOL
iter = iter + 1;
x = x - GAMMA * dF(x); % gradient descent
fvals(iter) = F(x); % evaluate objective function
progress(iter, x); % show progress
end
% Plot
plot(1:iter, fvals, 'LineWidth',2); grid on;
title('Objective Function'); xlabel('Iteration'); ylabel('F(x)');
% Evaluate final solution of system of equations G(x)=0
disp('G(x) = '); disp(G(x))
% Output:
%
% iter = 1: x = [0;0;0] , F(x) = 58.456136
% iter = 2: x = [0.0075;0.002;-0.20944] , F(x) = 23.306394
% iter = 3: x = [0.015005;0.0015482;-0.335103] , F(x) = 10.617030
% ...
% iter = 187: x = [0.683335;0.0388258;-0.52231] , F(x) = 0.101161
% iter = 188: x = [0.684666;0.0389831;-0.522302] , F(x) = 0.099372
%
% (converged in 188 iterations after exceeding termination tolerance for F(x))
```

### R[edit]

The following R programming language code is an example of implementing gradient descent algorithm to find the minimum of the function in previous section. Note that we are looking for 's minimum by solving its derivative being equal to zero.

And the x can be updated with gradient descent method every iteration in the form of

where k = 1, 2, ..., maximum iteration, and α is the step size.

```
# set up a stepsize
alpha = 0.003
# set up a number of iteration
iter = 500
# define the objective function f(x) = x^4 - 3*x^3 + 2
objFun = function(x) return(x^4 - 3*x^3 + 2)
# define the gradient of f(x) = x^4 - 3*x^3 + 2
gradient = function(x) return((4*x^3) - (9*x^2))
# randomly initialize a value to x
set.seed(100)
x = floor(runif(1, 0, 10))
# create a vector to contain all xs for all steps
x.All = numeric(iter)
# gradient descent method to find the minimum
for(i in seq_len(iter)){
x = x - alpha*gradient(x)
x.All[i] = x
print(x)
}
# print result and plot all xs for every iteration
print(paste("The minimum of f(x) is ", objFun(x), " at position x = ", x, sep = ""))
plot(x.All, type = "l")
```

## Extensions[edit]

Gradient descent can be extended to handle constraints by including a projection onto the set of constraints. This method is only feasible when the projection is efficiently computable on a computer. Under suitable assumptions, this method converges. This method is a specific case of the forward-backward algorithm for monotone inclusions (which includes convex programming and variational inequalities).^{[7]}

### Fast gradient methods[edit]

Another extension of gradient descent is due to Yurii Nesterov from 1983,^{[8]} and has been subsequently generalized. He provides a simple modification of the algorithm that enables faster convergence for convex problems. For unconstrained smooth problems the method is called the Fast Gradient Method (FGM)
or the Accelerated Gradient Method (AGM). Specifically, if the differentiable function is convex and is Lipschitz, and it is not assumed that is strongly convex, then the error in the objective value generated at each step by the gradient descent method will be bounded by . Using the Nesterov acceleration technique, the error decreases at .^{[9]} It is known that the rate for the decrease of the cost function is optimal for first-order optimization methods. Nevertheless, there is the opportunity to improve the algorithm by reducing the constant factor. The optimized gradient method (OGM)^{[10]} reduces that constant by a factor of two and is an optimal first-order method for large-scale problems.^{[11]}

For constrained or non-smooth problems, Nesterov's FGM is called the fast proximal gradient method (FPGM), an acceleration of the proximal gradient method.

### The momentum method[edit]

Yet another extension, that reduces the risk of getting stuck in a local minimum, as well as speeds up the convergence considerably in cases where the process would otherwise zig-zag heavily, is the *momentum method*, which uses a momentum term in analogy to "the mass of Newtonian particles that move through a viscous medium in a conservative force field".^{[12]} This method is often used as an extension to the backpropagation algorithms used to train artificial neural networks.^{[13]}^{[14]}

## An analogy for understanding gradient descent[edit]

The basic intuition behind gradient descent can be illustrated by a hypothetical scenario. A person is stuck in the mountains and is trying to get down (i.e. trying to find the minima). There is heavy fog such that visibility is extremely low. Therefore, the path down the mountain is not visible, so he must use local information to find the minima. He can use the method of gradient descent, which involves looking at the steepness of the hill at his current position, then proceeding in the direction with the steepest descent (i.e. downhill). If he was trying to find the top of the mountain (i.e. the maxima), then he would proceed in the direction steepest ascent (i.e. uphill). Using this method, he would eventually find his way down the mountain. However, assume also that the steepness of the hill is not immediately obvious with simple observation, but rather it requires a sophisticated instrument to measure, which the person happens to have at the moment. It takes quite some time to measure the steepness of the hill with the instrument, thus he should minimize his use of the instrument if he wanted to get down the mountain before sunset. The difficulty then is choosing the frequency at which he should measure the steepness of the hill so not to go off track.

In this analogy, the person represents the algorithm, and the path taken down the mountain represents the sequence of parameter settings that the algorithm will explore. The steepness of the hill represents the slope of the error surface at that point. The instrument used to measure steepness is differentiation (the slope of the error surface can be calculated by taking the derivative of the squared error function at that point). The direction he chooses to travel in aligns with the gradient of the error surface at that point. The amount of time he travels before taking another measurement is the learning rate of the algorithm. See Backpropagation § Limitations for a discussion of the limitations of this type of "hill climbing" algorithm.

## See also[edit]

- Conjugate gradient method
- Stochastic gradient descent
- Rprop
- Delta rule
- Wolfe conditions
- Preconditioning
- BFGS method
- Nelder–Mead method
- Gauss–Newton algorithm
- Hill climbing

## References[edit]

**^**Jonathan Barzilai and Jonathan M. Borwein, "Two-point step size gradient methods", in:*IMA journal of numerical analysis*, 8.1 (1998), pp. 141-148.**^**Kiwiel, Krzysztof C. (2001). "Convergence and efficiency of subgradient methods for quasiconvex minimization".*Mathematical Programming, Series A*.**90**(1). Berlin, Heidelberg: Springer. pp. 1–25. doi:10.1007/PL00011414. ISSN 0025-5610. MR 1819784.**^**Yuan, Ya-xiang (1999). "Step-sizes for the gradient method" (PDF).*AMS/IP Studies in Advanced Mathematics*.**42**(2): 785.**^**G. P. Akilov, L. V. Kantorovich, Functional Analysis, Pergamon Pr; 2 Sub edition, ISBN 0-08-023036-9, 1982**^**W. H. Press, S. A. Teukolsky, W. T. Vetterling, B. P. Flannery, Numerical Recipes in C: The Art of Scientific Computing, 2nd Ed., Cambridge University Press, New York, 1992**^**T. Strutz:*Data Fitting and Uncertainty (A practical introduction to weighted least squares and beyond).*2nd edition, Springer Vieweg, 2016, ISBN 978-3-658-11455-8.**^**P. L. Combettes and J.-C. Pesquet, "Proximal splitting methods in signal processing", in:*Fixed-Point Algorithms for Inverse Problems in Science and Engineering*, (H. H. Bauschke, R. S. Burachik, P. L. Combettes, V. Elser, D. R. Luke, and H. Wolkowicz, Editors), pp. 185-212. Springer, New York, 2011.**^**Yu. Nesterov, "Introductory Lectures on Convex Optimization. A Basic Course" (Springer, 2004, ISBN 1-4020-7553-7)**^**Fast Gradient Methods, lecture notes by Prof. Lieven Vandenberghe for EE236C at UCLA**^**D. Kim, J A Fessler, "Optimized first-order methods for smooth convex minimization" Math. Prog. 151:8-107, Sep. 2016 https://dx.doi.org/10.1007/s10107-015-0949-3**^**Yoel Drori, "The exact information-based complexity of smooth convex minimization." https://arxiv.org/abs/1606.01424**^**Qian, Ning (January 1999). "On the momentum term in gradient descent learning algorithms" (PDF).*Neural Networks*.**12**(1): 145–151. Archived from the original (PDF) on 8 May 2014. Retrieved 17 October 2014.**^**"Momentum and Learning Rate Adaptation". Willamette University. Retrieved 17 October 2014.**^**Geoffrey Hinton; Nitish Srivastava; Kevin Swersky. "The momentum method".*Coursera*. Retrieved 2 October 2018. Part of a lecture series for the Coursera online course Neural Networks for Machine Learning.

## Sources[edit]

- Avriel, Mordecai (2003).
*Nonlinear Programming: Analysis and Methods*. Courier Corporation. ISBN 978-0-486-43227-4. - Snyman, Jan A.; Wilke, Daniel N. (2018),
*Practical Mathematical Optimization - Basic Optimization Theory and Gradient-Based Algorithms*, Springer Optimization and Its Applications Vol. 133 (2 ed.), Springer, pp. xxvi+372, ISBN 978-3-319-77585-2. (Python module pmo.py) - Homod, Raad Z.; Sahari, Khairul Salleh Mohamed; Almurib, Haider A. F.; Nagi, Farrukh Hafiz (2012-06-01). "Gradient auto-tuned Takagi–Sugeno Fuzzy Forward control of a HVAC system using predicted mean vote index".
*Energy and Buildings*.**49**(6): 254–267. doi:10.1016/j.enbuild.2012.02.013. - Cauchy, Augustin (1847).
*Méthode générale pour la résolution des systèmes d'équations simultanées*. pp. 536–538.