从官网拷贝过来的,就是做个学习记录。版本 0.4


 

tensor to numpy

a = torch.ones(5)
print(a)

输出

tensor([1., 1., 1., 1., 1.])

进行转换

b = a.numpy()
print(b)

输出

[1. 1. 1. 1. 1.]

注意,转换后的tensor与numpy指向同一地址,所以,对一方的值改变另一方也随之改变

a.add_(1)
print(a)
print(b)

numpy to tensor

import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
np.add(a, 1, out=a)
print(a)
print(b)

输出

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

除chartensor外所有tensor都可以转换为numpy

相关文章:

  • 2022-03-02
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-26
  • 2022-01-10
  • 2023-02-10
猜你喜欢
  • 2022-12-23
  • 2021-12-27
  • 2021-04-26
  • 2022-12-23
  • 2022-12-23
  • 2021-11-30
  • 2022-01-01
相关资源
相似解决方案