【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 小时前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽3 小时前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战3 小时前
Pydantic配置管理最佳实践(一)
python
阿尔的代码屋9 小时前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
AI探索者1 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者1 天前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh1 天前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅1 天前
Python函数入门详解(定义+调用+参数)
python
曲幽1 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时1 天前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构