Return the least-squares solution to a linear matrix equation using QR decomposition. Solves the equation `a x = b` by computing a vector `x` that minimizes the Euclidean 2-norm `|| b - a x ||^2`. The equation may be under-, well-, or over- determined (i.e., the number of
(a, b)
| 1398 | |
| 1399 | |
| 1400 | def lstsq(a, b): |
| 1401 | """ |
| 1402 | Return the least-squares solution to a linear matrix equation using |
| 1403 | QR decomposition. |
| 1404 | |
| 1405 | Solves the equation `a x = b` by computing a vector `x` that |
| 1406 | minimizes the Euclidean 2-norm `|| b - a x ||^2`. The equation may |
| 1407 | be under-, well-, or over- determined (i.e., the number of |
| 1408 | linearly independent rows of `a` can be less than, equal to, or |
| 1409 | greater than its number of linearly independent columns). If `a` |
| 1410 | is square and of full rank, then `x` (but for round-off error) is |
| 1411 | the "exact" solution of the equation. |
| 1412 | |
| 1413 | Parameters |
| 1414 | ---------- |
| 1415 | a : (M, N) array_like |
| 1416 | "Coefficient" matrix. |
| 1417 | b : {(M,), (M, K)} array_like |
| 1418 | Ordinate or "dependent variable" values. If `b` is two-dimensional, |
| 1419 | the least-squares solution is calculated for each of the `K` columns |
| 1420 | of `b`. |
| 1421 | |
| 1422 | Returns |
| 1423 | ------- |
| 1424 | x : {(N,), (N, K)} Array |
| 1425 | Least-squares solution. If `b` is two-dimensional, |
| 1426 | the solutions are in the `K` columns of `x`. |
| 1427 | residuals : {(1,), (K,)} Array |
| 1428 | Sums of residuals; squared Euclidean 2-norm for each column in |
| 1429 | ``b - a*x``. |
| 1430 | If `b` is 1-dimensional, this is a (1,) shape array. |
| 1431 | Otherwise the shape is (K,). |
| 1432 | rank : Array |
| 1433 | Rank of matrix `a`. |
| 1434 | s : (min(M, N),) Array |
| 1435 | Singular values of `a`. |
| 1436 | """ |
| 1437 | q, r = qr(a) |
| 1438 | x = solve_triangular(r, q.T.conj().dot(b)) |
| 1439 | residuals = b - a.dot(x) |
| 1440 | residuals = abs(residuals**2).sum(axis=0, keepdims=b.ndim == 1) |
| 1441 | |
| 1442 | token = tokenize(a, b) |
| 1443 | |
| 1444 | # r must be a triangular with single block |
| 1445 | |
| 1446 | # rank |
| 1447 | rname = "lstsq-rank-" + token |
| 1448 | rdsk = {(rname,): (np.linalg.matrix_rank, (r.name, 0, 0))} |
| 1449 | graph = HighLevelGraph.from_collections(rname, rdsk, dependencies=[r]) |
| 1450 | # rank must be an integer |
| 1451 | rank = Array(graph, rname, shape=(), chunks=(), dtype=int) |
| 1452 | |
| 1453 | # singular |
| 1454 | sname = "lstsq-singular-" + token |
| 1455 | rt = r.T.conj() |
| 1456 | sdsk = { |
| 1457 | (sname, 0): ( |
nothing calls this directly
no test coverage detected