Pytorch——tensor.expand_as()函数示例

tensor.expand_as()这个函数就是把一个tensor变成和函数括号内一样形状的tensor,用法与expand()类似。

差别是expand括号里为size,expand_as括号里为其他tensor。

举例:

import torch
x = torch.tensor([[1], [2], [3]])
print('xsize:',x.size())
print('x:',x)

x_expand=x.expand(3,4)
print('x_expand:',x_expand)

x_expand=x.expand(-1,4)  # -1 means not changing the size of that dimension
print('x_expand:',x_expand)

x_expand_as=x.expand_as(x_expand)
print('x_expand_as:',x_expand_as)

输出为:

xsize: torch.Size([3, 1])
x: tensor([[1],
        [2],
        [3]])
x_expand: tensor([[1, 1, 1, 1],
        [2, 2, 2, 2],
        [3, 3, 3, 3]])
x_expand: tensor([[1, 1, 1, 1],
        [2, 2, 2, 2],
        [3, 3, 3, 3]])
x_expand_as: tensor([[1, 1, 1, 1],
        [2, 2, 2, 2],
        [3, 3, 3, 3]])

 

你可能感兴趣的:(pytorch,pytorch,人工智能,张量,深度学习,机器学习)