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)
  • 相关阅读:
    Chromium GN构建工具的使用
    cef 不更新编译
    Debugging SSL on Linux
    chromium url 请求流程
    mim
    qt打包发布问题 缺失qt动态库
    qmake生成pro的make总失败。但是qt creator里面是好的
    qt 与 x11 头文件同时引用
    Ubuntu16安装GTK+2.0教程
    gcc编译静态库到自己的程序 解决在不同linux下因libc版本问题而不能运行 版本兼容问题
  • 原文地址:https://www.cnblogs.com/TianyuSu/p/14119444.html
Copyright © 2011-2022 走看看