一、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函數用於從正態分布中生成隨機數據的方法。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/257202.html