pytorch:tensor的运算

本文详细介绍了PyTorch中张量的四种基本运算:加减乘除、矩阵相乘、次方与次方根运算,以及近似运算,包括torch.add、torch.sub、torch.matmul等函数的用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

**

一、加减乘除

**
torch.add / torch.sub / torch.mul / torch.div
分别为矩阵对应元素的加减乘除
与使用符号±*/功能相同
//表示整除

In [1]: import torch

In [2]: a = torch.rand(3,4)

In [3]: b = torch.rand(4)

In [4]: a+b
Out[4]:
tensor([[0.2696, 1.2878, 1.4269, 0.6681],
        [0.6802, 1.0790, 1.8201, 0.7958],
        [1.0932, 1.6674, 0.9889, 0.8394]])

In [5]: torch.add(a,b)
Out[5]:
tensor([[0.2696, 1.2878, 1.4269, 0.6681],
        [0.6802, 1.0790, 1.8201, 0.7958],
        [1.0932, 1.6674, 0.9889, 0.8394]])

In [6]: torch.all(torch.eq(a+b,torch.add(a,b)))
Out[6]: tensor(1, dtype=torch.uint8)

In [7]: torch.all(torch.eq(a-b,torch.sub(a,b)))
Out[7]: tensor(1, dtype=torch.uint8)

In [8]: torch.all(torch.eq(a*b,torch.mul(a,b)))
Out[8]: tensor(1, dtype=torch.uint8)

In [9]: torch.all(torch.eq(a/b,torch.div(a,b)))
Out[9]: tensor(
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值