Python中不同维度的矩阵相乘

2024-09-30 14:19:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要使用单值分解在Python中反转以下矩阵,并且我需要将这些矩阵相乘以获得初始矩阵以供确认。当矩阵有不同的维数时,我怎么做

   X_b= [[array([2.52390408]), array([2.4962137]), array([2.46467486]), array([2.48760957])], [array([2.52390408]), array([2.4962137]), array([2.46467486]), array([2.48760957])]]

我使用了命令

svd=linalg.svd(x_b, full_matrices=True, compute_uv=True, hermitian=False)

结果是

a=svd[0]

a =[[ 0.50615947 -0.50060626 -0.49428127 -0.49888074]
  [ 0.50060626  0.83361215 -0.16428559 -0.16581433]
  [ 0.49428127 -0.16428559  0.8377901  -0.16371932]
  [ 0.49888074 -0.16581433 -0.16371932  0.83475721]]]

b=svd[1]

b= [[4.98638127]
 [4.98638127]]

c=svd[2]

c= [[[1.]]

 [[1.]]]

Tags: 命令falsetrue矩阵arrayuvfullsvd
1条回答
网友
1楼 · 发布于 2024-09-30 14:19:48

numpy.linalg.svd的文档页面中,说明了如何使用svd的返回值重构输入矩阵:

linalg.svd(a, full_matrices=True, compute_uv=True, hermitian=False)

Parameters:

  • a (…, M, N) array_like
    A real or complex array with a.ndim >= 2.

Returns:

  • u { (…, M, M), (…, M, K) } array
    Unitary array(s). The first a.ndim - 2 dimensions have the same size as those of the input a. The size of the last two dimensions depends on the value of full_matrices. Only returned when compute_uv is True.
  • s (…, K) array
    Vector(s) with the singular values, within each vector sorted in descending order. The first a.ndim - 2 dimensions have the same size as those of the input a.
  • vh { (…, N, N), (…, K, N) } array
    Unitary array(s). The first a.ndim - 2 dimensions have the same size as those of the input a. The size of the last two dimensions depends on the value of full_matrices. Only returned when compute_uv is True.

[...] When a is a 2D array, it is factorized as u @ np.diag(s) @ vh = (u * s) @ vh, where u and vh are 2D unitary arrays and s is a 1D array of a’s singular values. When a is higher-dimensional, SVD is applied in stacked mode [...].


您可以根据您的用例调整给定的示例:

>>> X_b = np.array([[[2.52390408], [2.4962137], [2.46467486], [2.48760957]],
                    [[2.52390408], [2.4962137], [2.46467486], [2.48760957]]])

>>> u, s, vh = np.linalg.svd(X_b[...,0], full_matrices=True)
>>> u.shape, s.shape, vh.shape
((2, 2), (2,), (4, 4))

重建X_b

>>> (u * s) @ vh[:2,:]
array([[2.52390408, 2.4962137 , 2.46467486, 2.48760957],
       [2.52390408, 2.4962137 , 2.46467486, 2.48760957]])

>>> np.allclose((u * s) @ vh[:2,:], X_b[...,0])
True

相关问题 更多 >