【python深度学习】——pytorch中tensor的view、resize(resize_)与reshape

@TOC

1. view()

view()方法具有以下特性:

  1. 它只能在tensor是连续的时候使用(可以调用is_contiguous()方法查看tensor是否连续), 如果要对不连续的张量使用, 需要先使用.contiguous()使其在内存上连续。
  2. view()方法不改变tensor的storage内容, 只改变其元数据(metadata)。(参见后面的示例代码,通过tensor的storage().data_ptr()查看数据的地址)
  3. 调用view()时,需要确保tensor的元素总数保持不变。例如, [2, 3]的tensor可以view为[3, 2]或[1, 6]。

示例代码

python 复制代码
import torch

# 创建一个2x3的tensor
tensor = torch.rand(2, 3)
print(tensor.shape)  

# 使用view()改变tensor形状
new_tensor = tensor.view(3, 2)
print(new_tensor.shape)  

# 查看tensor和new_tensor的存储地址
print(tensor.storage().data_ptr())  
print(new_tensor.storage().data_ptr())  

# 查看tensor和new_tensor的存储内容
print(tensor.storage())
print(new_tensor.storage())

# 查看tensor和new_tensor的stride
print(tensor.stride())  
print(new_tensor.stride())  

2. resize()/resize_():

  1. resize_()是原地操作版本,会直接修改原tensor,而resize()会返回一个新的tensor。
  2. resize()/resize_()方法可以自动改变tensor的元素总数。如果新形状的元素总数大于原来的,会用0填充新增的元素;如果小于原来的,则会截断多余的元素。在补0的情况下, 会开辟一块新的内存区域来存放新的tensor。

示例代码

python 复制代码
import torch

# 创建一个2x3的tensor
tensor = torch.tensor([1,2,3,4])
print(tensor.shape)
print(tensor.storage().data_ptr())
# 使用resize()改变tensor形状
tensor.resize_(3, 2)
print(tensor.shape) # Output: torch.Size([3, 2])

# 新增的元素会被填充为0
print(tensor)
print(tensor.storage().data_ptr())

3. reshape():

  1. 在数据连续时
    reshape()方法在数据连续时, 作用和view()类似, 都是共享存储区的情况下(不改变tensor的storage)
  2. 不连续 时, reshape类似等同于contiguous()+view()------它会在新的存储区创建一个tensor, 不与原数据共享存储区。

示例代码

python 复制代码
import torch

# 创建一个2x3的tensor
tensor = torch.rand(2, 3)

# reshape()处理非连续的tensor
non_contiguous = tensor.t()
print(non_contiguous.is_contiguous()) # Output: False
reshaped = non_contiguous.reshape(1, 6)
print(reshaped.is_contiguous()) # Output: True

print(reshaped.storage().data_ptr())
print(non_contiguous.storage().data_ptr())
相关推荐
这里有鱼汤2 小时前
小白必看:QMT里的miniQMT入门教程
后端·python
TF男孩12 小时前
ARQ:一款低成本的消息队列,实现每秒万级吞吐
后端·python·消息队列
该用户已不存在17 小时前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
站大爷IP19 小时前
Java调用Python的5种实用方案:从简单到进阶的全场景解析
python
用户8356290780511 天前
从手动编辑到代码生成:Python 助你高效创建 Word 文档
后端·python
c8i1 天前
python中类的基本结构、特殊属性于MRO理解
python
隐语SecretFlow1 天前
国人自研开源隐私计算框架SecretFlow,深度拆解框架及使用【开发者必看】
深度学习
liwulin05061 天前
【ESP32-CAM】HELLO WORLD
python
Doris_20231 天前
Python条件判断语句 if、elif 、else
前端·后端·python
Doris_20231 天前
Python 模式匹配match case
前端·后端·python