zl程序教程

您现在的位置是:首页 >  其他

当前栏目

pytorch tensor操作:tensor与numpy转换

转换numpyPyTorch 操作 Tensor
2023-06-13 09:14:28 时间

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.]

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/180366.html原文链接:https://javaforall.cn