站点图标 AI技术聚合

tensor与numpy的相互转换

tensor与numpy的相互转换

1. numpy转tensor

命令1:torch.tensor()

 a = np.random.random(size=(4,5))
 b = torch.tensor(a,dtype=torch.float)
====输出========
>> a
array([[0.93866392, 0.5665604 , 0.32893379, 0.77752777, 0.59380636],
       [0.09680724, 0.09611474, 0.69760508, 0.9120742 , 0.07956756],
       [0.46761691, 0.7771953 , 0.23979901, 0.52539619, 0.99063046],
       [0.05881101, 0.77289148, 0.22587614, 0.6438252 , 0.82986165]])

>>b
tensor([[0.9387, 0.5666, 0.3289, 0.7775, 0.5938],
        [0.0968, 0.0961, 0.6976, 0.9121, 0.0796],
        [0.4676, 0.7772, 0.2398, 0.5254, 0.9906],
        [0.0588, 0.7729, 0.2259, 0.6438, 0.8299]])

注意

命令2:torch.as_tensor()

>>> c =torch.as_tensor(a)
>>> c
tensor([[0.9387, 0.5666, 0.3289, 0.7775, 0.5938],
        [0.0968, 0.0961, 0.6976, 0.9121, 0.0796],
        [0.4676, 0.7772, 0.2398, 0.5254, 0.9906],
        [0.0588, 0.7729, 0.2259, 0.6438, 0.8299]], dtype=torch.float64)

命令3:torch.from_numpy()

>>> d = torch.from_numpy(a)
>>> d
tensor([[0.9387, 0.5666, 0.3289, 0.7775, 0.5938],
        [0.0968, 0.0961, 0.6976, 0.9121, 0.0796],
        [0.4676, 0.7772, 0.2398, 0.5254, 0.9906],
        [0.0588, 0.7729, 0.2259, 0.6438, 0.8299]], dtype=torch.float64)

区别:转换之后,numpy.array和tensor中的数据是否仍指向相同的内存地址

  • torch.from_numpy(np.array)torch.as_tensor(),均会指向相同的内存地址。
  • torch.tensor()不会指向相同的内存地址,是深度copy。从下面的实例可以看到,修改numpy的值,tensor的值不会改变
n = np.ones(5)
t = torch.as_tensor(n)
t1 = torch.from_numpy(n)
t2 = torch.tensor(n)
print('numpy n = ', n)
print('torch t =', t)
print('torch t1 =', t1)
print('torch t2 =', t2)

n += 1
print("\nafter add 1, numpy = ", n)
print('torch t = ', t)
print('torch t1 = ', t1)
print('torch t2 = ', t2)

# 输出。
numpy n =  [1. 1. 1. 1. 1.]
torch t = tensor([1., 1., 1., 1., 1.], dtype=torch.float64)
torch t1 = tensor([1., 1., 1., 1., 1.], dtype=torch.float64)
# numpy +1之后,三种方式转换出来的tensor的变化
after add 1, numpy =  [2. 2. 2. 2. 2.]
torch t =  tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
torch t1 =  tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
torch t2 =  tensor([1., 1., 1., 1., 1.], dtype=torch.float64)

2. tensor转numpy

命令1:tensor.numpy()

命令2:np.array(tensor)

对比

  • tensor.numpy()之后,仍会指向相同的内存地址
  • np.array(tensor)之后,不会指向相同的内存地址
t = torch.ones(5)
n1 = t.numpy()
n2 = np.array(t)
print('numpy n1 = ', n1)
print('numpy n2 = ', n2)
print('torch t =', t)

t += 1

print("\nafter +1 ")
print("numpy n1= ", n1)
print("numpy n2 = ", n2)
print('torch = ', t)

# 输出结果
numpy n1 =  [1. 1. 1. 1. 1.]
numpy n2 =  [1. 1. 1. 1. 1.]
torch t = tensor([1., 1., 1., 1., 1.])

after +1 
numpy n1=  [2. 2. 2. 2. 2.]
numpy n2 =  [1. 1. 1. 1. 1.]  # 没有改变
torch =  tensor([2., 2., 2., 2., 2.])

注意:

GPU上的tensor不能和numpy直接转换。必须先转换为CPU上的tensor。

# 如果一个tensor的device是GPU,先使用如下命令转为CPU
tensor.cpu()  
# 再使用tensor.numpy()进行转化
tensor.data.numpy()
# tensor到GPU
tensor.GPU()

参考

  1. https://pytorch.org/docs/1.2.0/torch.html#torch.as_tensor

文章出处登录后可见!

已经登录?立即刷新
退出移动版