pytorch repeat 和 expand 函数的使用场景,区别

标签:区别   引用   sign   int   选中   ike   view   ref   操作   


x = torch.tensor([0, 1, 2, 3]).float().view(4, 1)


def test_assign(x):
# 赋值操作
x_expand = x.expand(-1, 3)
x_repeat = x.repeat(1, 3)
x_expand[:, 1] = torch.tensor([0, -1, -2, -3])
x_repeat[:, 1] = torch.tensor([0, -1, -2, -3])
print(x_expand, ‘\n‘, x_repeat)
"""
x_expand, 每一列的值都被改了,因为是操作引用,一个变化全部变化
tensor([[ 0., 0., 0.],
[-1., -1., -1.],
[-2., -2., -2.],
[-3., -3., -3.]])
x_repeat, 只有选中的列发生了改变,因为是内存都是复制来的
tensor([[ 0., 0., 0.],
[ 1., -1., 1.],
[ 2., -2., 2.],
[ 3., -3., 3.]])

"""


def other(x):
# 引用值做其他操作
x_expand = x.expand(-1, 3) # x,ref
x_repeat = x.repeat(1, 3) # real copy
y = torch.rand_like(x_expand) * 10 # real mem
expand = x_expand - y # x, ref - real mem
x = x_expand - y # assign x
repeat = x_repeat - y
print(expand, ‘\n‘, x, ‘\n‘, repeat)
print(expand == repeat, ‘\n‘, x == repeat)
print(id(x)==id(x_expand))
"""
expand
tensor([[ -6.6548, -9.2567, -3.7804],
[ -7.5785, -9.4398, -5.6251],
[ -6.5088, -5.3956, -3.9644],
[-12.3324, -7.5420, -12.4954]])
x
tensor([[ -6.6548, -9.2567, -3.7804],
[ -7.5785, -9.4398, -5.6251],
[ -6.5088, -5.3956, -3.9644],
[-12.3324, -7.5420, -12.4954]])
repeat
tensor([[ -6.6548, -9.2567, -3.7804],
[ -7.5785, -9.4398, -5.6251],
[ -6.5088, -5.3956, -3.9644],
[-12.3324, -7.5420, -12.4954]])

expand==repeat
tensor([[True, True, True],
[True, True, True],
[True, True, True],
[True, True, True]])
x==repeat
tensor([[True, True, True],
[True, True, True],
[True, True, True],
[True, True, True]])
"""


test_assign(x)
other(x)

pytorch repeat 和 expand 函数的使用场景,区别

标签:区别   引用   sign   int   选中   ike   view   ref   操作   

原文地址:https://www.cnblogs.com/TianyuSu/p/14119444.html

版权声明:完美者 发表于 2020-12-16 12:40:47。
转载请注明:pytorch repeat 和 expand 函数的使用场景,区别 | 完美导航

暂无评论

暂无评论...