如何在 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.