zoukankan      html  css  js  c++  java
  • 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)
  • 相关阅读:
    洛谷1525关押罪犯——二分
    洛谷P1525关押罪犯——二分做法
    poj2411铺砖——状压DP
    1 理解Linux系统的“平均负载”
    3.2-3 tac、more
    3.20 tr:替换或删除字符
    3.14-19 wc、iconv、dos2unix、diff、vimdiff、rev
    3.21-22 od、tee
    指针和引用的区别
    new与malloc区别
  • 原文地址:https://www.cnblogs.com/TianyuSu/p/14119444.html
Copyright © 2011-2022 走看看