
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]])
注意:


>>> 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)

>>> 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)
>>> d.numpy()
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]])
GPU上的tensor不能和numpy直接转换。必须先转换为CPU上的tensor。
# 如果一个tensor的device是GPU,先使用如下命令转为CPU
tensor.cpu()
# 再使用tensor.numpy()进行转化
tensor.data.numpy()
# tensor到GPU
tensor.GPU()
使用tensor.item()可以直接将值取出来