pytorch学习1:tensor的操作

tensor操作中的api和numpy非常相似

1、基本操作

x = torch.ones(2,2)
print(x)

x.type()

# 将其转换为整型
x = x.long()
print(x)

# 再将其转回float
x = x.float()
print(x)

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

# 沿着行取最大值
max_value, max_idx = torch.max(x, dim=1)

# 沿着行对x求和
sum_x = torch.sum(x, dim=1)
print(sum_x)

2、增加维度或者减少维度


print(x.shape)
x = x.unsqueeze(0)
print(x.shape)
> torch.Size([4, 3])
> torch.Size([1, 4, 3])

x = x.unsqueeze(1) # 在第二维增加
print(x.shape)
> torch.Size([1, 1, 4, 3])

x = x.squeeze(0) # 减少第一维
print(x.shape)
> torch.Size([1, 4, 3])

x = x.squeeze()
print(x.shape)
> torch.Size([4, 3])

3、维度交换

x = torch.randn(3,4,5)
print(x.shape)
> torch.Size([3, 4, 5])
# 使用permute和transpose进行维度交换
x = x.permute(1,0,2)
print(x.shape)
>torch.Size([4, 3, 5])
# transpose交换tensor中的两个维度
x = x.transpose(0,2)
print(x.shape)
> torch.Size([5, 3, 4])

4、使用view对tensor进行reshape

x = torch.randn(3,4,5)
x = x.view(-1, 5)
# -1 表示任意的大小,5表示第二维变成5
print(x.shape)

# 重新reshape成(3, 2, 10)的大小
x = x.view(3,2,10)
print(x.shape)

5、求和

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

# 两个tensor求和
z = x + y
# z = torch.add(x,y)

6、inplace操作

pytorch中大多数的操作都支持inplace操作,也就是可以直接对tensor进行操作而不需要另外开辟内存空间,方式非常简单,一般都是在操作的符号后面加_,比如

x = torch.ones(3, 3)
print(x.shape)

# unsqueeze 进行inplace
x.unsqueeze_(0)
print(x.shape)

# transpose 进行inplace
x.transpose_(1,0)
print(x.shape)

x = torch.ones(3, 3)
y = torch.ones(3, 3)
print(x)
x.add_(y)
print(x)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值