pytorch: tensor与numpy之间的转换

2023-05-16

训练时,输入一般为tensor,但在计算误差时一般用numpy;tensor和numpy的转换采用numpy()和from_numpy这两个函数机型转换。值得注意的是,这两个函数所产生的tensor和numpy是共享相同内存的,而且两者之间转换很快。

import torch
import numpy as np

# Convert tensor to numpy
a = torch.ones(3)
b = a.numpy()
print(a, b)
a += 1
print(a, b)

# Convert numpy to tensor
c = np.ones(3)
d = torch.from_numpy(c)
print(c, d)
c += 1
print(c, d)

输出为:
tensor([1., 1., 1.]) [1. 1. 1.]
tensor([2., 2., 2.]) [2. 2. 2.]
[1. 1. 1.] tensor([1., 1., 1.], dtype=torch.float64)
[2. 2. 2.] tensor([2., 2., 2.], dtype=torch.float64)

另外,还有一个numpy转换为tensor的函数,但不共享内存,转换较慢

import torch
import numpy as np

e = np.array([1,2,3])
f = torch.tensor(e)
print(e, f)
e += 1
print(e, f)

输出为:
[1 2 3] tensor([1, 2, 3], dtype=torch.int32)
[2 3 4] tensor([1, 2, 3], dtype=torch.int32)

再另外介绍一个取数字的函数:item() ,该函数把tensor和numpy的数转化为数的类型。例如,type(a[0])和type(b[0])分别为tensor和numpy,用item()就可以转化为int或float。当要把训练结果写入到excel保存时,只能时python的原生数字形式,该函数就发挥作用了。

print(type(a[1]))
print(type(b[1]))
print(type(a[1].item()))
print(type(b[1].item()))

<class ‘torch.Tensor’>
<class ‘numpy.float32’>
<class ‘float’>
<class ‘float’>

注意·:该函数只能用在对象引用一个数组,不能用在包含一个数组的对象,如a.item()或b.item()

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

pytorch: tensor与numpy之间的转换 的相关文章

随机推荐