pytorch:contiguous()

contiguous:连续的,邻近的

调用contiguous时,会强制拷贝一份tensor,但两个tensor完全没有联系。则断开两个变量之间的依赖,也就是所谓的深拷贝。

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- tensor([[-0.5822,  0.5781],
        [ 1.4893,  1.2434],
        [-2.1330,  0.2530]])
y- tensor([[-0.5822,  0.5781],
        [ 1.4893,  1.2434],
        [-2.1330,  0.2530]])

修改后:
x- tensor([[11.0000,  0.5781],
        [ 1.4893,  1.2434],
        [-2.1330,  0.2530]])
y- tensor([[11.0000,  0.5781],
        [ 1.4893,  1.2434],
        [-2.1330,  0.2530]])

即对y使用了.contiguous()后,改变y的值,x没有任何影响。

如果不使用.contiguous(),则

import torch

x = torch.randn(3, 2)
# y = torch.transpose(x, 0, 1).contiguous()
z= torch.transpose(x, 0, 1)
print('修改前:')
print('x-', x)
print('z-',z)
print('\n修改后:')
z[0, 0] = 11
print('x-', x)
print('y-', z)

输出:
修改前:
x- tensor([[-1.5120,  0.9070],
        [ 1.1465,  1.4240],
        [ 0.5535,  0.1564]])
z- tensor([[-1.5120,  1.1465,  0.5535],
        [ 0.9070,  1.4240,  0.1564]])

修改后:
x- tensor([[11.0000,  0.9070],
        [ 1.1465,  1.4240],
        [ 0.5535,  0.1564]])
y- tensor([[11.0000,  1.1465,  0.5535],
        [ 0.9070,  1.4240,  0.1564]])

当遇到需要调用contiguous()时,运行会提醒。

RuntimeError: input is not contiguous

#在pytorch中,只有很少几个操作是不改变tensor的内容本身,只是重新定义下表与元素对应关系的,即不进行数据拷贝和数据改变,变得是元数据。

改变元数据的操作:

narrow()

view()

expand()

transpose()

在使用transpose()进行转置操作时,pytorch不会创建新的、转置后的tensor,而是修改了tensor中的一些属性,也就是元数据

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值