Conditions shared between Tensor and numpy data in PyTorch:

Conditions shared between Tensor and numpy data in PyTorch:

When we are learning PyTorch, it will involve the high conversion efficiency between the Tensor data type and numpy data, here because their data memory is shared. However, in actual operation, you will find that the data is not updated when numpy is transferred to Tensor;

from __future__ import print_function

import numpy as np
import torch as t

'''
在实现numpy与Tensor数据互相操作时,数据是共享内存的;
但是我们在复制操作时,数据内存不是共享光的;
'''
a = np.zeros((2,2)).astype('int64')
b = t.Tensor(a) # 此时是复制的操作,不共享数据;
c = t.from_numpy(a)
print('-------a矩阵:——------')
print(a)
print('-------b矩阵:——------')
print(b)
print('-------c矩阵:——------')
print(c)
a[1]=1

print('修改后:')
print('-------a矩阵:——------')
print(a)
print('-------b矩阵:——------')
print(b)
print('-------c矩阵:——------')
print(c)

At this time, we can see that the data b matrix does not change, and the c matrix is ​​updated as the a matrix is ​​updated:

image-20200420194656621

Guess you like

Origin www.cnblogs.com/Zhao159461/p/12740000.html