.numpy()和.from_numpy()负责将tensor和numpy中的数组互相转换,共享共同内存,不共享地址
torch.tensor()复制数据,但不共享地址
#tensor转numpy,共享内存但不共享地址 a=torch.ones(5) b=a.numpy() print(a,b) print(id(a)==id(b)) a+=1 print(a,b) print(id(a)==id(b)) b+=1 print(a,b) print(id(a)==id(b)) ''' tensor([1., 1., 1., 1., 1.]) [1. 1. 1. 1. 1.] False tensor([2., 2., 2., 2., 2.]) [2. 2. 2. 2. 2.] False tensor([3., 3., 3., 3., 3.]) [3. 3. 3. 3. 3.] False '''
#numpy'转tenor,同样共享内存 import numpy as np a=np.ones(5) b=torch.from_numpy(a) print(a,b) a+=1 print(a,b) b+=1 print(a,b) ''' [1. 1. 1. 1. 1.] tensor([1., 1., 1., 1., 1.], dtype=torch.float64) [2. 2. 2. 2. 2.] tensor([2., 2., 2., 2., 2.], dtype=torch.float64) [3. 3. 3. 3. 3.] tensor([3., 3., 3., 3., 3.], dtype=torch.float64) '''
#torch.tensor复制数据,但是不共享内存 c=torch.tensor(a) a+=1 print(a,c) ''' [4. 4. 4. 4. 4.] tensor([3., 3., 3., 3., 3.], dtype=torch.float64) '''