pytorch | contiguous() 函数

1. 背景

torch中一些操作会改变原数据,比如:narrow() view() expand() transpose()等操作,在使用transpose()进行转置操作时,pytorch并不会创建新的、转置后的tensor,而是修改了tensor中的一些属性(也就是元数据),使得此时的offset和stride是与转置tensor相对应的。转置的tensor和原tensor的内存是共享的,即改变转置后的tensor, 原先tensor中内容也会改变,而contiguous方法就类似深拷贝,使得上面这些操作不会改变元数据

2. 示例

python 复制代码
x = torch.randn(3, 2)
y = torch.transpose(x, 0, 1)
print("修改前:")
print("x-", x)
print("y-", y)
 
print("\n修改后:")
y[0, 0] = 11
print("x-", x)
print("y-", y)

输出:修改后的 x 会随 y 的改变而改变

修改前:

x- tensor([[-1.2076, -0.5300],

-0.0826, -1.0144\], \[ 1.2097, -1.2360\]\]) y- tensor(\[\[-1.2076, -0.0826, 1.2097\], \[-0.5300, -1.0144, -1.2360\]\])

修改后:

x- tensor([[11.0000, -0.5300],

-0.0826, -1.0144\], \[ 1.2097, -1.2360\]\]) y- tensor(\[\[11.0000, -0.0826, 1.2097\], \[-0.5300, -1.0144, -1.2360\]\])

使用 conguous方法

python 复制代码
import torch
x = torch.randn(3, 2)
y = torch.transpose(x, 0, 1).contiguous()
print("修改前:")
print("x-", x)
print("y-", y)
 
print("\n修改后:")
y[0, 0] = 11
print("x-", x)
print("y-", y)

输出: 可以看到x并没有随y的改变而改变

x- tensor([[ 1.3756, -0.1766],

0.9518, -1.7000\], \[-1.0423, -0.6077\]\]) y- tensor(\[\[ 1.3756, 0.9518, -1.0423\], \[-0.1766, -1.7000, -0.6077\]\])

修改后:

x- tensor([[ 1.3756, -0.1766],

0.9518, -1.7000\], \[-1.0423, -0.6077\]\]) y- tensor(\[\[11.0000, 0.9518, -1.0423\], \[-0.1766, -1.7000, -0.6077\]\])

3. 总结

当调用 contiguous() 时,会强制拷贝一份 tensor,让它的布局和从头创建的一模一样,使得两个 tensor 完全没有联系,类似于深拷贝

相关推荐
AKAMAI9 小时前
Akamai 宣布收购功能即服务公司 Fermyon
人工智能·云计算
河南博为智能科技有限公司9 小时前
高集成度国产八串口联网服务器:工业级多设备联网解决方案
大数据·运维·服务器·数据库·人工智能·物联网
光路科技9 小时前
人工智能时代,工业以太网正在“进化”成什么样?
人工智能
翔云 OCR API9 小时前
承兑汇票识别接口技术解析-开发者接口
开发语言·前端·数据库·人工智能·ocr
roman_日积跬步-终至千里10 小时前
【模式识别与机器学习(16)】聚类分析【1】:基础概念与常见方法
人工智能·机器学习
nvd1110 小时前
一个简单的GitHub AI Agent 实现指南
人工智能·langchain
Trouville0110 小时前
Pycharm软件初始化设置,字体和shell路径如何设置到最舒服
ide·python·pycharm
阿里云大数据AI技术10 小时前
【新模型速递】PAI-Model Gallery云上一键部署DeepSeek-V3.2模型
人工智能
阿恩.77010 小时前
2026年1月最新计算机、人工智能、经济管理国际会议:选对会议 = 论文成功率翻倍
人工智能·经验分享·笔记·计算机网络·金融·区块链
高-老师10 小时前
WRF模式与Python融合技术在多领域中的应用及精美绘图
人工智能·python·wrf模式