Python 求解procrustes问题的线性投影矩阵
我有两个矩阵:Python 求解procrustes问题的线性投影矩阵,python,matrix,scipy,procrustes,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]]) 我想创建一个转换矩阵,将源矩阵投影到目标矩阵
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)
根据报告,它说:
因此,mtx2
是投影矩阵
如果我有另一个数据,我想使用Scipy用来将源矩阵投影到目标矩阵的“学习变换矩阵”,将它们投影到目标矩阵,该怎么办
如何使用Scipy执行此操作?您需要修改函数以返回转换矩阵(
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
资料来源:Thanx@serafeim,这就是我要找的。最后一个问题,如何将mtx2矩阵返回到源形状?
mtx2_proj=np.dot(mtx2,R.T)
somtx2=np.dot(mtx2_proj,R)
而不添加/s?我问你是因为我注意到,当我像你那样做的时候,我得到了与原来的“相似”,但标准化为零(因为代码的第一步是规范化)。对不起,是的。您需要重命名代码中的mtx2
,因为在应用规范化时它会被覆盖。