全国旗舰校区

不同学习城市 同样授课品质

北京

深圳

上海

广州

郑州

大连

武汉

成都

西安

杭州

青岛

重庆

长沙

哈尔滨

南京

太原

沈阳

合肥

贵阳

济南

下一个校区
就在你家门口
+
当前位置:首页  >  技术干货

torch.norm函数详解

发布时间:2023-11-23 15:06:51
发布人:xqq

一、torch.norm函数

torch.norm函数是PyTorch库中的一个标量计算函数,用于在给定维度上计算输入张量的范数(also known as vector length or magnitude)。

常用的张量范数有L1范数和L2范数,torch.norm默认使用L2范数,可以通过norm_type参数指定L1范数。


import torch

# 1D Tensor
a = torch.tensor([1, 2, 3, 4, 5])
print(torch.norm(a))       # output: tensor(7.4162)
print(torch.norm(a, 1))    # output: tensor(15.)
print(torch.norm(a, float('inf'))) # output: tensor(5.)

# 2D Tensor
b = torch.tensor([[1, 2, 3], [4, 5, 6]])
print(torch.norm(b))       # output: tensor(9.5394)
print(torch.norm(b, 1))    # output: tensor(15.)
print(torch.norm(b, float('inf'))) # output: tensor(15.)

二、torch.normal什么意思

在PyTorch中,torch.normal函数用于从给定的均值和标准差中生成指定大小的正态分布(Gaussian distribution)样本值的Tensor。

对于一个mxn的Tensor,输出的Tensor尺寸为mxn的且每个元素(i,j)都是从N(mean(i,j), std(i,j))中随机取样的值。


import torch

# generate 1D tensor with normal distribution
torch.manual_seed(0)
mean = torch.zeros(3)
std = torch.ones(3)
normal_samples = torch.normal(mean, std)
print(normal_samples)    # output: tensor([ 1.5410, -0.2934, -2.1788])

# generate 2D tensor with normal distribution
torch.manual_seed(0)
mean = torch.zeros(3, 2)
std = torch.ones(3, 2)
normal_samples = torch.normal(mean, std)
print(normal_samples)    # output: tensor([[ 1.5410, -0.2934],
                                        [-2.8200,  0.5285],
                                        [ 0.5802,  0.5422]])

三、torch.normal函数

torch.normal函数的参数包括:均值mean和标准差std,以及生成随机数的张量size。


import torch

mean = torch.arange(1., 5.)
std = torch.arange(1, 2)
size = (2, 2)

normal_samples = torch.normal(mean, std, size)
print(normal_samples)    # output: tensor([[ 1.4611,  1.9118],
                                        [ 2.0693,  4.1555]])

四、torch.norm 两个张量

除了norm_type和dim参数,torch.norm还可以针对两个张量进行计算。


import torch

a = torch.tensor([1, 2, 3])
b = torch.tensor([4, 5, 6])

# calculate L2 norm of two tensors
print(torch.norm(a-b, p=2))    # output: tensor(5.1962)

# calculate Frobenius norm of two matrices
c = torch.tensor([[1, 2], [3, 4]])
d = torch.tensor([[5, 6], [7, 8]])
print(torch.norm(c-d))    # output: tensor(8.0000)

五、小结

在本文中,我们学习了如何使用torch.norm函数来计算张量的范数并了解了其常用的参数norm_type和dim。此外,我们还介绍了torch.normal函数用于从正态分布中生成随机数据的方法。

torch.normal

相关文章

linux 线程 cpu,linuxcpu线程

linux 线程 cpu,linuxcpu线程

2023-11-23
格式代码出现两次原因及解决办法

格式代码出现两次原因及解决办法

2023-11-23
s3dis详解:从特点到应用

s3dis详解:从特点到应用

2023-11-23
okhttp下载文件用法介绍

okhttp下载文件用法介绍

2023-11-23

最新文章

武汉新媒体行业公司排名

武汉新媒体行业公司排名

2023-11-01
武汉新媒体就业现状好吗

武汉新媒体就业现状好吗

2023-11-01
武汉全媒体行业发展现状及趋势

武汉全媒体行业发展现状及趋势

2023-10-31
武汉全媒体现状

武汉全媒体现状

2023-10-31
在线咨询 免费试学 教程领取