torch.mul()函数使用说明,含高维张量实例及运行结果

torch.mul函数使用说明,含实例及运行结果

  • torch.mul() 函数
    • torch.mul() 函数定义
    • 参数及功能
    • 高维数据实例解释
  • 参考博文及感谢

torch.mul() 函数

对输入的张量或数做点积运算,如果维度不统一会想进行维度统一(广播机制),再进行点积运算;广播机制是直接复制上一维度的值。

torch.mul() 函数定义

torch.mul(input, other, *, out=None) → Tensor

参数及功能

**input ** (Tensor) – the input tensor. 输入的张量
**other ** (Tensor or Number) 张量或数
Supports broadcasting to a common shape, type promotion, and integer, float, and complex inputs. 支持广播到通用形状、类型推广以及整数、浮点和复杂输入。

高维数据实例解释

直接看一个5维的二值例子,先看图(红虚线和实线是为了便于区分维度而添加),不懂再结合代码和结果分析
torch.mul()函数使用说明,含高维张量实例及运行结果_第1张图片

代码如下:

import torch
import numpy as np

np.random.seed(2022)
a = np.random.randint(low=0, high=2, size=(2, 2, 1, 3, 4))
a = torch.tensor(a)
b = np.random.randint(low=0, high=2, size=(2, 1, 2, 3, 4))
b = torch.tensor(b)
c = torch.mul(a, b)
print(a)
print("=============================================")
print(b)
print("=============================================")
print(c.size())
print("=============================================")
print(c)

运行结果为:

tensor([[[[[1, 0, 1, 0],
           [1, 1, 0, 1],
           [0, 0, 0, 0]]],


         [[[1, 1, 1, 1],
           [1, 1, 0, 0],
           [0, 1, 0, 1]]]],



        [[[[0, 0, 0, 1],
           [0, 0, 0, 1],
           [0, 1, 0, 0]]],


         [[[1, 1, 1, 1],
           [1, 1, 1, 1],
           [0, 0, 0, 0]]]]], dtype=torch.int32)
=============================================
tensor([[[[[0, 1, 0, 1],
           [1, 0, 0, 0],
           [0, 1, 1, 0]],

          [[0, 1, 0, 1],
           [1, 1, 1, 1],
           [1, 1, 0, 1]]]],



        [[[[1, 1, 0, 0],
           [0, 0, 1, 0],
           [0, 1, 0, 1]],

          [[1, 0, 0, 1],
           [1, 1, 1, 0],
           [1, 1, 1, 1]]]]], dtype=torch.int32)
=============================================
torch.Size([2, 2, 2, 3, 4])
=============================================
tensor([[[[[0, 0, 0, 0],
           [1, 0, 0, 0],
           [0, 0, 0, 0]],

          [[0, 0, 0, 0],
           [1, 1, 0, 1],
           [0, 0, 0, 0]]],


         [[[0, 1, 0, 1],
           [1, 0, 0, 0],
           [0, 1, 0, 0]],

          [[0, 1, 0, 1],
           [1, 1, 0, 0],
           [0, 1, 0, 1]]]],



        [[[[0, 0, 0, 0],
           [0, 0, 0, 0],
           [0, 1, 0, 0]],

          [[0, 0, 0, 1],
           [0, 0, 0, 0],
           [0, 1, 0, 0]]],


         [[[1, 1, 0, 0],
           [0, 0, 1, 0],
           [0, 0, 0, 0]],

          [[1, 0, 0, 1],
           [1, 1, 1, 0],
           [0, 0, 0, 0]]]]], dtype=torch.int32)

参考博文及感谢

部分内容参考以下链接,这里表示感谢 Thanks♪(・ω・)ノ
参考博文1 torch.mul() 官方文档
https://pytorch.org/docs/stable/generated/torch.mul.html

你可能感兴趣的:(Pytorch,python,python,pytorch)