Retrieving number of iterations that ran for spars

2019-05-10 11:55发布

How to retrieve how many iterations ran to achieve specified tolerance level in SciPy sparse linear system solvers?

2条回答
欢心
2楼-- · 2019-05-10 12:26

The solvers support a callback keyword argument that gets called after every iteration. So you could do something like this:

def solve_sparse(A, b):
  num_iters = 0

  def callback(xk):
    num_iters += 1

  # call the solver on your data
  return scipy.sparse.linalg.cg(A, b, callback=callback)[0]
查看更多
Summer. ? 凉城
3楼-- · 2019-05-10 12:31

For Python 3, the following works:

    def solve_sparse(A, b):
      num_iters = 0

      def callback(xk):
         nonlocal num_iters
         num_iters+=1

      x,status=scipy.sparse.linalg.cg(A, b,tol=1e-15, callback=callback)
      return x,status,num_iters
查看更多
登录 后发表回答