mindspore.scipy

Warning

These are experimental APIs that are subject to change or deletion. Only support Linux.

Scipy-like interfaces in mindspore.

mindspore.scipy.linalg

Linear algebra submodule

mindspore.scipy.linalg.block_diag(*arrs)[source]

Create a block diagonal matrix from provided arrays.

Given the list of Tensors A, B, and C, the output will have these Tensors arranged on the diagonal:

[[A, 0, 0],
 [0, B, 0],
 [0, 0, C]]

Note

block_diag is not supported on Windows platform yet.

Parameters:

arrs (list) – up to 2-D Input Tensors. One or more Tensors, the dimension of Tensors should be 0-D, 1-D or 2-D.

Returns:

Tensor with A, B, C, … on the diagonal which has the same dtype as A.

Raises:

ValueError – If there are Tensors with dimensions higher than 2 in all arguments.

Supported Platforms:

GPU CPU

Examples

>>> import numpy as onp
>>> from mindspore import Tensor
>>> from mindspore.scipy.linalg import block_diag
>>> A = Tensor(onp.array([[1, 0], [0, 1]]))
>>> B = Tensor(onp.array([[3, 4, 5], [6, 7, 8]]))
>>> C = Tensor(onp.array([[7]]))
>>> P = Tensor(onp.zeros((2, ), dtype='int32'))
>>> print(block_diag(A, B, C))
[[1 0 0 0 0 0]
 [0 1 0 0 0 0]
 [0 0 3 4 5 0]
 [0 0 6 7 8 0]
 [0 0 0 0 0 7]]
>>> print(block_diag(A, P, B, C))
[[1 0 0 0 0 0 0 0]
 [0 1 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0]
 [0 0 0 0 3 4 5 0]
 [0 0 0 0 6 7 8 0]
 [0 0 0 0 0 0 0 7]]
mindspore.scipy.linalg.cho_factor(a, lower=False, overwrite_a=False, check_finite=True)[source]

Compute the cholesky decomposition of a matrix, to use in mindspore.scipy.linalg.cho_solve().

Returns the cholesky decomposition of a Hermitian positive-definite matrix A. Based on the value of lower, perform the following decomposition:

  • when lower is True: \(A = L L^*\)

  • when lower is False: \(A = U^* U\)

\(L^*\) is a conjugate transpose matrix of \(L\). \(U^*\) is a conjugate transpose matrix of \(U\).

The return value can be directly used as the first parameter to mindspore.scipy.linalg.cho_solve().

Note

  • cho_factor is not supported on Windows platform yet.

  • Only float32, float64, int32, int64 are supported Tensor dtypes.

  • If Tensor with dtype int32 or int64 is passed, it will be cast to mstype.float64.

Warning

The returned matrix also contains random data in the entries not used by the cholesky decomposition. If you need to zero these entries, use the function cholesky instead.

Parameters:
  • a (Tensor) – square Matrix of \((M,M)\) to be decomposed.

  • lower (bool, optional) – Whether to compute the upper or lower triangular cholesky factorization. Default: False .

  • overwrite_a (bool, optional) – Whether to overwrite data in a (may improve performance). Default: False . In MindSpore, this arg does not work right now.

  • check_finite (bool, optional) – Whether to check that the input matrix contains only finite numbers. Disabling may give a performance gain, but may result in problems (crashes, non-termination) if the inputs do contain infinities or NaNs. Default: True . In MindSpore, this arg does not work right now.

Returns:

  • Tensor, matrix whose upper or lower triangle contains the cholesky factor of a. Other parts of the matrix contain random data.

  • bool, flag indicating whether the factor is in the lower or upper triangle

Raises:

ValueError – If input a tensor is not a square matrix or its dims are not equal to 2D.

Supported Platforms:

GPU CPU

Examples

>>> import numpy as onp
>>> from mindspore import Tensor
>>> from mindspore.scipy.linalg import cho_factor
>>> a = Tensor(onp.array([[9, 3, 1, 5], [3, 7, 5, 1], [1, 5, 9, 2], [5, 1, 2, 6]]).astype(onp.float32))
>>> c, low = cho_factor(a)
>>> print(c)
[[ 3.          1.          0.33333334  1.6666666 ]
 [ 3.          2.4494898   1.9051585  -0.2721655 ]
 [ 1.          5.          2.2933078   0.8559526 ]
 [ 5.          1.          2.          1.5541857 ]]
mindspore.scipy.linalg.cho_solve(c_and_lower, b, overwrite_b=False, check_finite=True)[source]

Given the cholesky factorization of \(A\), solve the linear equation.

\[A x = b\]

Note

  • cho_solve is not supported on Windows platform yet.

  • Only float32, float64, int32, int64 are supported Tensor dtypes.

  • If Tensor with dtype int32 or int64 is passed, it will be cast to mstype.float64.

Parameters:
  • c_and_lower ((Tensor, bool)) – cholesky factorization of \(a\), as given by mindspore.scipy.linalg.cho_factor().

  • b (Tensor) – Right-hand side.

  • overwrite_b (bool, optional) – Whether to overwrite data in \(b\) (may improve performance). Default: False.

  • check_finite (bool, optional) – Whether to check that the input matrices contain only finite numbers. Disabling may give a performance gain, but may result in problems (crashes, non-termination) if the inputs do contain infinities or NaNs. Default: True.

Returns:

Tensor, the solution to the system \(A x = b\).

Supported Platforms:

GPU CPU

Examples

>>> import numpy as onp
>>> import mindspore as ms
>>> a = ms.Tensor(onp.array([[9, 3, 1, 5], [3, 7, 5, 1], [1, 5, 9, 2], [5, 1, 2, 6]]).astype(onp.float32))
>>> b = ms.Tensor(onp.array([1, 1, 1, 1]).astype(onp.float32))
>>> c, low = ms.scipy.linalg.cho_factor(a)
>>> x = ms.scipy.linalg.cho_solve((c, low), b)
>>> print(x)
[-0.01749266  0.11953348  0.01166185  0.15743434]
mindspore.scipy.linalg.cholesky(a, lower=False, overwrite_a=False, check_finite=True)[source]

Compute the cholesky decomposition of a matrix.

Returns the cholesky decomposition of a Hermitian positive-definite matrix A. Based on the value of lower, perform the following decomposition:

  • when lower is True: \(A = L L^*\)

  • when lower is False: \(A = U^* U\)

\(L^*\) is a conjugate transpose matrix of L. \(U^*\) is a conjugate transpose matrix of U.

Note

  • cholesky is not supported on the Windows platform yet.

  • Only float32, float64, int32, int64 are supported Tensor dtypes.

  • If Tensor with dtype int32 or int64 is passed, it will be cast to mstype.float64.

Parameters:
  • a (Tensor) – square Matrix of \((M, M)\) to be decomposed.

  • lower (bool, optional) – Whether to compute the upper- or lower-triangular cholesky factorization. Default: False .

  • overwrite_a (bool, optional) – Whether to overwrite data in a (may improve performance). Default: False . in MindSpore, this arg does not work right now.

  • check_finite (bool, optional) – Whether to check that the input matrix contains only finite numbers. Disabling may give a performance gain, but may result in problems (crashes, non-termination) if the inputs do contain infinities or NaNs. Default: True . in MindSpore, this arg does not work right now.

Returns:

Tensor, upper- or lower-triangular cholesky factor of a.

Raises:

ValueError – If the input tensor is not a square matrix or it's dims not equal to 2D.

Supported Platforms:

GPU CPU

Examples

>>> import numpy as onp
>>> from mindspore import Tensor
>>> from mindspore.scipy.linalg import cholesky
>>> a = Tensor(onp.array([[1, 2],[2, 5]]).astype(onp.float32))
>>> L = cholesky(a, lower=True)
>>> print(L)
[[1. 0.]
 [2. 1.]]
mindspore.scipy.linalg.eigh(a, b=None, lower=True, eigvals_only=False, overwrite_a=False, overwrite_b=False, turbo=True, eigvals=None, type=1, check_finite=True)[source]

Solve a standard or generalized eigenvalue problem for a complex Hermitian or real symmetric matrix.

Find eigenvalues Tensor w and optionally eigenvectors Tensor v of Tensor a, where b is positive definite such that for every eigenvalue λ (i-th entry of w) and its eigenvector vi (i-th column of v) satisfies:

              a @ vi = λ * b @ vi
vi.conj().T @ a @ vi = λ
vi.conj().T @ b @ vi = 1

In the standard problem, b is assumed to be the identity matrix.

Note

  • eigh is not supported on Windows platform yet.

  • Only float32, float64, int32, int64 are supported Tensor dtypes.

  • If Tensor with dtype int32 or int64 is passed, it will be cast to mstype.float64.

Parameters:
  • a (Tensor) – A \((M, M)\) complex Hermitian or real symmetric matrix whose eigenvalues and eigenvectors will be computed.

  • b (Tensor, optional) – A \((M, M)\) complex Hermitian or real symmetric positive definite matrix. If omitted, identity matrix is assumed. Default: None.

  • lower (bool, optional) – Whether the pertinent Tensor data is taken from the lower or upper triangle of a and, if applicable, b. Default: True.

  • eigvals_only (bool, optional) – Whether to calculate only eigenvalues and no eigenvectors. Default: False .

  • overwrite_a (bool, optional) – Whether to overwrite data in a (may improve performance). Default: False .

  • overwrite_b (bool, optional) – Whether to overwrite data in b (may improve performance). Default: False .

  • turbo (bool, optional) – Use divide and conquer algorithm (faster but expensive in memory, only for generalized eigenvalue problem and if full set of eigenvalues are requested). Has no significant effect if eigenvectors are not requested. Default: True .

  • eigvals (tuple, optional) – Indexes of the smallest and largest (in ascending order) eigenvalues and corresponding eigenvectors to be returned: \(0 <= lo <= hi <= M-1\). If omitted, all eigenvalues and eigenvectors are returned. Default: None .

  • type (int, optional) –

    For the generalized problems, this keyword specifies the problem type to be solved for w and v (only takes 1, 2, 3 as possible inputs):

    1 =>     a @ v = w @ b @ v
    2 => a @ b @ v = w @ v
    3 => b @ a @ v = w @ v
    

    This keyword is ignored for standard problems. Default: 1 .

  • check_finite (bool, optional) – Whether to check that the input matrices contain only finite numbers. Disabling may give a performance gain, but may result in problems (crashes, non-termination) if the inputs do contain infinities or NaNs. Default: True .

Returns:

  • Tensor with shape \((N,)\), the \(N (1<=N<=M)\) selected eigenvalues, in ascending order, each repeated according to its multiplicity.

  • Tensor with shape \((M, N)\), if eigvals_only == False.

Raises:
  • RuntimeError – If eigenvalue computation does not converge, an error occurred, or b matrix is not positive definite. Note that if input matrices are not symmetric or Hermitian, no error will be reported but results will be wrong.

  • TypeError – If a is not Tensor.

  • TypeError – If lower is not bool.

  • TypeError – If eigvals_only is not bool.

  • TypeError – If overwrite_a is not bool.

  • TypeError – If overwrite_b is not bool.

  • TypeError – If turbo is not bool.

  • TypeError – If check_finite is not bool.

  • ValueError – If a is not 2D square matrix.

  • ValueError – If b is not None.

  • ValueError – If eigvals is not None.

Supported Platforms:

GPU CPU

Examples

>>> import numpy as onp
>>> import mindspore.numpy as mnp
>>> from mindspore import Tensor, dtype
>>> from mindspore.scipy.linalg import eigh
>>> a = Tensor([[6, 3, 1, 5], [3, 0, 5, 1], [1, 5, 6, 2], [5, 1, 2, 2]], dtype.float64)
>>> w, v = eigh(a)
>>> print(onp.allclose(mnp.dot(a, v).asnumpy(), mnp.dot(v, mnp.diag(w)).asnumpy(), 1e-5, 1e-8))
True
mindspore.scipy.linalg.inv(a, overwrite_a=False, check_finite=True)[source]

Compute the inverse of a matrix.

Note

  • inv is not supported on Windows platform yet.

  • Only float32, float64, int32, int64 are supported Tensor dtypes.

  • If Tensor with dtype int32 or int64 is passed, it will be cast to mstype.float64.

Parameters:
  • a (Tensor) – Square matrix to be inverted.

  • overwrite_a (bool, optional) – Discard data in a (may improve performance). Default: False .

  • check_finite (bool, optional) – Whether to check that the input matrix contains only finite numbers. Disabling may give a performance gain, but may result in problems (crashes, non-termination) if the inputs do contain infinities or NaNs. Default: True .

Returns:

Tensor, inverse of the matrix a.

Raises:
  • LinAlgError – If \(a\) is singular.

  • ValueError – If \(a\) is not square, or not 2D.

Supported Platforms:

GPU CPU

Examples

>>> import numpy as onp
>>> from mindspore import Tensor
>>> import mindspore.numpy as mnp
>>> from mindspore.scipy.linalg import inv
>>> a = Tensor(onp.array([[1., 2.], [3., 4.]]))
>>> print(inv(a))
[[-2.   1. ]
 [ 1.5 -0.5]]
>>> print(mnp.dot(a, inv(a)))
[[1.0000000e+00 0.0000000e+00]
 [8.8817842e-16 1.0000000e+00]]
mindspore.scipy.linalg.lstsq(A, B, rcond=None, driver=None)[source]

Computes a solution to the least squares problem of a system of linear equations \(AX = B\).

Note

  • lstsq is currently only used in mindscience scientific computing scenarios and does not support other usage scenarios.

  • lstsq is not supported on Windows platform yet.

Parameters:
  • A (Tensor) – LHS input tensor of shape \((*, M, N)\), where \(*\) is zero or more batch dimensions.

  • B (Tensor) – RHS input tensor of shape \((*, M, K)\), where \(*\) is zero or more batch dimensions.

  • rcond (number.Number, optional) – Not implemented now, Default is None.

  • driver (str, optional) – Which LAPACK driver is used to solve the least-squares problem. Options are "gels", "gelsy", "gelss", "gelsd". Default is None ("gelsy"). If A is well-conditioned, "gels" is a good choice for full-rank matrix, and "gelsy" for a general matrix. If A is not well-conditioned, "gelsd" works well, "gelss" was used historically. It is generally slow but uses less memory.

Returns:

  • solution (Tensor). Least-squares solution. It has shape \((*, N, K)\), where \(*\) is the same as broadcast batch dimensions.

  • residual (Tensor). Square of the 2-norm for each column in \(AX - B\). It has shape \((*, K)\), where \(*\) is the same as broadcast batch dimensions. It is computed when driver is one of ("gels", "gelss", "gelsd") and \(M > N\) , otherwise, it is an empty tensor.

  • rank (Tensor). Effective rank of A. It has shape \((*)\), where \(*\) is the same as batch dimensions of A. It is computed when driver is one of ("gelsy", "gelss", "gelsd"), otherwise it is an empty tensor.

  • singular_value (Tensor). Singular values of A. It has shape \((*, min(M, N))\), where \(*\) is same as batch dimensions of A. It is computed when driver is one of ("gelss", "gelsd"), otherwise it is an empty tensor.

Raises:
  • TypeError – If dtypes of A and B are not the same.

  • ValueError – If A is less than 2 dimensions.

  • ValueError – If the shapes of A and B are not matched.

  • ValueError – If driver is not in set {None, "gels", "gelsy", "gelss", "gelsd"}.

Supported Platforms:

Ascend CPU

Examples

>>> import numpy as onp
>>> import mindspore
>>> from mindspore import Tensor
>>> from mindspore.scipy.linalg import lstsq
>>> a = Tensor(onp.array([[3, 0, 0, 0], [2, 1, 0, 0], [1, 0, 1, 0], [1, 1, 1, 1]], onp.float32))
>>> b = Tensor(onp.array([3, 1, 3, 4], onp.float32))
>>> solution, residual, rank, singular_value = lstsq(a, b)
>>> print(solution)
[ 1. -1.  2.  2.]
>>> print(a @ solution)  # Check the result
[3. 1. 3. 4.]
mindspore.scipy.linalg.lu(a, permute_l=False, overwrite_a=False, check_finite=True)[source]

Compute pivoted LU decomposition of a general matrix.

The decomposition is:

\[A = P L U\]

where \(P\) is a permutation matrix, \(L\) lower triangular with unit diagonal elements, and \(U\) upper triangular.

Note

  • lu is not supported on Windows platform yet.

  • Only float32, float64, int32, int64 are supported Tensor dtypes.

  • If Tensor with dtype int32 or int64 is passed, it will be cast to mstype.float64.

Parameters:
  • a (Tensor) – a \((M, N)\) matrix to decompose. Note that if the input tensor is not a float, then it will be cast to mstype.float32.

  • permute_l (bool, optional) – Perform the multiplication \(P L\) (Default: do not permute). Default: False .

  • overwrite_a (bool, optional) – Whether to overwrite data in \(a\) (may improve performance). Default: False .

  • check_finite (bool, optional) – Whether to check that the input matrix contains only finite numbers. Disabling may give a performance gain, but may result in problems (crashes, non-termination) if the inputs do contain infinities or NaNs. Default: True .

Returns:

If permute_l == False

  • Tensor, \((M, M)\) permutation matrix.

  • Tensor, \((M, K)\) lower triangular or trapezoidal matrix with unit diagonal. \(K = min(M, N)\).

  • Tensor, \((K, N)\) upper triangular or trapezoidal matrix.

If permute_l == True

  • Tensor, \((M, K)\) permuted L matrix. \(K = min(M, N)\).

  • Tensor, \((K, N)\) upper triangular or trapezoidal matrix.

Supported Platforms:

GPU CPU

Examples

>>> import numpy as onp
>>> from mindspore import Tensor
>>> from mindspore.scipy.linalg import lu
>>> a = Tensor(onp.array([[2, 5, 8, 7], [5, 2, 2, 8], [7, 5, 6, 6], [5, 4, 4, 8]]).astype(onp.float64))
>>> p, l, u = lu(a)
>>> print(p)
[[0 1 0 0]
 [0 0 0 1]
 [1 0 0 0]
 [0 0 1 0]]
>>> print(l)
[[ 1.          0.          0.          0.        ]
 [ 0.2857143   1.          0.          0.        ]
 [ 0.71428573  0.12        1.          0.        ]
 [ 0.71428573 -0.44       -0.46153846  1.        ]]
>>> print(u)
[[ 7.          5.          6.          6.        ]
 [ 0.          3.57142854  6.28571415  5.28571415]
 [ 0.          0.         -1.03999996  3.07999992]
 [ 0.         -0.         -0.          7.46153831]]
mindspore.scipy.linalg.lu_factor(a, overwrite_a=False, check_finite=True)[source]

Compute pivoted LU decomposition of a square matrix, and its outputs can be directly used as the inputs of lu_solve. The decomposition is:

\[a = P L U\]

where \(P\) is a permutation matrix, \(L\) lower triangular with unit diagonal elements, and \(U\) upper triangular.

Note

  • lu_factor is not supported on Windows platform yet.

  • Only float32, float64, int32, int64 are supported Tensor dtypes.

  • If Tensor with dtype int32 or int64 is passed, it will be cast to mstype.float64.

Parameters:
  • a (Tensor) – square matrix of \((M, M)\) to decompose. Note that if the input tensor is not a float, then it will be cast to mstype.float32.

  • overwrite_a (bool, optional) – Whether to overwrite data in \(a\) (may increase performance). Default: False .

  • check_finite (bool, optional) – Whether to check that the input matrix contains only finite numbers. Disabling may give a performance gain, but may result in problems (crashes, non-termination) if the inputs do contain infinities or NaNs. Default: True .

Returns:

  • Tensor, a square matrix of \((M, M)\) containing U in its upper triangle, and L in its lower triangle. The unit diagonal elements of L are not stored.

  • Tensor, \((M,)\) pivot indices representing the permutation matrix P: the i-th element value j in the indices indicates that row i of matrix was interchanged with row j.

Raises:

ValueError – If \(a\) is not 2D square.

Supported Platforms:

GPU CPU

Examples

>>> import numpy as onp
>>> from mindspore import Tensor
>>> from mindspore.scipy.linalg import lu_factor
>>> a = Tensor(onp.array([[2, 5, 8, 7], [5, 2, 2, 8], [7, 5, 6, 6], [5, 4, 4, 8]]).astype(onp.float64))
>>> lu, piv = lu_factor(a)
>>> print(lu)
[[ 7.          5.          6.          6.        ]
 [ 0.28571429  3.57142857  6.28571429  5.28571429]
 [ 0.71428571  0.12       -1.04        3.08      ]
 [ 0.71428571 -0.44       -0.46153846  7.46153846]]
>>> print(piv)
[2 2 3 3]
mindspore.scipy.linalg.solve_triangular(a, b, trans=0, lower=False, unit_diagonal=False, overwrite_b=False, debug=None, check_finite=True)[source]

Solve the linear system \(a x = b\) for x, assuming a is a triangular matrix.

Note

  • solve_triangular is currently only used in mindscience scientific computing scenarios and does not support other usage scenarios.

  • solve_triangular is not supported on Windows platform yet.

Parameters:
  • a (Tensor) – A triangular matrix of shape \((*, M, M)\) where \(*\) is zero or more batch dimensions.

  • b (Tensor) – A Tensor of shape \((*, M)\) or \((*, M, N)\). Right-hand side matrix in \(a x = b\).

  • trans (Union[int, str], optional) –

    Type of system to solve. Default: 0.

    trans

    system

    0 or 'N'

    a x = b

    1 or 'T'

    a^T x = b

    2 or 'C'

    a^H x = b

  • lower (bool, optional) – Use only data contained in the lower triangle of a. Default: False.

  • unit_diagonal (bool, optional) – If True, diagonal elements of \(a\) are assumed to be 1 and will not be referenced. Default: False.

  • overwrite_b (bool, optional) – Not implemented now. Default: False.

  • debug (Any, optional) – Not implemented now. Default: None.

  • check_finite (bool, optional) – Not implemented now. Default: True.

Returns:

Tensor of shape \((*, M)\) or \((*, M, N)\), which is the solution to the system \(a x = b\). Shape of \(x\) matches \(b\).

Raises:
  • ValueError – If a is less than 2 dimensions.

  • ValueError – If a is not square matrix.

  • TypeError – If dtypes of a and b are not the same.

  • ValueError – If the shapes of a and b are not matched.

  • ValueError – If trans is not in set {0, 1, 2, 'N', 'T', 'C'}.

Supported Platforms:

Ascend CPU

Examples

>>> import numpy as onp
>>> import mindspore
>>> from mindspore import Tensor
>>> from mindspore.scipy.linalg import solve_triangular
>>> a = Tensor(onp.array([[3, 0, 0, 0], [2, 1, 0, 0], [1, 0, 1, 0], [1, 1, 1, 1]], onp.float32))
>>> b = Tensor(onp.array([3, 1, 3, 4], onp.float32))
>>> x = solve_triangular(a, b, lower=True, unit_diagonal=False, trans='N')
>>> print(x)
[ 1. -1.  2.  2.]
>>> print(a @ x)  # Check the result
[3. 1. 3. 4.]

API Name

Description

Supported Platforms

mindspore.scipy.linalg.block_diag

Create a block diagonal matrix from provided arrays.

GPU CPU

mindspore.scipy.linalg.cho_factor

Compute the cholesky decomposition of a matrix, to use in mindspore.scipy.linalg.cho_solve().

GPU CPU

mindspore.scipy.linalg.cho_solve

Given the cholesky factorization of \(A\), solve the linear equation.

GPU CPU

mindspore.scipy.linalg.cholesky

Compute the cholesky decomposition of a matrix.

GPU CPU

mindspore.scipy.linalg.eigh

Solve a standard or generalized eigenvalue problem for a complex Hermitian or real symmetric matrix.

GPU CPU

mindspore.scipy.linalg.inv

Compute the inverse of a matrix.

GPU CPU

mindspore.scipy.linalg.lstsq

Computes a solution to the least squares problem of a system of linear equations \(AX = B\).

Ascend CPU

mindspore.scipy.linalg.lu

Compute pivoted LU decomposition of a general matrix.

GPU CPU

mindspore.scipy.linalg.lu_factor

Compute pivoted LU decomposition of a square matrix, and its outputs can be directly used as the inputs of lu_solve.

GPU CPU

mindspore.scipy.linalg.solve_triangular

Solve the linear system \(a x = b\) for x, assuming a is a triangular matrix.

Ascend CPU

mindspore.scipy.optimize

Optimize submodule

Inexact line search that satisfies strong Wolfe conditions.

Algorithm 3.5 from Wright and Nocedal, 'Numerical Optimization', 1999, pg. 59-61

Note

line_search is not supported on Windows platform yet.

Parameters:
  • f (function) – function of the form f(x) where x is a flat Tensor and returns a real scalar. The function should be composed of operations with vjp defined.

  • xk (Tensor) – initial guess.

  • pk (Tensor) – direction to search in. Assumes the direction is a descent direction.

  • jac (function) – the gradient function at x where x is a flat Tensor and returns a Tensor. The function can be None if you want to use automatic credits.

  • gfk (Tensor) – initial value of value_and_gradient at position. Default: None .

  • old_fval (Tensor) – The same as gfk. Default: None .

  • old_old_fval (Tensor) – unused argument, only for scipy API compliance. Default: None .

  • c1 (float) – Wolfe criteria constant, see ref. Default: 1e-4 .

  • c2 (float) – The same as c1. Default: 0.9 .

  • maxiter (int) – maximum number of iterations to search. Default: 20 .

Returns:

LineSearchResults, results of line search.

Supported Platforms:

GPU CPU

Examples

>>> import numpy as onp
>>> from mindspore.scipy.optimize import line_search
>>> from mindspore import Tensor
>>> x0 = Tensor(onp.ones(2).astype(onp.float32))
>>> p0 = Tensor(onp.array([-1, -1]).astype(onp.float32))
>>> def func(x):
...     return x[0] ** 2 - x[1] ** 3
>>> res = line_search(func, x0, p0)
>>> print(res.a_k)
1.0
mindspore.scipy.optimize.linear_sum_assignment(cost_matrix, maximize, dimension_limit=Tensor(sys.maxsize))[source]

Solve the linear sum assignment problem.

The assignment problem is represented as follows:

\[min\sum_{i}^{} \sum_{j}^{} C_{i,j} X_{i,j}\]

where \(C\) is cost matrix, \(X_{i,j} = 1\) means column \(j\) is assigned to row \(i\) .

Parameters:
  • cost_matrix (Tensor) – 2-D cost matrix. Tensor of shape \((M, N)\) .

  • maximize (bool) – Calculate a maximum weight matching if true, otherwise calculate a minimum weight matching.

  • dimension_limit (Tensor, optional) – A scalar used to limit the actual size of the 2nd dimension of cost_matrix. Default is Tensor(sys.maxsize), which means no limitation. The type is 0-D int64 Tensor.

Returns:

A tuple of tensors containing 'row_idx' and 'col_idx'.

  • row_idx (Tensor) - Row indices of the problem. If dimension_limit is given, -1 would be padded at the end. The shape is \((N, )\) , where \(N\) is the minimum value of cost_matrix dimension.

  • col_idx (Tensor) - Column indices of the problem. If dimension_limit is given, -1 would be padded at the end. The shape is \((N, )\) , where \(N\) is the minimum value of cost_matrix dimension.

Raises:
  • TypeError – If the data type of cost_matrix is not the type in [float16, float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64, bool]

  • TypeError – If the type of maximize is not bool.

  • TypeError – If the data type of dimension_limit is not int64.

  • ValueError – If the rank of cost_matrix is not 2.

Supported Platforms:

Ascend CPU

Examples

>>> import mindspore as ms
>>> import numpy as np
>>> from mindspore import Tensor
>>> import mindspore.scipy.optimize.linear_sum_assignment as lsap
>>> cost_matrix = Tensor(np.array([[2, 3, 3], [3, 2, 3], [3, 3, 2]])).astype(ms.float64)
>>> dimension_limit = Tensor(2)
>>> maximize = False
>>> a, b = lsap(cost_matrix, maximize, dimension_limit)
>>> print(a)
[0 1 -1]
>>> print(b)
[0 1 -1]
>>> a, b = lsap(cost_matrix, maximize)
>>> print(a)
[0 1 2]
>>> print(b)
[0 1 2]
mindspore.scipy.optimize.minimize(func, x0, args=(), method=None, jac=None, hess=None, hessp=None, bounds=None, constraints=(), tol=None, callback=None, options=None)[source]

Minimization of scalar function of one or more variables.

This API for this function matches SciPy with some minor deviations:

  • Gradients of func are calculated automatically using MindSpore's autodiff support when the value of jac is None.

  • The method argument is required. An exception will be thrown if you don't specify a solver.

  • Various optional arguments "hess", "hessp", "bounds", "constraints", "tol", "callback" in the SciPy interface have not yet been implemented.

  • Optimization results may differ from SciPy due to differences in the line search implementation.

Note

  • minimize does not yet support differentiation or arguments in the form of multi-dimensional Tensor, but support for both is planned.

  • minimize is not supported on Windows platform yet.

  • LAGRANGE method is only supported on "GPU".

Parameters:
  • func (Callable) – the objective function to be minimized, \(fun(x, *args) -> float\), where x is a 1-D array with shape \((n,)\) and args is a tuple of the fixed parameters needed to completely specify the function. fun must support differentiation if jac is None.

  • x0 (Tensor) – initial guess. Array of real elements of size \((n,)\), where n is the number of independent variables.

  • args (Tuple) – extra arguments passed to the objective function. Default: () .

  • method (str) – solver type. Should be one of "BFGS" and "LBFGS", "LAGRANGE".

  • jac (Callable, optional) – method for computing the gradient vector. Only for "BFGS" and "LBFGS". if it is None, the gradient will be estimated with gradient of func. if it is a callable, it should be a function that returns the gradient vector: \(jac(x, *args) -> array\_like, shape (n,)\) where x is an array with shape \((n,)\) and args is a tuple with the fixed parameters.

  • hess (Callable, optional) – Method for calculating the Hessian Matrix. Not implemented yet.

  • hessp (Callable, optional) – Hessian of objective function times an arbitrary vector p. Not implemented yet.

  • bounds (Sequence, optional) – Sequence of (min, max) pairs for each element in x. Not implemented yet.

  • constraints (Callable, optional) – representing the inequality constraints, each function in constraints indicates the function < 0 as an inequality constrain.

  • tol (float, optional) – tolerance for termination. For detailed control, use solver-specific options. Default: None .

  • callback (Callable, optional) – A callable called after each iteration. Not implemented yet.

  • options (Mapping[str, Any], optional) –

    a dictionary of solver options. All methods accept the following generic options. Default: None .

    • history_size (int): size of buffer used to help to update inv hessian, only used with method="LBFGS". Default: 20 .

    • maxiter (int): Maximum number of iterations to perform. Depending on the method each iteration may use several function evaluations.

    The follow options are exclusive to Lagrange method:

    • save_tol (list): list of saving tolerance, with the same length with 'constraints'.

    • obj_weight (float): weight for objective function, usually between 1.0 - 100000.0.

    • lower (Tensor): lower bound constrain for variables, must have same shape with x0.

    • upper (Tensor): upper bound constrain for variables, must have same shape with x0.

    • learning_rate (float): learning rate for each Adam step.

    • coincide_func (Callable): sub-function representing the common parts between objective function and constraints to avoid redundant computation.

    • rounds (int): times to update Lagrange multipliers.

    • steps (int): steps to apply Adam per round.

    • log_sw (bool): whether to print the loss at each step.

Returns:

OptimizeResults, object holding optimization results.

Supported Platforms:

GPU CPU

Examples

>>> import numpy as onp
>>> from mindspore.scipy.optimize import minimize
>>> from mindspore import Tensor
>>> x0 = Tensor(onp.zeros(2).astype(onp.float32))
>>> def func(p):
...     x, y = p
...     return (x ** 2 + y - 11.) ** 2 + (x + y ** 2 - 7.) ** 2
>>> res = minimize(func, x0, method='BFGS', options=dict(maxiter=None, gtol=1e-6))
>>> print(res.x)
[3. 2.]
>>> l_res = minimize(func, x0, method='LBFGS', options=dict(maxiter=None, gtol=1e-6))
>>> print(l_res.x)
[3. 2.]

API Name

Description

Supported Platforms

mindspore.scipy.optimize.line_search

Inexact line search that satisfies strong Wolfe conditions.

GPU CPU

mindspore.scipy.optimize.linear_sum_assignment

Solve the linear sum assignment problem.

Ascend CPU

mindspore.scipy.optimize.minimize

Minimization of scalar function of one or more variables.

GPU CPU