pytorch使用-tensor基本操作


一、tensor加减乘除

加法操作

import torch

x = torch.randn(2, 3)
y = torch.randn(2, 3)

z = x + y
print(z)

z = torch.add(x, y)
print(z)

y.add_(x)
print(y)

在这里插入图片描述
其他操作类似:减法:sub(-), 乘法:mul(*), 除法:div(/)

二、tensor矩阵运算

# 二维矩阵相乘
a = torch.full([2, 2], 3, dtype=torch.long)
b = torch.ones(2, 2, dtype=torch.long)

print(a)
print(b)
print(torch.mm(a, b))

在这里插入图片描述

#  matmul 和 @ 可以用于二维矩阵计算,也可以是多维
# 四维,计算的时候就是前两维不变,后两维进行计算。
a = torch.rand(1, 1, 3, 2)
b = torch.rand(1, 1, 2, 4)

c = torch.matmul(a, b)
print(a)
print(b)
print(c)

在这里插入图片描述

pow

a = torch.full([2, 2], 6)
print(a.pow(3))

a = torch.full([2, 2], 6)
print(a**2)

sqrt: 平方根
rsqrt: 平方根倒数

a = torch.full([2, 2], 1024)

print(a.sqrt())
print(a.rsqrt())
print(a**0.5)

exp log

a = torch.ones(2, 2)

print(torch.exp(a))
print(torch.log(a))
print(torch.log2(a))

.floor()——往下近似
.ceil()——往上近似
.trunc()——裁剪为整数部分
.frac()——裁剪成小数部分

a = torch.tensor(3.1415926)

print(a.floor())
print(a.ceil())
print(a.trunc())
print(a.frac())

torch.round()——四舍五入

a = torch.tensor(3.1415926)

print(a.round())

.item() 转化为python number

x = torch.randn(1)

print(x)
print(x.item())

在这里插入图片描述

四、tensor切片操作

a = torch.randn(4, 3)
print(a)

# 取第二列
print(a[:, 1])

# 取前两列
print(a[:, :2])

在这里插入图片描述

五、tensor改变形状

x = torch.randn(4, 4)
y = x.view(16)

# -1, 自动匹配个数
z = x.view(-1, 8)

print(x)
print(y)
print(z)

在这里插入图片描述

六、tensor 和 numpy.array相互转换

# 底层内存共享
x = torch.ones(5)
print(x)

y = x.numpy()
print(y)

x.add_(1)
print(y)

在这里插入图片描述

import numpy as np
x = np.ones(5)
y = torch.from_numpy(x)
print(y)

在这里插入图片描述

七、tensor 转到GPU上

if torch.cuda.is_available():
    
    device = torch.device("cuda")
    x = torch.randn(2, 3)
    print(x)

    y = x.to(device)
    print(y)

    z = torch.randn(2, 3, device="cuda")
    print(z)
    
    # 同时在GPU上才能相加
    print(y + z)

    # 转换会cpu
    print(z.to("cpu"))

在这里插入图片描述

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大虾飞哥哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值