求解投影问题的线性投影矩阵

时间:2019-09-04 13:15:35

标签: python matrix scipy procrustes

我有两个矩阵:

target = np.array([[1, 1, 1, 1, 1],
               [2, 2, 2, 2, 2],
               [3, 3, 3, 3, 3]])

source = np.array([[11, 11, 11, 11, 11],
               [22, 22, 22, 22, 22],
               [33, 33, 33, 33, 33]])

,我想创建一个转换矩阵,将矩阵投影到目标上。

我发现Scipy库提供了执行此操作的功能:

from scipy.spatial import procrustes
mtx1, mtx2, disparity = procrustes(target, source)

基于documentation,它表示:

enter image description here

因此,mtx2是投影矩阵。

如果我还有其他数据,并且想使用Scipy用来将矩阵投影到目标矩阵的“学习的转换矩阵”,将它们投影到目标矩阵,该怎么办? 目标一个?

如何使用Scipy?

1 个答案:

答案 0 :(得分:1)

您需要修改函数才能返回转换矩阵(R)。

删除注释后的源代码 如下:

def procrustes(data1, data2):
    mtx1 = np.array(data1, dtype=np.double, copy=True)
    mtx2 = np.array(data2, dtype=np.double, copy=True)

    if mtx1.ndim != 2 or mtx2.ndim != 2:
        raise ValueError("Input matrices must be two-dimensional")
    if mtx1.shape != mtx2.shape:
        raise ValueError("Input matrices must be of same shape")
    if mtx1.size == 0:
        raise ValueError("Input matrices must be >0 rows and >0 cols")

    # translate all the data to the origin
    mtx1 -= np.mean(mtx1, 0)
    mtx2 -= np.mean(mtx2, 0)

    norm1 = np.linalg.norm(mtx1)
    norm2 = np.linalg.norm(mtx2)

    if norm1 == 0 or norm2 == 0:
        raise ValueError("Input matrices must contain >1 unique points")

    # change scaling of data (in rows) such that trace(mtx*mtx') = 1
    mtx1 /= norm1
    mtx2 /= norm2

    # transform mtx2 to minimize disparity
    R, s = orthogonal_procrustes(mtx1, mtx2)
    mtx2 = np.dot(mtx2, R.T) * s    # HERE, the projected mtx2 is estimated.

    # measure the dissimilarity between the two datasets
    disparity = np.sum(np.square(mtx1 - mtx2))

    return mtx1, mtx2, disparity, R

来源:https://github.com/scipy/scipy/blob/v1.3.0/scipy/spatial/_procrustes.py#L17-L132