美文网首页
pytorch tensor操作:tensor与numpy转换

pytorch tensor操作:tensor与numpy转换

作者: ltochange | 来源:发表于2021-08-05 23:49 被阅读0次

tensor转numpy

t = torch.ones(5)
print(f"t: {t}")
n = t.numpy()
print(f"n: {n}")

输出:

t: tensor([1., 1., 1., 1., 1.])
n: [1. 1. 1. 1. 1.]

cpu上的tensor可以和numpy array共享内存地址,改变其中的一个另一个也会改变

t.add_(1)
print(f"t: {t}")
print(f"n: {n}")

输出:

t: tensor([2., 2., 2., 2., 2.])
n: [2. 2. 2. 2. 2.]

可训练的tensor转numpy

t = torch.ones(5)
t_trained = t.clone().detach().requires_grad_(True)
print(f"t_trained: {t_trained}")
n = t_trained.detach().numpy()
print(f"n: {n}")

输出:

t_trained: tensor([1., 1., 1., 1., 1.], requires_grad=True)
n: [1. 1. 1. 1. 1.]

numpy转tensor

n = np.ones(5)
t = torch.from_numpy(n)
np.add(n, 1, out=n)
# n = np.add(n, 1) 不改变t,非in_place操作
print(f"t: {t}")
print(f"n: {n}")

输出:

t: tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
n: [2. 2. 2. 2. 2.]

相关文章

网友评论

      本文标题:pytorch tensor操作:tensor与numpy转换

      本文链接:https://www.haomeiwen.com/subject/mlzvvltx.html