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 完全没有联系,类似于深拷贝

相关推荐
小小张说故事3 分钟前
Python 的函数调用到底贵在哪?拆开一次 call:51 纳秒栈帧与 *args 的 40 纳秒罚单
python
代码山河27 分钟前
大模型的幻觉是什么?为什么会产生幻觉
人工智能·ai·大模型
数聚天成DeepSData44 分钟前
验收一批标注数据时,一致性到底在比谁和谁
人工智能·深度学习·机器学习·数据集·deepsdata
码农小白AI1 小时前
监督抽查报告要素不全?IACheck AI 报告文档审核 Agent 做报告要素完整性审查
人工智能
程序猿乐锅1 小时前
【从0-1学习Python | 第七篇】Python 面向对象基础
开发语言·笔记·后端·python·学习·1024程序员节
lzqrzpt1 小时前
太阳能控制器选型要点:电路工艺与工程适配技术解析
python·1024程序员节
海宇AI1 小时前
零信任架构实战:基于海宇行驶OCR证识别构建自动化租车车队行驶证电子档案网关
运维·人工智能·架构·自动化·1024程序员节
大模型真好玩1 小时前
大模型训练全流程实战指南实战篇(十七)— LLamaFatory预训练实战:从语料到模型
人工智能·agent·deepseek
蒲公英eric2 小时前
逻辑回归与信用违约预测:从S曲线到分类器
人工智能·数学建模·逻辑回归
databook2 小时前
时间序列数据中,如何找出缺失值
python·数据分析