During initializing, I tried to reduce the repeats in my code, so instead of:
JavaScript
x
3
1
output= (torch.zeros(2, 3),
2
torch.zeros(2, 3))
3
I wrote:
JavaScript
1
3
1
z = torch.zeros(2, 3)
2
output= (z,z)
3
However, I find that the second method is wrong.
If I assign the data to variables h,c
, any change on h
would also be applied to c
JavaScript
1
6
1
h,c = output
2
print(h,c)
3
h +=torch.ones(2,3)
4
print('-----------------')
5
print(h,c)
6
results of the test above:
JavaScript
1
8
1
tensor([[0., 0., 0.],
2
[0., 0., 0.]]) tensor([[0., 0., 0.],
3
[0., 0., 0.]])
4
-----------------
5
tensor([[1., 1., 1.],
6
[1., 1., 1.]]) tensor([[1., 1., 1.],
7
[1., 1., 1.]])
8
Is there a more elegent way to initialize two indenpendent variables?
Advertisement
Answer
I agree that your initial line needs no modification but if you do want an alternative, consider:
JavaScript
1
3
1
z = torch.zeros(2, 3)
2
output= (z,z.clone())
3
The reason the other one (output = (z,z)
) doesn’t work, as you’ve correctly discovered is that no copy is made. You’re only passing the same reference in each entry of the tuple to z