ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2020-12-11 11:34:23  阅读:216  来源: 互联网

标签:repeat tensor torch pytorch print True 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, '\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)

标签:repeat,tensor,torch,pytorch,print,True,expand
来源: https://www.cnblogs.com/TianyuSu/p/14119444.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有