【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, 21, 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())
相关推荐
Bruce_Liuxiaowei2 小时前
Python 实例赋值遮蔽类属性:一个从不报错的静默陷阱
开发语言·python·语法糖
做运维的阿瑞3 小时前
Python 标准库汇总:分类速览与常用模块清单
linux·运维·python
why-geo3 小时前
Hermes Agent 与 Python 的会产生什么样的碰撞
人工智能·python·ai编程
正经教主3 小时前
【FDE系列】阶段2:Day 29:FastAPI 进阶 — Pydantic 模型与完整 CRUD 实战
人工智能·python·fde
gCode Teacher 格码致知3 小时前
Pandas教学-6:coerce详解
python·pandas
梦在远山后3 小时前
Electron 与 FastAPI 如何完成流式 Agent 对话
python·langchain·agent
大衛說3 小时前
12 · 文件 I/O 与序列化
python
小静AI工程实验室3 小时前
Python 爬虫中文乱码排查:严格解码、UTF-8 BOM 与 JSON 转义的 12 项实验
字符编码·爬虫·python
金色印象3 小时前
【论文解读】DRSN:把软阈值去噪“内化”进残差网络的强噪声故障诊断方法
深度学习·残差网络·故障诊断·软阈值·收缩函数·强噪声·drsn
天天被压力3 小时前
【跨市场数据实战 #08】可转债折价机会怎么筛:3个接口抓比价、列表和实时盘口
java·人工智能·python