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



    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, ' ', 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, ' ', x, ' ', repeat)
    print(expand == repeat, ' ', 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)
  • 相关阅读:
    HDU 4508
    HDU 4503
    HDU 4532
    HDU 4544
    HDU 3167 KMP
    HDU 4542
    HDU 4528
    【70】自然语言处理与词嵌入
    【69】循环神经网络
    【68】一维和三维卷积
  • 原文地址:https://www.cnblogs.com/TianyuSu/p/14119444.html
Copyright © 2020-2023  润新知