如何在 PyTorch 中歸一化張量?
在 TensorFlow 中,PyTorch 的 張量 可以使用 **torch.nn.functional** 模組提供的 **normalize()** 函式進行歸一化。這是一個非線性啟用函式。
它對給定張量在指定維度上執行 **Lp 歸一化**。
它返回原始張量元素的歸一化值張量。
一維張量可以在維度 0 上歸一化,而二維張量可以在維度 0 和 1 上歸一化,即列方向或行方向。
n 維張量可以在維度 (0, 1, 2,..., n-1) 上歸一化。
語法
torch.nn.functional.normalize(input, p=2.0, dim = 1)
引數
**輸入** – 輸入張量
**p** – 範數公式中的冪 (指數) 值
**dim** – 對其元素進行歸一化的維度。
步驟
我們可以使用以下步驟來歸一化張量:
匯入 **torch** 庫。確保你已安裝它。
import torch from torch.nn.functional import normalize
建立一個張量並列印它。
t = torch.tensor([[1.,2.,3.],[4.,5.,6.]])
print("Tensor:", t)使用不同的 p 值和不同的維度對張量進行歸一化。上面定義的張量是一個二維張量,因此我們可以對其進行兩個維度的歸一化。
t1 = normalize(t, p=1.0, dim = 1) t2 = normalize(t, p=2.0, dim = 0)
列印上面計算出的歸一化張量。
print("Normalized tensor:
", t1)
print("Normalized tensor:
", t2)示例 1
# import torch library
import torch
from torch.nn.functional import normalize
# define a torch tensor
t = torch.tensor([1., 2., 3., -2., -5.])
# print the above tensor
print("Tensor:
", t)
# normalize the tensor
t1 = normalize(t, p=1.0, dim = 0)
t2 = normalize(t, p=2.0, dim = 0)
# print normalized tensor
print("Normalized tensor with p=1:
", t1)
print("Normalized tensor with p=2:
", t2)輸出
Tensor: tensor([ 1., 2., 3., -2., -5.]) Normalized tensor with p=1: tensor([ 0.0769, 0.1538, 0.2308, -0.1538, -0.3846]) Normalized tensor with p=2: tensor([ 0.1525, 0.3050, 0.4575, -0.3050, -0.7625])
示例 2
# import torch library
import torch
from torch.nn.functional import normalize
# define a 2D tensor
t = torch.tensor([[1.,2.,3.],[4.,5.,6.]])
# print the above tensor
print("Tensor:
", t)
# normalize the tensor
t0 = normalize(t, p=2.0)
# print the normalized tensor
print("Normalized tensor:
", t0)
# normalize the tensor in dim 0 or column-wise
tc = normalize(t, p=2.0, dim = 0)
# print the normalized tensor
print("Column-wise Normalized tensor:
", tc)
# normalize the tensor in dim 1 or row-wise
tr = normalize(t, p=2.0, dim = 1)
# print the normalized tensor
print("Row-wise Normalized tensor:
", tr)輸出
Tensor: tensor([[1., 2., 3.], [4., 5., 6.]]) Normalized tensor: tensor([[0.2673, 0.5345, 0.8018], [0.4558, 0.5698, 0.6838]]) Column-wise Normalized tensor: tensor([[0.2425, 0.3714, 0.4472], [0.9701, 0.9285, 0.8944]]) Row-wise Normalized tensor: tensor([[0.2673, 0.5345, 0.8018], [0.4558, 0.5698, 0.6838]])
廣告
資料結構
網路
關係型資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP