Pytorch实现n个向量的归一化

一、需求

        一个张量,有n个向量,我要做的是对这每个向量都除以它自己的模(这个模就是范数,可以是L1范数或者L2范数)。如下:

二、具体实现

        代码:

import torch
import torch.nn as nn
import torch.nn.functional as F

# suppose n=10, then there are 10 vectors in a tensor, 
# and each vector has 3 dimension
n_vectors = torch.zeros(10, 3)
# initialize each vectors randomly
n_vectors=nn.init.uniform_(tensor=n_vectors, a=-5, b=5)
print(n_vectors)
# use official normalization method of pytorch
n_vectors = F.normalize(n_vectors, p=2, dim=1)
print(n_vectors)

        输出:

tensor([[ 3.4124,  0.0452, -1.3099],
        [-0.9727, -0.0567,  3.2670],
        [-0.9700,  4.8445, -0.5155],
        [-2.4775, -3.6286, -4.6726],
        [ 0.1190, -1.6225, -3.9567],
        [ 3.5483, -4.6952, -3.9193],
        [ 3.4525, -4.3136, -1.3532],
        [ 3.2062,  0.8937, -1.3886],
        [ 2.5678,  2.5092, -4.6496],
        [ 4.5103, -2.0436, -0.7519]])
tensor([[ 0.9335,  0.0124, -0.3583],
        [-0.2853, -0.0166,  0.9583],
        [-0.1953,  0.9752, -0.1038],
        [-0.3863, -0.5657, -0.7285],
        [ 0.0278, -0.3793, -0.9249],
        [ 0.5018, -0.6640, -0.5543],
        [ 0.6069, -0.7583, -0.2379],
        [ 0.8890,  0.2478, -0.3850],
        [ 0.4371,  0.4271, -0.7915],
        [ 0.9005, -0.4080, -0.1501]])

        备注:

        0.9335=3.4124/math.sqrt(3.4124×3.4124+0.0452×0.0452+(-1.3099)×(-1.3099))
        0.0124=0.0452/math.sqrt(3.4124×3.4124+0.0452×0.0452+(-1.3099)×(-1.3099))
        -0.3583=-1.3099/math.sqrt(3.4124×3.4124+0.0452×0.0452+(-1.3099)×(-1.3099))

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

飞机火车巴雷特

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值