---
title: "Mahout 系列之----共轭梯度"
author: "thd52java"
date: "2013-11-09T12:11:10Z"
tags: []
categories: ["互联网"]
slug: "mahout"
draft: false
lastmod: "2013-11-09T12:11:10Z"
id: 1973360
url: "https://thd52java.iteye.com/blog/1973360"
---

**无预处理共轭梯度**

 

 

 

要求解线性方程组 ![\boldsymbol{Ax}=\boldsymbol{b}](http://upload.wikimedia.org/math/c/7/2/c7225d6e652b64f0acdd0dffc6c44c8e.png)，稳定双共轭梯度法从初始解 ![\boldsymbol{x}_0](http://upload.wikimedia.org/math/9/8/0/980f3ec9a50adbbffd502a361a649dca.png) 开始按以下步骤迭代：

 

1. ![\boldsymbol{r}_0=\boldsymbol{b}-\boldsymbol{Ax}](http://upload.wikimedia.org/math/1/d/e/1de72cd675a91ac0add8fc5211b6537f.png)
2. 任意选择向量 ![\boldsymbol{\hat{r}}_0\;](http://upload.wikimedia.org/math/3/4/5/345aceca104a6339b38cf007d0f0b8ab.png) 使得 ![(\boldsymbol{\hat{r}}_0,\boldsymbol{r}_0) \neq0\;](http://upload.wikimedia.org/math/3/f/c/3fc5a46b6857c9f366144a322d8c67f5.png)，例如，![\boldsymbol{\hat{r}}_0=\boldsymbol{r}_0\;](http://upload.wikimedia.org/math/1/6/6/166c47cff9ea5cac834d2358b3dc3041.png)
3. ![\rho_0=\alpha=\omega_0=1\;](http://upload.wikimedia.org/math/0/3/5/03533e45ed5f441f8a2cdb00740a6beb.png)
4. ![\boldsymbol{v}_0=\boldsymbol{p}_0=\boldsymbol{0}](http://upload.wikimedia.org/math/0/5/4/0543c9b11324ec60d22a26d3867fcbc0.png)
5. 对 ![i=1,2,3,\ldots](http://upload.wikimedia.org/math/3/8/1/3811e78644ca48d898bc8de8dba39d38.png)
   
   01. ![\rho_i=(\boldsymbol{\hat{r}}_0,\boldsymbol{r}_{i-1})\;](http://upload.wikimedia.org/math/c/1/8/c18b19fce9d3bb2f42afad6d054f543c.png)
   02. ![\beta=(\rho_i/\rho_{i-1})(\alpha/\omega_{i-1})\;](http://upload.wikimedia.org/math/9/2/4/924b0499f9375a464adac46a4552717f.png)
   03. ![\boldsymbol{p}_i=\boldsymbol{r}_{i-1}+\beta(\boldsymbol{p}_{i-1}-\omega_{i-1}\boldsymbol{v}_{i-1})](http://upload.wikimedia.org/math/9/e/9/9e9a3c6e84198aea9bc3ee2ad81c2b9e.png)
   04. ![\boldsymbol{v}_i=\boldsymbol{Ap}_i](http://upload.wikimedia.org/math/0/3/8/0382e865a8e13ccedc36e6d1d2249675.png)
   05. ![\alpha=\rho_i/(\boldsymbol{\hat{r}}_0,\boldsymbol{v}_i)\;](http://upload.wikimedia.org/math/1/d/6/1d6464dd080abed6733776895ec51274.png)
   06. ![\boldsymbol{s}=\boldsymbol{r}_{i-1}-\alpha\boldsymbol{v}_i](http://upload.wikimedia.org/math/6/a/9/6a938f8eab67d67702b6746b94b5f5ce.png)
   07. ![\boldsymbol{t}=\boldsymbol{As}](http://upload.wikimedia.org/math/5/8/1/58126b7f2e8058319823647580feecc1.png)
   08. ![\omega_i=(\boldsymbol{t},\boldsymbol{s})/(\boldsymbol{t},\boldsymbol{t})](http://upload.wikimedia.org/math/7/b/3/7b33fdb007318f9c16bd488febe4571b.png)
   09. ![\boldsymbol{x}_i=\boldsymbol{x}_{i-1}+\alpha\boldsymbol{p}_i+\omega_i\boldsymbol{s}](http://upload.wikimedia.org/math/0/a/2/0a22f406e7fbf3c8858f0a00ed8c7178.png)
   10. 若 ![\boldsymbol{x}_i](http://upload.wikimedia.org/math/6/e/c/6ecd473b82c65efe68e9fdc8b0db60cd.png) 足够精确则退出
   11. ![\boldsymbol{r}_i=\boldsymbol{s}-\omega_i\boldsymbol{t}](http://upload.wikimedia.org/math/0/d/d/0dd5f7222061d9b456f93eb44390f234.png)

 

**预处理共轭梯度**

 

预处理通常被用来加速迭代方法的收敛。要使用预处理子 ![\boldsymbol{K}=\boldsymbol{K}_1\boldsymbol{K}_2\approx\boldsymbol{A}](http://upload.wikimedia.org/math/1/3/1/131d801d84dbbe2879074747f4923508.png) 来求解线性方程组 ![\boldsymbol{Ax}=\boldsymbol{b}](http://upload.wikimedia.org/math/c/7/2/c7225d6e652b64f0acdd0dffc6c44c8e.png)，预处理稳定双共轭梯度法从初始解 ![\boldsymbol{x}_0](http://upload.wikimedia.org/math/9/8/0/980f3ec9a50adbbffd502a361a649dca.png) 开始按以下步骤迭代：

 

1. ![\boldsymbol{r}_0=\boldsymbol{b}-\boldsymbol{Ax}](http://upload.wikimedia.org/math/1/d/e/1de72cd675a91ac0add8fc5211b6537f.png)
2. 任意选择向量 ![\boldsymbol{\hat{r}}_0\;](http://upload.wikimedia.org/math/3/4/5/345aceca104a6339b38cf007d0f0b8ab.png) 使得 ![(\boldsymbol{\hat{r}}_0,\boldsymbol{r}_0) \neq0\;](http://upload.wikimedia.org/math/3/f/c/3fc5a46b6857c9f366144a322d8c67f5.png)，例如，![\boldsymbol{\hat{r}}_0=\boldsymbol{r}_0\;](http://upload.wikimedia.org/math/1/6/6/166c47cff9ea5cac834d2358b3dc3041.png)
3. ![\rho_0=\alpha=\omega_0=1\;](http://upload.wikimedia.org/math/0/3/5/03533e45ed5f441f8a2cdb00740a6beb.png)
4. ![\boldsymbol{v}_0=\boldsymbol{p}_0=\boldsymbol{0}](http://upload.wikimedia.org/math/0/5/4/0543c9b11324ec60d22a26d3867fcbc0.png)
5. 对 ![i=1,2,3,\ldots](http://upload.wikimedia.org/math/3/8/1/3811e78644ca48d898bc8de8dba39d38.png)
   
   01. ![\rho_i=(\boldsymbol{\hat{r}}_0,\boldsymbol{r}_{i-1})\;](http://upload.wikimedia.org/math/c/1/8/c18b19fce9d3bb2f42afad6d054f543c.png)
   02. ![\beta=(\rho_i/\rho_{i-1})(\alpha/\omega_{i-1})\;](http://upload.wikimedia.org/math/9/2/4/924b0499f9375a464adac46a4552717f.png)
   03. ![\boldsymbol{p}_i=\boldsymbol{r}_{i-1}+\beta(\boldsymbol{p}_{i-1}-\omega_{i-1}\boldsymbol{v}_{i-1})](http://upload.wikimedia.org/math/9/e/9/9e9a3c6e84198aea9bc3ee2ad81c2b9e.png)
   04. ![\boldsymbol{y}=\boldsymbol{K}^{-1}\boldsymbol{p}_i](http://upload.wikimedia.org/math/3/7/5/3752c83ecf4c431deff8781df73f109b.png)
   05. ![\boldsymbol{v}_i=\boldsymbol{Ay}](http://upload.wikimedia.org/math/2/a/7/2a78027ab8a043ae01985496b4accf74.png)
   06. ![\alpha=\rho_i/(\boldsymbol{\hat{r}}_0,\boldsymbol{v}_i)\;](http://upload.wikimedia.org/math/1/d/6/1d6464dd080abed6733776895ec51274.png)
   07. ![\boldsymbol{s}=\boldsymbol{r}_i-\alpha\boldsymbol{v}_i](http://upload.wikimedia.org/math/0/e/9/0e9d0ac70db90fc35a7124848dcbca39.png)
   08. ![\boldsymbol{z}=\boldsymbol{As}](http://upload.wikimedia.org/math/0/9/b/09b3da9f5fafbb950f6d842a3f63e62e.png)
   09. ![\boldsymbol{t}=\boldsymbol{K}^{-1}\boldsymbol{z}](http://upload.wikimedia.org/math/1/6/9/1692b0962269e3fdf9f5662fb89204b3.png)
   10. ![\omega_i=(\boldsymbol{K}_1^{-1}\boldsymbol{t},\boldsymbol{K}_1^{-1}\boldsymbol{s})/(\boldsymbol{K}_1^{-1}\boldsymbol{s},\boldsymbol{K}_1^{-1}\boldsymbol{s})](http://upload.wikimedia.org/math/2/e/6/2e6f1f0041855c495670e243d86d0472.png)
   11. ![\boldsymbol{x}_i=\boldsymbol{x}_{i-1}+\alpha\boldsymbol{y}+\omega_i\boldsymbol{z}](http://upload.wikimedia.org/math/d/a/c/dacc59feffd72f5f63432c063450bec2.png)
   12. 若 ![\boldsymbol{x}_i](http://upload.wikimedia.org/math/6/e/c/6ecd473b82c65efe68e9fdc8b0db60cd.png) 足够精确则退出
   13. ![\boldsymbol{r}_i=\boldsymbol{s}-\omega_i\boldsymbol{t}](http://upload.wikimedia.org/math/0/d/d/0dd5f7222061d9b456f93eb44390f234.png)

 

这个形式等价于将无预处理的稳定双共轭梯度法应用于显式预处理后的方程组

 

![\boldsymbol{\tilde{A}\tilde{x}}=\boldsymbol{\tilde{b}}](http://upload.wikimedia.org/math/f/5/d/f5d18eca16467761580efa06023fc970.png)，

 

其中 ![\boldsymbol{\tilde{A}}=\boldsymbol{K}_1^{-1}\boldsymbol{AK}_2^{-1}](http://upload.wikimedia.org/math/d/8/6/d86f90063e5ad8d3ceb43c6109de0084.png)，![\boldsymbol{\tilde{x}}=\boldsymbol{K}_2\boldsymbol{x}](http://upload.wikimedia.org/math/c/f/a/cfaa0d497e0eca9705a3642b29dce013.png)，![\boldsymbol{\tilde{b}}=\boldsymbol{K}_1^{-1}\boldsymbol{b}](http://upload.wikimedia.org/math/9/d/7/9d7f4be12a9d9559088299efb0fa2595.png)。换句话说，左预处理和右预处理都可以通过这个形式实施。

 

**Mahout 分布式共轭梯度实现：**

 

package org.apache.mahout.math.solver;

 

import org.apache.mahout.math.CardinalityException;  
import org.apache.mahout.math.DenseVector;  
import org.apache.mahout.math.Vector;  
import org.apache.mahout.math.VectorIterable;  
import org.apache.mahout.math.function.Functions;  
import org.apache.mahout.math.function.PlusMult;  
import org.slf4j.Logger;  
import org.slf4j.LoggerFactory;

 

/\**  
 * &lt;p&gt;Implementation of a conjugate gradient iterative solver for linear systems. Implements both  
 * standard conjugate gradient and pre-conditioned conjugate gradient.  
 *  
 * &lt;p&gt;Conjugate gradient requires the matrix A in the linear system Ax = b to be symmetric and positive  
 * definite. For convenience, this implementation allows the input matrix to be be non-symmetric, in  
 * which case the system A'Ax = b is solved. Because this requires only one pass through the matrix A, it  
 * is faster than explictly computing A'A, then passing the results to the solver.  
 *  
 * &lt;p&gt;For inputs that may be ill conditioned (often the case for highly sparse input), this solver  
 * also accepts a parameter, lambda, which adds a scaled identity to the matrix A, solving the system  
 * (A + lambda\*I)x = b. This obviously changes the solution, but it will guarantee solvability. The  
 * ridge regression approach to linear regression is a common use of this feature.  
 *  
 * &lt;p&gt;If only an approximate solution is required, the maximum number of iterations or the error threshold  
 * may be specified to end the algorithm early at the expense of accuracy. When the matrix A is ill conditioned,  
 * it may sometimes be necessary to increase the maximum number of iterations above the default of A.numCols()  
 * due to numerical issues.  
 *  
 * &lt;p&gt;By default the solver will run a.numCols() iterations or until the residual falls below 1E-9.  
 *  
 * &lt;p&gt;For more information on the conjugate gradient algorithm, see Golub & van Loan, "Matrix Computations",  
 * sections 10.2 and 10.3 or the &lt;a href="[http://en.wikipedia.org/wiki/Conjugate\_gradient"&gt;conjugate](http://en.wikipedia.org/wiki/Conjugate_gradient%27%3Econjugate) gradient  
 * wikipedia article&lt;/a&gt;.  
 \*/

 

public class ConjugateGradientSolver {

 

  public static final double DEFAULT\_MAX\_ERROR = 1.0e-9;  
   
  private static final Logger log = LoggerFactory.getLogger(ConjugateGradientSolver.class);  
  private static final PlusMult PLUS\_MULT = new PlusMult(1.0);

 

  private int iterations;  
  private double residualNormSquared;  
   
  public ConjugateGradientSolver() {  
    this.iterations = 0;  
    this.residualNormSquared = Double.NaN;  
  } 

 

  /\**  
   * Solves the system Ax = b with default termination criteria. A must be symmetric, square, and positive definite.  
   * Only the squareness of a is checked, since testing for symmetry and positive definiteness are too expensive. If  
   * an invalid matrix is specified, then the algorithm may not yield a valid result.  
   *   
   * @param a  The linear operator A.  
   * @param b  The vector b.  
   * @return The result x of solving the system.  
   * @throws IllegalArgumentException if a is not square or if the size of b is not equal to the number of columns of a.  
   *  
   \*/  
  public Vector solve(VectorIterable a, Vector b) {  
    return solve(a, b, null, b.size(), DEFAULT\_MAX\_ERROR);  
  }  
   
  /\**  
   * Solves the system Ax = b with default termination criteria using the specified preconditioner. A must be  
   * symmetric, square, and positive definite. Only the squareness of a is checked, since testing for symmetry  
   * and positive definiteness are too expensive. If an invalid matrix is specified, then the algorithm may not  
   * yield a valid result.  
   *   
   * @param a  The linear operator A.  
   * @param b  The vector b.  
   * @param precond A preconditioner to use on A during the solution process.  
   * @return The result x of solving the system.  
   * @throws IllegalArgumentException if a is not square or if the size of b is not equal to the number of columns of a.  
   *  
   \*/  
  public Vector solve(VectorIterable a, Vector b, Preconditioner precond) {  
    return solve(a, b, precond, b.size(), DEFAULT\_MAX\_ERROR);  
  }  
 

 

  /\**  
   * Solves the system Ax = b, where A is a linear operator and b is a vector. Uses the specified preconditioner  
   * to improve numeric stability and possibly speed convergence. This version of solve() allows control over the  
   * termination and iteration parameters.  
   *  
   * @param a  The matrix A.  
   * @param b  The vector b.  
   * @param preconditioner The preconditioner to apply.  
   * @param maxIterations The maximum number of iterations to run.  
   * @param maxError The maximum amount of residual error to tolerate. The algorithm will run until the residual falls  
   * below this value or until maxIterations are completed.  
   * @return The result x of solving the system.  
   * @throws IllegalArgumentException if the matrix is not square, if the size of b is not equal to the number of  
   * columns of A, if maxError is less than zero, or if maxIterations is not positive.  
   \*/  
  

 

 

 

// 共轭梯度实现的主题部分。很明显该方法是既可以用预处理的方式，也可以不用预处理的方式。Mahout中提供了单机模式的雅克比预处理，但是没有提供分布式处理的雅克比预处理，这个需要自己写。很简单，只要将对角线元素去倒数，组成一个对角阵即可。  
  public Vector solve(VectorIterable a,  
                      Vector b,  
                      Preconditioner preconditioner,  
                      int maxIterations,  
                      double maxError) {

 

    if (a.numRows() != a.numCols()) {  
      throw new IllegalArgumentException("Matrix must be square, symmetric and positive definite.");  
    }  
     
    if (a.numCols() != b.size()) {  
      throw new CardinalityException(a.numCols(), b.size());  
    }

 

    if (maxIterations &lt;= 0) {  
      throw new IllegalArgumentException("Max iterations must be positive.");       
    }  
     
    if (maxError &lt; 0.0) {  
      throw new IllegalArgumentException("Max error must be non-negative.");  
    }  
     
    Vector x = new DenseVector(b.size());

 

    iterations = 0;  
    Vector residual = b.minus(a.times(x));  
    residualNormSquared = residual.dot(residual);

 

    log.info("Conjugate gradient initial residual norm = {}", Math.sqrt(residualNormSquared));  
    double previousConditionedNormSqr = 0.0;  
    Vector updateDirection = null;  
    while (Math.sqrt(residualNormSquared) &gt; maxError && iterations &lt; maxIterations) {  
      Vector conditionedResidual;  
      double conditionedNormSqr;  
      if (preconditioner == null) {  
        conditionedResidual = residual;  
        conditionedNormSqr = residualNormSquared;  
      } else {  
        conditionedResidual = preconditioner.precondition(residual);  
        conditionedNormSqr = residual.dot(conditionedResidual);  
      }       
       
      ++iterations;  
       
      if (iterations == 1) {  
        updateDirection = new DenseVector(conditionedResidual);  
      } else {  
        double beta = conditionedNormSqr / previousConditionedNormSqr;  
         
        // updateDirection = residual + beta * updateDirection  
        updateDirection.assign(Functions.MULT, beta);  
        updateDirection.assign(conditionedResidual, Functions.PLUS);  
      }  
       
      Vector aTimesUpdate = a.times(updateDirection);  
       
      double alpha = conditionedNormSqr / updateDirection.dot(aTimesUpdate);  
       
      // x = x + alpha * updateDirection  
      PLUS\_MULT.setMultiplicator(alpha);  
      x.assign(updateDirection, PLUS\_MULT);

 

      // residual = residual - alpha * A * updateDirection  
      PLUS\_MULT.setMultiplicator(-alpha);  
      residual.assign(aTimesUpdate, PLUS\_MULT);  
       
      previousConditionedNormSqr = conditionedNormSqr;  
      residualNormSquared = residual.dot(residual);  
       
      log.info("Conjugate gradient iteration {} residual norm = {}", iterations, Math.sqrt(residualNormSquared));  
    }  
    return x;  
  }

 

  /\**  
   * Returns the number of iterations run once the solver is complete.  
   *  
   * @return The number of iterations run.  
   \*/  
  public int getIterations() {  
    return iterations;  
  }

 

  /\**  
   * Returns the norm of the residual at the completion of the solver. Usually this should be close to zero except in  
   * the case of a non positive definite matrix A, which results in an unsolvable system, or for ill conditioned A, in  
   * which case more iterations than the default may be needed.  
   *  
   * @return The norm of the residual in the solution.  
   \*/  
  public double getResidualNorm() {  
    return Math.sqrt(residualNormSquared);  
  }   
}

 

 

 

 

DistributedConjugateGradientSolver  是上CG的扩展，DCG和CG的区别在于，DCG矩阵和向量相乘时需要MR实现矩阵相乘。