今天在代码中遇到:
x * y.expand_as(x)
于是就进行了知识填补。。。
多的不说,少的不唠,直接上代码案例进行学习:
import torch
x = torch.tensor([[1], [2], [3]]) # 生成tensor x,3行1列
print('xsize:',x.size())
print('x:',x)
xsize: torch.Size([3, 1])
x: tensor([[1],
[2],
[3]])
x_expand=x.expand(3,4) # 将x扩展为3行4列
print('x_expand:',x_expand)
x_expand: tensor([[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3]])
x_expand=x.expand(-1,4) # -1 means not changing the size of that dimension
print('x_expand:',x_expand)
x_expand: tensor([[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3]])
x_expand_as=x.expand_as(x_expand) # 将x的形状变为和x_expand一样
print('x_expand_as:',x_expand_as)
x_expand_as: tensor([[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3]])
总结
expand_as()这个函数就是把一个tensor变成和函数括号内一样形状的tensor,用法与expand()类似。
差别为expand括号里为size,expand_as括号里为其他tensor。
参考:
https://blog.csdn.net/wenqiwenqi123/article/details/101306839