tensor.view()和tensor.reshape()和tensor.resize_()

tensor.view()和tensor.reshape()

示例文件 test.py

import torch

a = torch.randint(0, 10, (3, 4))
b = a.view(2, 6)
c = a.reshape(2, 6)

print(id(a)==id(b), id(a)==id(c), id(b)==id(c))
print(id(a.storage())==id(b.storage()),
	  id(a.storage())==id(c.storage()),
	  id(b.storage())==id(c.storage()))

print("permute result:")
k = a.permute(1, 0)
print(id(a)==id(k))
print(id(a.storage())==id(k.storage()))

print(k.is_contiguous())
print(a.is_contiguous())
a = a.permute(1, 0)

print("contiguous result:")
k = a.contiguous()
print(id(a)==id(k))
print(id(a.storage())==id(k.storage()))

c = a.reshape(2, 6)
print(c)

a = a.contiguous()
b = a.view(2, 6)
print(b)

print(id(a)==id(b), id(a)==id(c), id(b)==id(c))
print(id(a.storage())==id(b.storage()),
	  id(a.storage())==id(c.storage()),
	  id(b.storage())==id(c.storage()))

终端命令行及运行结果

<user>python test.py
False False False
True True True
permute result:
False
True
False
True
contiguous result:
False
True
tensor([[1, 5, 2, 9, 2, 7],
        [9, 6, 5, 6, 0, 3]])
tensor([[1, 5, 2, 9, 2, 7],
        [9, 6, 5, 6, 0, 3]])
False False False
True True True

从运算结果来看:

1)view()方法只能改变连续的(contiguous)张量,否则需要先调用contiguous()方法;而reshape()方法不受此限制。

2)如果对 tensor 调用过 transpose(),permute()等操作的话会使该 tensor 在内存中变得不再连续。

3)view()方法和shape()方法返回的张量与原张量共享基础数据(存储器,注意不是共享内存地址)。

4)参数不可为空,-1就代表这个位置由其他位置的数字来推断,只要在不致歧义的情况的下,view()参数就可以推断出来。

tensor.resize_()

示例文件 test.py

import torch

a = torch.arange(24).view(4, 6)

print(a.resize_(6, 4))
b = a.resize_(3, 3)
print(b)
print(b.resize_(5, 5))

终端命令行及运行结果

<user>python test.py
tensor([[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11],
        [12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23]])
tensor([[0, 1, 2],
        [3, 4, 5],
        [6, 7, 8]])
tensor([[                  0,                   1,                   2,
                           3,                   4],
        [                  5,                   6,                   7,
                           8,                   9],
        [                 10,                  11,                  12,
                          13,                  14],
        [                 15,                  16,                  17,
                          18,                  19],
        [                 20,                  21,                  22,
                          23, 3559939791936844404]])

从运算结果来看:

1)当目标大小大于当前大小时,基础存储器的大小将增大,以适应新的元素数,任何新的内存都是未初始化的。

2)当目标大小小于当前大小时,基础存储器的大小将不变,返回目标大小的元素重组后的张量,未使用的元素仍然保存在存储器中,如果再次resize回原来的大小,这些元素将会被重新使用。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值