pytorch张量和numpy数组的转换

1.张量>>>>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.]

在张量中的改变也会影响numpy数组

t.add_(1)
print(f"t: {t}")
print(f"n: {n}")
t: tensor([2., 2., 2., 2., 2.])
n: [2. 2. 2. 2. 2.]

2.numpy数组>>>>张量

n = np.ones(5)
t = torch.from_numpy(n)

在numpy数组中的改变也会影响到张量

np.add(n, 1, out=n)
print(f"t: {t}")
print(f"n: {n}")
t: tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
n: [2. 2. 2. 2. 2.]
posted @ 2021-05-18 16:41  小Aer  阅读(12)  评论(0编辑  收藏  举报  来源