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维的二值例子,先看图(红虚线和实线是为了便于区分维度而添加),不懂再结合代码和结果分析
在这里插入图片描述

代码如下:

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

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值