【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())
相关推荐
东来也_八门13 分钟前
我用麦当劳开放的 MCP,把那个最冷门的营养接口做成了真实配餐求解器
python
AI日报派送佬20 分钟前
Ultralytics YOLO 模型训练技巧与最佳实践
人工智能·python·深度学习·yolo·机器学习·计算机视觉
zhaowangji28 分钟前
mujoco仿真(机械臂推动正方体到指定位置)
人工智能·python
数据管道工31 分钟前
解析一个老网站:GBK 编码、页面结构漂移与限流退避
python
只睡四小时33 分钟前
AI 生成 PPTX:11 页课件编译出 429 个形状
javascript·python·pptx·ai生成ppt·ooxml
leisoo809735 分钟前
股票筹码分布怎么用获利比例成本区间与集中度实战 IG50免费开源股票数据API接口
开发语言·jvm·数据库·python·开源
ControlM37 分钟前
从官方 CDN 里扒出 TRAE (TraeCode) 历史版本安装包
python·逆向·trae
tianyuanwo38 分钟前
Python 属性查找陷阱:从 `AttributeError: ‘X‘ object has no attribute ‘_children‘` 说起
python
程序猿阿森1 小时前
混合精度详解:FP16 vs BF16,Loss Scaling 与 PyTorch 实战
人工智能·pytorch·python
benchmark_cc1 小时前
A股、港股、美股日K如何拼接?处理不同交易日造成的时间轴错位
大数据·python·pandas·量化交易·股票数据·quantdash