如何在 python numpy 中创建随机正交矩阵

新手上路,请多包涵

有没有一种方法可以调用来在 python 中创建随机正交矩阵?可能使用 numpy?或者有没有办法使用多种 numpy 方法创建正交矩阵?谢谢。

原文由 Dacion 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.6k
2 个回答

这是从 https://github.com/scipy/scipy/pull/5622/files 中提取的 rvs 方法,变化很小 - 足以作为独立的 numpy 函数运行。

 import numpy as np

def rvs(dim=3):
     random_state = np.random
     H = np.eye(dim)
     D = np.ones((dim,))
     for n in range(1, dim):
         x = random_state.normal(size=(dim-n+1,))
         D[n-1] = np.sign(x[0])
         x[0] -= D[n-1]*np.sqrt((x*x).sum())
         # Householder transformation
         Hx = (np.eye(dim-n+1) - 2.*np.outer(x, x)/(x*x).sum())
         mat = np.eye(dim)
         mat[n-1:, n-1:] = Hx
         H = np.dot(H, mat)
         # Fix the last sign such that the determinant is 1
     D[-1] = (-1)**(1-(dim % 2))*D.prod()
     # Equivalent to np.dot(np.diag(D), H) but faster, apparently
     H = (D*H.T).T
     return H

它符合 Warren 的测试, https://stackoverflow.com/a/38426572/901925

原文由 hpaulj 发布,翻译遵循 CC BY-SA 3.0 许可协议

scipy 的 0.18 版有 scipy.stats.ortho_groupscipy.stats.special_ortho_group 。添加它的拉取请求是 https://github.com/scipy/scipy/pull/5622

例如,

 In [24]: from scipy.stats import ortho_group  # Requires version 0.18 of scipy

In [25]: m = ortho_group.rvs(dim=3)

In [26]: m
Out[26]:
array([[-0.23939017,  0.58743526, -0.77305379],
       [ 0.81921268, -0.30515101, -0.48556508],
       [-0.52113619, -0.74953498, -0.40818426]])

In [27]: np.set_printoptions(suppress=True)

In [28]: m.dot(m.T)
Out[28]:
array([[ 1.,  0., -0.],
       [ 0.,  1.,  0.],
       [-0.,  0.,  1.]])

原文由 Warren Weckesser 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题