向轴添加额外维度 [英] Add extra dimension to an axes

查看:48
本文介绍了向轴添加额外维度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一批形状为 [5,1,100,100] (batch_size x dims x ht x wd) 的分割掩码,我必须用 RGB 显示在 tensorboardX 中图像批处理 [5,3,100,100].我想在分割掩码的第二个轴上添加两个虚拟维度以使其成为 [5,3,100,100] 这样当我将它传递给 torch.utils 时不会有任何维度不匹配错误.make_grid.我尝试过 unsqueezeexpandview,但我无法做到.有什么建议吗?

I have a batch of segmentation masks of shape [5,1,100,100] (batch_size x dims x ht x wd) which I have to display in tensorboardX with an RGB image batch [5,3,100,100]. I want to add two dummy dimensions to the second axes of the segmentation mask to make it [5,3,100,100] so there will not be any dimension mismatch error when I pass it to torch.utils.make_grid. I have tried unsqueeze, expand and view but I am not able to do it. Any suggestions?

推荐答案

您可以使用 expandrepeatrepeat_interleave:

You can use expand, repeat, or repeat_interleave:

import torch

x = torch.randn((5, 1, 100, 100))
x1_3channels = x.expand(-1, 3, -1, -1)
x2_3channels = x.repeat(1, 3, 1, 1)
x3_3channels = x.repeat_interleave(3, dim=1)

print(x1_3channels.shape)  # torch.Size([5, 3, 100, 100])
print(x2_3channels.shape)  # torch.Size([5, 3, 100, 100])
print(x3_3channels.shape)  # torch.Size([5, 3, 100, 100])

请注意,如文档中所述:

Note that, as stated in the docs:

扩展张量不会分配新的内存,而只会在现有张量上创建一个新视图,其中通过将步幅设置为 0 将大小为 1 的维度扩展到更大的大小.任何大小为 1 的维度都可以扩展为任意值,而无需分配新内存.

Expanding a tensor does not allocate new memory, but only creates a new view on the existing tensor where a dimension of size one is expanded to a larger size by setting the stride to 0. Any dimension of size 1 can be expanded to an arbitrary value without allocating new memory.

  • torch.repeat():
  • expand()不同,这个函数复制张量的数据.

    这篇关于向轴添加额外维度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆