Pytorch基础:Tensor的flatten方法

相关阅读

Pytorch基础https://blog.csdn.net/weixin_45791458/category_12457644.html?spm=1001.2014.3001.5482


        在Pytorch中,flatten是Tensor类的一个重要方法,同时它也是一个torch模块中的一个函数,它们的语法如下所示。 

Tensor.flatten(start_dim=0, end_dim=-1) → Tensor
torch.flatten(input, start_dim=0, end_dim=-1) → Tensor

input (Tensor) – the input tensor
start_dim (int) – the first dim to flatten
end_dim (int) – the last dim to flatten

        flatten函数(或方法)用于将一个张量以特定方法展平, 如果传递了参数,则会将从start_dim到end_dim之间的维度展开。默认情况下,flatten将从第0维展平至最后1维。

        flatten函数(或方法)可能返回原始张量、原始张量的视图(共享底层存储)或原始张量的副本:

  • 如果没有维度被展平,则返回原始张量(同一个对象)。
  • 如果输出张量可以视为等效地使用View展平,则返回视图(共享底层存储)。
  • 如果输出张量不能视为等效地使用View展平,则返回数据副本。 

        可以查看View相关的文章,进行更加深入的了解,下面有三个例子分别说明这三种情况:

# 例1
import torch

input_tensor = torch.tensor([[1, 2], [3, 4]])
flattened_tensor = torch.flatten(input_tensor, start_dim=0, end_dim=0)
print(input_tensor)
print(flattened_tensor)
print(id(flattened_tensor) == id(input_tensor)) # 查看是否是同一个张量对象
print(flattened_tensor.storage().data_ptr() == input_tensor.storage().data_ptr()) # 查看是否共享底层存储

输出:
tensor([[1, 2],
        [3, 4]])
tensor([[1, 2],
        [3, 4]])
True
True

# 例2
import torch

input_tensor = torch.tensor([[1, 2], [3, 4]])
flattened_tensor = torch.flatten(input_tensor, start_dim=0, end_dim=1)
print(input_tensor)
print(flattened_tensor)
print(id(flattened_tensor) == id(input_tensor)) # 查看是否是同一个张量对象
print(flattened_tensor.storage().data_ptr() == input_tensor.storage().data_ptr()) # 查看是否共享底层存储

输出:
tensor([[1, 2],
        [3, 4]])
tensor([1, 2, 3, 4])
False
True

# 例3
import torch

input_tensor = torch.tensor([[1, 2], [3, 4]]).transpose(0, 1)
flattened_tensor = torch.flatten(input_tensor, start_dim=0, end_dim=1)
print(input_tensor)
print(flattened_tensor)
print(id(flattened_tensor) == id(input_tensor)) # 查看是否是同一个张量对象
print(flattened_tensor.storage().data_ptr() == input_tensor.storage().data_ptr()) # 查看是否共享底层存储

输出:
tensor([[1, 3],
        [2, 4]])
tensor([1, 3, 2, 4])
False
False
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

日晨难再

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

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

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

打赏作者

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

抵扣说明:

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

余额充值