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()
文章来源:https://www.toymoban.com/news/detail-400511.html
>>> 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。文章来源地址https://www.toymoban.com/news/detail-400511.html
# 如果一个tensor的device是GPU,先使用如下命令转为CPU
tensor.cpu()
# 再使用tensor.numpy()进行转化
tensor.data.numpy()
# tensor到GPU
tensor.GPU()
参考
- https://pytorch.org/docs/1.2.0/torch.html#torch.as_tensor
到了这里,关于tensor与numpy的相互转换的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!