pytorch 实现施密特正交化

对于一个给定的pytorch张量,如果想要对这里面的每一个行向量进行施密特正交化,可以使用下面的代码:

import numpy as np
from sympy.matrices import Matrix, GramSchmidt
import torch
import torch.nn.functional as F

def orthogo_tensor(x):
    m, n = x.size()
    x_np = x.t().numpy()
    matrix = [Matrix(col) for col in x_np.T]
    gram = GramSchmidt(matrix)
    ort_list = []
    for i in range(m):
        vector = []
        for j in range(n):
            vector.append(float(gram[i][j]))
        ort_list.append(vector)
    ort_list = np.mat(ort_list)
    ort_list = torch.from_numpy(ort_list)
    ort_list = F.normalize(ort_list,dim=1)
    return ort_list

x = torch.randn(4,6)
x = orthogo_tensor(x)
print(x)
print(x.matmul(x.t()))

程序运行结果如下所示:

tensor([[-0.1633,  0.5601, -0.6081, -0.2640, -0.4215, -0.2061],
        [ 0.0386, -0.0236, -0.0674,  0.4131, -0.5576,  0.7154],
        [-0.3210,  0.6896,  0.5430, -0.1018,  0.1794,  0.2898],
        [-0.3445, -0.3674,  0.3962, -0.5217, -0.5563, -0.0886]],
       dtype=torch.float64)
tensor([[ 1.0000e+00, -3.6843e-09,  1.5446e-08, -7.1455e-08],
        [-3.6843e-09,  1.0000e+00, -2.1965e-08, -3.5087e-08],
        [ 1.5446e-08, -2.1965e-08,  1.0000e+00, -2.0042e-07],
        [-7.1455e-08, -3.5087e-08, -2.0042e-07,  1.0000e+00]],
       dtype=torch.float64)
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值