一、torch.norm函數(shù)
torch.norm函數(shù)是PyTorch庫中的一個標(biāo)量計算函數(shù),用于在給定維度上計算輸入張量的范數(shù)(also known as vector length or magnitude)。
常用的張量范數(shù)有L1范數(shù)和L2范數(shù),torch.norm默認(rèn)使用L2范數(shù),可以通過norm_type參數(shù)指定L1范數(shù)。
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函數(shù)用于從給定的均值和標(biāo)準(zhǔn)差中生成指定大小的正態(tài)分布(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函數(shù)
torch.normal函數(shù)的參數(shù)包括:均值mean和標(biāo)準(zhǔn)差std,以及生成隨機數(shù)的張量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參數(shù),torch.norm還可以針對兩個張量進(jìn)行計算。
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)
五、小結(jié)
在本文中,我們學(xué)習(xí)了如何使用torch.norm函數(shù)來計算張量的范數(shù)并了解了其常用的參數(shù)norm_type和dim。此外,我們還介紹了torch.normal函數(shù)用于從正態(tài)分布中生成隨機數(shù)據(jù)的方法。