Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Steepest descent spitting out unreasonably large values

My implementation of steepest descent for solving Ax = b is showing some weird behavior: for any matrix large enough (~10 x 10, have only tested square matrices so far), the returned x contains all huge values (on the order of 1x10^10).

def steepestDescent(A, b, numIter=100, x=None):
    """Solves Ax = b using steepest descent method"""
    warnings.filterwarnings(action="error",category=RuntimeWarning)

    # Reshape b in case it has shape (nL,)
    b = b.reshape(len(b), 1)

    exes = []
    res = []

    # Make a guess for x if none is provided
    if x==None:
        x = np.zeros((len(A[0]), 1))
        exes.append(x)

    for i in range(numIter):
        # Re-calculate r(i) using r(i) = b - Ax(i) every five iterations
        # to prevent roundoff error. Also calculates initial direction
        # of steepest descent.
        if (numIter % 5)==0:
            r = b - np.dot(A, x)
        # Otherwise use r(i+1) = r(i) - step * Ar(i)
        else:
            r = r - step * np.dot(A, r)

        res.append(r)

        # Calculate step size. Catching the runtime warning allows the function
        # to stop and return before all iterations are completed. This is
        # necessary because once the solution x has been found, r = 0, so the
        # calculation below divides by 0, turning step into "nan", which then
        # goes on to overwrite the correct answer in x with "nan"s
        try:
            step = np.dot(r.T, r) / np.dot( np.dot(r.T, A), r )
        except RuntimeWarning:
            warnings.resetwarnings()
            return x
        # Update x
        x = x + step * r
        exes.append(x)

    warnings.resetwarnings()
    return x, exes, res

(exes and res are returned for debugging)

I assume the problem must be with calculating r or step (or some deeper issue) but I can't make out what it is.

like image 343
Cole Zimmerman Avatar asked Jul 26 '16 15:07

Cole Zimmerman


1 Answers

The code seems correct. For example, the following test work for me (both linalg.solve and steepestDescent give the close answer, most of the time):

import numpy as np

n = 100
A = np.random.random(size=(n,n)) + 10 * np.eye(n)
print(np.linalg.eig(A)[0])
b = np.random.random(size=(n,1))
x, xs, r = steepestDescent(A,b, numIter=50)
print(x - np.linalg.solve(A,b))

The problem is in the math. This algorithm is guaranteed to converge to the correct solution if A is positive definite matrix. By adding the 10 * identity matrix to a random matrix, we increase the probability that all the eigen-values are positive

If you test with large random matrices (for example A = random.random(size=(n,n)), you are almost certain to have a negative eigenvalue, and the algorithm will not converge.

like image 104
Eolmar Avatar answered Nov 09 '22 16:11

Eolmar