pytorch / 1.8.0 / generated / torch.lstsq.html /

torch.lstsq

torch.lstsq(input, A, *, out=None) → Tensor

Computes the solution to the least squares and least norm problems for a full rank matrix A A of size ( m × n ) (m \times n) and a matrix B B of size ( m × k ) (m \times k) .

If m n m \geq n , lstsq() solves the least-squares problem:

min X A X B 2 . \begin{array}{ll} \min_X & \|AX-B\|_2. \end{array}

If m < n m < n , lstsq() solves the least-norm problem:

min X X 2 subject to A X = B . \begin{array}{ll} \min_X & \|X\|_2 & \text{subject to} & AX = B. \end{array}

Returned tensor X X has shape ( max ( m , n ) × k ) (\max(m, n) \times k) . The first n n rows of X X contains the solution. If m n m \geq n , the residual sum of squares for the solution in each column is given by the sum of squares of elements in the remaining m n m - n rows of that column.

Note

The case when m < n m < n is not supported on the GPU.

Parameters
  • input (Tensor) – the matrix B B
  • A (Tensor) – the m m by n n matrix A A
Keyword Arguments

out (tuple, optional) – the optional destination tensor

Returns

A namedtuple (solution, QR) containing:

  • solution (Tensor): the least squares solution
  • QR (Tensor): the details of the QR factorization
Return type

(Tensor, Tensor)

Note

The returned matrices will always be transposed, irrespective of the strides of the input matrices. That is, they will have stride (1, m) instead of (m, 1).

Example:

>>> A = torch.tensor([[1., 1, 1],
...                   [2, 3, 4],
...                   [3, 5, 2],
...                   [4, 2, 5],
...                   [5, 4, 3]])
>>> B = torch.tensor([[-10., -3],
...                   [ 12, 14],
...                   [ 14, 12],
...                   [ 16, 16],
...                   [ 18, 16]])
>>> X, _ = torch.lstsq(B, A)
>>> X
tensor([[  2.0000,   1.0000],
        [  1.0000,   1.0000],
        [  1.0000,   2.0000],
        [ 10.9635,   4.8501],
        [  8.9332,   5.2418]])

© 2019 Torch Contributors
Licensed under the 3-clause BSD License.
https://pytorch.org/docs/1.8.0/generated/torch.lstsq.html