Note that pytorch a problem in tensor data and data conversion numpy

Reprinted from: (a problem noted pytorch tensor data and the data conversion numpy) [ https://blog.csdn.net/nihate/article/details/82791277 ]
In pytorch, the converted data to the tensor numpy.array tensor data is a commonly used functions torch.from_numpy (array) or torch.Tensor (array), the first function is more commonly used. The following look through the code differences:

import numpy as np
import torch

a=np.arange(6,dtype=int).reshape(2,3)
b=torch.from_numpy(a)
c=torch.Tensor(a)

a[0][0]=10
print(a,'\n',b,'\n',c)
[[10  1  2]
 [ 3  4  5]] 
 tensor([[10,  1,  2],
        [ 3,  4,  5]], dtype=torch.int32) 
 tensor([[0., 1., 2.],
        [3., 4., 5.]])

c[0][0]=10
print(a,'\n',b,'\n',c)
[[10  1  2]
 [ 3  4  5]] 
 tensor([[10,  1,  2],
        [ 3,  4,  5]], dtype=torch.int32) 
 tensor([[10.,  1.,  2.],
        [ 3.,  4.,  5.]])

print(b.type())
torch.IntTensor
print(c.type())
torch.FloatTensor

As can be seen a modification of the array element value, b tensor element values also changed, but has the same tensor c. Modify tensor element value c, a tensor array element value and b are the same. This shows torch.from_numpy (array) is doing an array of shallow copy, torch.Tensor (array) array is to do a deep copy .

Guess you like

Origin www.cnblogs.com/xym4869/p/11302160.html