当前位置:   article > 正文

机器学习 - PyTorch tensor 和 numpy

机器学习 - PyTorch tensor 和 numpy

因为numpy是一个python numerical computing library, PyTorch 可以 interact with it nicely.

The two main methods you will want to use for NumPy to PyTorch (and back again) are:

  • torch.from_numpy(ndarray) - NumPy array -> PyTorch tensor
  • torch.Tensor.numpy() - PyTorch tensor -> NumPy array
import numpy as np

array = np.arange(1.0, 8.0)
tensor = torch.from_numpy(array)
print(array)
print(tensor)

# 输出结果
[1. 2. 3. 4. 5. 6. 7.]
tensor([1., 2., 3., 4., 5., 6., 7.], dtype=torch.float64)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

这里稍微介绍一下:
By default, NumPy arrays are created with the datatype float64 and if you convert it to a PyTorch tensor, it’ll keep the same datatype.

However, many PyTorch calculations default to using float32.

So if you want to convert your numpy array (float64) -> PyTorch tensor (float64) -> PyTorch tensor (float32), you can use tensor = torch.from_numpy(array).type(torch.float32)


下面是代码来展示,让tensor和numpy做两者之间的互相转换

import numpy as np

# Array to Tensor 
array = np.arange(1.0, 8.0)
tensor = torch.from_numpy(array)
print(f"array: {array}")
print(f"tensor 1: {tensor}")

array = array + 1
print(f"array: {array}")
tensor = tensor + 1
print(f"tensor 2: {tensor}")

# Tensor to Numpy array
tensor = torch.ones(7)
print(f"tensor 3: {tensor}")
numpy_tensor = tensor.numpy()
print(f"numpy_tensor: {numpy_tensor} | numpy_tensor datatype: {numpy_tensor.dtype}")

# Change the tensor, keep the array the same 
tensor = tensor + 1
print(f"tensor: {tensor}") 
print(f"numpy_tensor: {numpy_tensor}")

# 结果如下
array: [1. 2. 3. 4. 5. 6. 7.]
tensor 1: tensor([1., 2., 3., 4., 5., 6., 7.], dtype=torch.float64)
array: [2. 3. 4. 5. 6. 7. 8.]
tensor 2: tensor([2., 3., 4., 5., 6., 7., 8.], dtype=torch.float64)
tensor 3: tensor([1., 1., 1., 1., 1., 1., 1.])
numpy_tensor: [1. 1. 1. 1. 1. 1. 1.] | numpy_tensor datatype: float32

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

看到这了,点个赞支持一下咯~

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/273368?site
推荐阅读
相关标签
  

闽ICP备14008679号