python开方运算符_Pytorch Tensor基本数学运算详解

本文介绍了Pytorch中Tensor的数学运算,包括加法、减法、乘法(哈达玛积)、除法、矩阵乘法、幂运算、开方、指数与对数、近似值和裁剪运算。通过示例代码展示了各运算的使用方法,并解释了Broadcasting机制。
摘要由CSDN通过智能技术生成

1. 加法运算

示例代码:

import torch

# 这两个Tensor加减乘除会对b自动进行Broadcasting

a = torch.rand(3, 4)

b = torch.rand(4)

c1 = a + b

c2 = torch.add(a, b)

print(c1.shape, c2.shape)

print(torch.all(torch.eq(c1, c2)))

输出结果:

torch.Size([3, 4]) torch.Size([3, 4])

tensor(1, dtype=torch.uint8)

2. 减法运算

示例代码:

a = torch.rand(3, 4)

b = torch.rand(4)

c1 = a - b

c2 = torch.sub(a, b)

print(c1.shape, c2.shape)

print(torch.all(torch.eq(c1, c2)))

输出结果:

torch.Size([3, 4]) torch.Size([3, 4])

tensor(1, dtype=torch.uint8)

3. 哈达玛积(element wise,对应元素相乘)

示例代码:

c1 = a * b

c2 = torch.mul(a, b)

print(c1.shape, c2.shape)

print(torch.all(torch.eq(c1, c2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值