numpy/scipy 中最小二乘拟合的多个系数集

Multiple coefficient sets for least squares fitting in numpy/scipy

有没有办法在 numpy.linalg.lstsq or scipy.linalg.lstsq 中对不同的系数矩阵执行多个同时(但不相关)的最小二乘拟合?例如,这是一个简单的线性拟合,我希望能够使用不同的 x 值但使用相同的 y 值。目前,我必须写一个循环:

x = np.arange(12.0).reshape(4, 3)
y = np.arange(12.0, step=3.0)
m = np.stack((x, np.broadcast_to(1, x.shape)), axis=0)

fit = np.stack(tuple(np.linalg.lstsq(w, y, rcond=-1)[0] for w in m), axis=-1)

这导致一组具有相同斜率和不同截距的拟合,使得 fit[n] 对应于系数 m[n]

线性最小二乘法不是一个很好的例子,因为它是可逆的,并且两个函数都可以选择多个 y 值。但是,它足以说明我的观点。

理想情况下,我想将其扩展到 ab 的任何 "broadcastable" 组合,其中 a.shape[-2] == b.shape[0] 完全相同,并且最后一个维度必须匹配或者是一个(或失踪)。我并没有真正挂断 a 的哪个维度代表不同的矩阵:将它作为第一个缩短循环很方便。

numpy 或 scipy 中是否有内置方法来避免 Python 循环?我对使用 lstsq 而不是手动转置、乘法和求逆矩阵非常感兴趣。

您可以将 scipy.sparse.linalg.lsqrscipy.sparse.block_diag 一起使用。我只是不确定它会更快。

示例:

>>> import numpy as np
>>> from scipy.sparse import block_diag
>>> from scipy.sparse import linalg as sprsla
>>> 
>>> x = np.random.random((3,5,4))
>>> y = np.random.random((3,5))
>>> 
>>> for A, b in zip(x, y):
...     print(np.linalg.lstsq(A, b))
... 
(array([-0.11536962,  0.22575441,  0.03597646,  0.52014899]), array([0.22232195]), 4, array([2.27188101, 0.69355384, 0.63567141, 0.21700743]))
(array([-2.36307163,  2.27693405, -1.85653264,  3.63307554]), array([0.04810252]), 4, array([2.61853881, 0.74251282, 0.38701194, 0.06751288]))
(array([-0.6817038 , -0.02537582,  0.75882223,  0.03190649]), array([0.09892803]), 4, array([2.5094637 , 0.55673403, 0.39252624, 0.18598489]))
>>> 
>>> sprsla.lsqr(block_diag(x), y.ravel())
(array([-0.11536962,  0.22575441,  0.03597646,  0.52014899, -2.36307163,
        2.27693405, -1.85653264,  3.63307554, -0.6817038 , -0.02537582,
        0.75882223,  0.03190649]), 2, 15, 0.6077437777160813, 0.6077437777160813, 6.226368324510392, 106.63227777368986, 1.3277892240815807e-14, 5.36589277249043, array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]))