如何在PyTorch中對輸入資料應用線性變換?
我們可以使用**torch.nn.Linear()**模組對輸入資料應用線性變換。它支援**TensorFloat32**型別的輸入資料。這在深度神經網路中用作一個層來執行線性變換。使用的線性變換為:
y = x * W ^ T + b
這裡**x**是輸入資料,**y**是線性變換後的輸出資料。W是權重矩陣,**b**是偏置。權重**W**的形狀為**(out_features, in_features)**,偏置**b**的形狀為(out_features)。它們在神經網路訓練期間被隨機初始化並更新。
語法
torch.nn.Linear(in_features, out_features)
引數
**in_features** - 輸入樣本的大小。
**out_features** - 輸出樣本的大小。
步驟
您可以使用以下步驟將線性變換應用於輸入資料:
匯入所需的庫。在以下所有示例中,所需的Python庫是**torch**。請確保您已安裝它。
import torch
定義輸入**張量**並列印它。
input = torch.randn(2,3) print("Input Tensor:
",input)
使用合適的**in_features**和**out_features**定義線性變換。
linear = nn.Linear(in_features, out_features)
將上述定義的線性變換應用於輸入資料。並且可以選擇將輸出賦值給一個新變數。
output = linear(input)
列印線性變換後的張量。
print("Transformed Tensor:
",output)
示例1
# Import the required library import torch import torch.nn as nn # torch.nn.Linear(in_features, out_features, bias=True, device=None, dtype=None) in_features = 3 out_features = 5 linear = nn.Linear(in_features, out_features) input = torch.randn(2,3) print("Input Tensor:
",input) print("Size of Input Tensor:
",input.size()) # Compute the linear transformation output = linear(input) print("Transformed Tensor:
",output) print("Size of Transformed Tensor:
",output.size())
輸出
Input Tensor: tensor([[-0.0921, 0.1992, -1.4930], [-0.0827, 0.0926, -0.1487]]) Size of Input Tensor: torch.Size([2, 3]) Transformed Tensor: tensor([[-0.5778, -0.3074, -0.5339, -0.3443, -0.1688], [-0.3149, -0.2189, -0.1795, -0.3617, -0.0839]], grad_fn=<AddmmBackward>) Size of Transformed Tensor: torch.Size([2, 5])
請注意,線性變換後大小發生了變化。
示例2
# Import the required library import torch import torch.nn as nn # torch.nn.Linear(in_features, out_features, bias=True, device=None, dtype=None) in_features = 3 out_features = 5 linear = nn.Linear(in_features, out_features, bias=False) input = torch.randn(2,3) print("Input Tensor:
",input) print("Size of Input Tensor:
",input.size()) # Compute the linear transformation output = linear(input) print("Transformed Tensor:
",output) print("Size of Transformed Tensor:
",output.size())
輸出
Input Tensor: tensor([[-0.6691, -1.6172, -0.9707], [-0.4425, 1.4376, -0.8004]]) Size of Input Tensor: torch.Size([2, 3]) Transformed Tensor: tensor([[ 0.3554, 1.3869, 0.5136, -0.1801, -0.5858], [ 0.3262, 0.2073, -0.8602, -0.0161, 0.5233]], grad_fn=<MmBackward>) Size of Transformed Tensor: torch.Size([2, 5])
請注意線性變換後大小是如何變化的。
廣告