The mathematical difference of the operators * = or + =

I found a strange thing when using an operator, for example. *=or+=

The code:

aa = Variable(torch.FloatTensor([[1,2],[3,4]]))
bb = aa
bb = bb*2
print(bb)
print(aa)

cc = Variable(torch.FloatTensor([[1,2],[3,4]]))
dd = cc
dd *= 2
print(cc)
print(dd)

Results shown below:

Variable containing:
 2  4
 6  8
[torch.FloatTensor of size 2x2]

Variable containing:
 1  2
 3  4
[torch.FloatTensor of size 2x2]

Variable containing:
 2  4
 6  8
[torch.FloatTensor of size 2x2]

Variable containing:
 2  4
 6  8
[torch.FloatTensor of size 2x2]

As you can see, when I used it bb=bb*2, aait was not affected. However, if used dd *= 2, ccit seems to point to the (shared) same address as it is cc, changed.

Their corresponding previous line is the same, for example. bb = aaand dd = cc. It seems that the operator *=changed the original deep copy to a shallow copy, and the change was made after the copy itself.

, . , , . , , , . torch.add() - .

OS: Mac OS X
PyTorch version: 3.0
How you installed PyTorch (conda, pip, source): conda
Python version: 3.6
CUDA/cuDNN version: None
GPU models and configuration: None

* ---------------------------------------

, dd *= 2 , dd cc? dd = dd * 2, cc? : dd = cc bb =aa. BTW, python ( pytorch Variable Tensor), dd *= 2 dd = dd * 2 cc.

+4
2

dd = cc, dd cc ( bb = aa). !

bb = bb * 2, * , bb . .

dd *= 2, , dd ( cc), .

, , * , = ( - ), *= .

, x *= y , x = x * y, , .

+4

, :

aa = Variable(torch.FloatTensor([[1,2],[3,4]]))
bb = aa
bb = bb*2
print(bb , id(bb))
print(aa , id(aa))

cc = Variable(torch.FloatTensor([[1,2],[3,4]]))
dd = cc
dd *= 2
print(cc, id(cc))
print(dd, id(dd))

, .

, :

aa = [1,2,3,4]
bb = aa
bb = bb*2
print(bb, id(bb))
print(aa, id(aa))

cc =[1,2,3,4]
dd = cc
dd *= 2
print(cc, id(cc))
print(dd, id(dd))

( ):

([1, 2, 3, 4, 1, 2, 3, 4], 140432043987888)  # bb  different ids
([1, 2, 3, 4], 140432043930400)              # aa  different ids  
([1, 2, 3, 4, 1, 2, 3, 4], 140432043916032)  # cc  same id, same object
([1, 2, 3, 4, 1, 2, 3, 4], 140432043916032)  # dd  same id, same object
0

Source: https://habr.com/ru/post/1694970/


All Articles