如何在 PyTorch 中將張量重新縮放至 [0, 1] 範圍並使其總和為 1?


我們可以將一個 n 維輸入張量重新縮放,使其元素位於 [0,1] 範圍內,並且總和為 1。為此,我們可以應用 **Softmax()** 函式。我們可以沿著特定維度重新縮放 n 維輸入張量。輸出張量的尺寸與輸入張量相同。

語法

torch.nn.Softmax(dim)

引數

  • dim – 計算 Softmax 的維度。

步驟

我們可以使用以下步驟在給定大小下隨機位置裁剪影像:

  • 匯入所需的庫。在以下所有示例中,所需的 Python 庫是 torch。請確保您已安裝它。

import torch
  • 定義一個 n 維輸入張量 **input**。

input = torch.randn(5,2)
  • 定義 **Softmax** 函式,並將維度 **dim** 作為可選引數傳遞。

softmax = torch.nn.Softmax(dim = 1)
  • 將上面定義的 **Softmax** 函式應用於輸入張量 **input**。

output = softmax(input)
  • 列印包含 Softmax 值的張量。

print(output)

示例 1

以下 Python 程式將張量重新縮放至 [0, 1] 範圍並使其總和為 1。

import torch
input = torch.randn(5)
print(input)

softmax = torch.nn.Softmax(dim = 0)
output = softmax(input)
print(output)

print(output.sum())

輸出

tensor([-0.5654, -0.9031, -0.3060, -0.6847, -1.4268])
tensor([0.2315, 0.1651, 0.3001, 0.2055, 0.0978])
tensor(1.0000)

請注意,重新縮放後,張量的元素位於 [0,1] 範圍內,並且重新縮放後的張量元素之和為 1。

示例 2

以下 Python 程式將張量重新縮放至 [0, 1] 範圍並使其總和為 1。

# Import the required library
import torch
input = torch.randn(5,2)
print(input)

softmax = torch.nn.Softmax(dim = 1)
output = softmax(input)
print(output)
print(output[0])
print(output[1].sum())

輸出

tensor([[-0.5788, 0.9244],
   [-0.5172, 1.6231],
   [ 1.3032, -2.1107],
   [-0.4802, 0.1321],
   [-1.3219, -0.3570]])
tensor([[0.1819, 0.8181],
   [0.1052, 0.8948],
   [0.9681, 0.0319],
   [0.3515, 0.6485],
   [0.2759, 0.7241]])
tensor([0.1819, 0.8181])
tensor(1.)

請注意,重新縮放後,張量的元素位於 [0,1] 範圍內,並且重新縮放後的張量元素之和為 1。

更新於: 2022年1月25日

2K+ 次瀏覽

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.