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)
  • 相关阅读:
    遇到的面试题目
    获取本机IP_考虑多网卡的情况
    C#发送电子邮件
    C#获取局域网中的所有正在使用的IP地址
    C#获取本机IP且过滤非真实网卡(如虚拟机网卡)
    C#获取本机的MAC地址
    C#获取本机磁盘信息
    C#获得系统打开的端口和状态
    C#通过编程方式实现Ping
    千万不要使用xfce和KDE版Manjaro Linux--之荒谬言论
  • 原文地址:https://www.cnblogs.com/TianyuSu/p/14119444.html
Copyright © 2011-2022 走看看