Python基础:contiguous

        在pytorch中,tensor的实际数据以一维数组(storage)的形式存储于某个连续的内存中,以”行优先"进行存储,tensor连续(contiquous)是指tensor的storage元素排列顺序与其按行优先时的元素排列顺序相同,tensor不连续会导致某些操作无法进行,比如view()就无法进行。

import torch
a = torch.tensor([[1, 2, 3],
                  [4, 5, 6],
                  [7, 8, 9]])
print(a)
print(a.storage())# a是连续的print(a.is_contiguous())

b = a.t()# b是a的转置
print(b)
print(b.storage())
print(b.is_contiguous())

 

tensor([[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]])
 1
 2
 3
 4
 5
 6
 7
 8
 9
[torch.LongStorage of size 9]
tensor([[1, 4, 7],
        [2, 5, 8],
        [3, 6, 9]])
 1
 2
 3
 4
 5
 6
 7
 8
 9
[torch.LongStorage of size 9]
False

        b应该是1 4 7 2 5 8 3 6 9才是连续的,虽然它经过a的转置,但是并没有改变其原先的存储顺序,所以出现的结果就是不连续的。 

        使用.contiguous()实现其为行存储 :

c = b.contiguous()
print(b)
print(c)
print(b.storage())
print(c.storage())
print(c.is_contiguous())

tensor([[1, 4, 7],
        [2, 5, 8],
        [3, 6, 9]])
tensor([[1, 4, 7],
        [2, 5, 8],
        [3, 6, 9]])
 1
 2
 3
 4
 5
 6
 7
 8
 9
[torch.LongStorage of size 9]
 1
 4
 7
 2
 5
 8
 3
 6
 9
[torch.LongStorage of size 9]
True

        可以发现c已经和b的存储顺序不一样了,是连续的了。 

参考:28-masked_fill张量掩码|Dropout正则化|view|register_buffer|contiguous|多头注意力-transformer_哔哩哔哩_bilibili 

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用 PyTorch 中的 `PixelShuffle` 模块来实现这个操作。具体代码如下: ```python import torch.nn as nn class PixelShuffle(nn.Module): def __init__(self, upscale_factor): super(PixelShuffle, self).__init__() self.upscale_factor = upscale_factor def forward(self, x): batch_size, channels, height, width = x.size() channels //= self.upscale_factor ** 2 out_height, out_width = height * self.upscale_factor, width * self.upscale_factor x = x.view(batch_size, channels, self.upscale_factor, self.upscale_factor, height, width) x = x.permute(0, 1, 4, 2, 5, 3).contiguous() x = x.view(batch_size, channels, out_height, out_width) return x # 定义输入特征图和像素重排模块 input_feature_map = torch.randn(1, 196, 768) pixel_shuffle = PixelShuffle(16) # 对输入特征图进行像素重排 output_feature_map = pixel_shuffle(input_feature_map.unsqueeze(0)).squeeze() # 输出结果 print(output_feature_map.size()) # torch.Size([1, 3, 224, 224]) ``` 这里我们定义了一个 `PixelShuffle` 模块,其 `forward` 方法接受输入特征图 `x`,并将其像素重排成目标形状。具体来说,我们首先将输入特征图 `x` 重塑成 6 维张量,然后使用 `permute` 方法交换维度,最后将其重塑成目标形状。在使用 `PixelShuffle` 模块时,我们需要指定 `upscale_factor` 参数,它表示上采样倍数,即目标特征图大小除以输入特征图大小。在本例中,`upscale_factor` 为 16,即目标特征图大小为输入特征图大小的 16 倍。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值