【Pytorch】torch.Tensor.expand_as()与torch.Tensor.expand()使用与比较

torch.Tensor.expand_as官方文档地址:https://pytorch.org/docs/stable/generated/torch.Tensor.expand_as.html?highlight=expand_as#torch.Tensor.expand_as

torch.Tensor.expand()官方文档地址:https://pytorch.org/docs/stable/generated/torch.Tensor.expand.html#torch.Tensor.expand

torch.Tensor.expand()

形式:Tensor.expand(*sizes) → Tensor

作用:返回这个张量的一个新视图,其中单例维度扩展为更大的尺寸。传入 -1 作为维度的大小意味着不更改该维度的大小。Tensor 也可以扩展到更大的维度,新的维度会附加在前面。对于新维度,大小不能设置为 -1。扩展张量不会分配新内存,而只会在现有张量上创建一个新视图,其中通过将步幅设置为 0 将尺寸为 1 的维度扩展为更大的尺寸。任何大小为 1 的维度都可以扩展为任意值,而无需分配新的内存。

参数:
*sizes (torch.Size or int…) – the desired expanded size

注:扩展张量的多个元素可以引用单个内存位置。因此,就地操作(尤其是矢量化的操作)可能会导致不正确的行为。如果您需要写入张量,请先克隆它们。

使用案例:

x = torch.tensor([[1], [2], [3]])
x.size()  # torch.Size([3, 1])
x.expand(3, 4) 
#tensor([[ 1,  1,  1,  1],
#        [ 2,  2,  2,  2],
#        [ 3,  3,  3,  3]])
x.expand(-1, 4)   # -1 means not changing the size of that dimension
#tensor([[ 1,  1,  1,  1],
#        [ 2,  2,  2,  2],
#        [ 3,  3,  3,  3]])

说明: expand()函数只能将size=1的维度扩展到更大的尺寸,如果扩展其他size的维度会报错。

torch.Tensor.expand_as

形式:Tensor.expand_as(other) → Tensor

作用:将此张量扩展为与其他张量相同的大小。 self.expand_as(other) 等价于 self.expand(other.size())

参数:
other (torch.Tensor) – The result tensor has the same size as other.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

智绘山河

你的鼓励可能解决你下一个问题

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值