【Python】torch.Tensor、numpy.ndarray、list三者之间的相互转换

文章目录

  • torch.Tensor➡numpy.ndarray
  • torch.Tensor➡list
  • numpy.ndarray➡torch.Tensor
  • numpy.ndarray➡list
  • list➡torch.Tensor
  • list➡numpy.ndarray


torch.Tensor➡numpy.ndarray

ndarray = tensor.numpy()

>>> import torch
>>> a = torch.Tensor([1])
>>> a
tensor([1.])
>>> type(a)
<class 'torch.Tensor'>
>>> b = a.numpy()
>>> b
array([1.], dtype=float32)
>>> type(b)
<class 'numpy.ndarray'>

torch.Tensor➡list

list = tensor.tolist()

>>> import torch
>>> a = torch.Tensor([1])
>>> a
tensor([1.])
>>> type(a)
<class 'torch.Tensor'>
>>> b = a.tolist()
>>> b
[1.0]
>>> type(b)
<class 'list'>

numpy.ndarray➡torch.Tensor

tensor = torch.from_numpy(ndarray)

>>> import numpy as np
>>> import torch
>>> a = np.array([1])
>>> a
array([1])
>>> type(a)
<class 'numpy.ndarray'>
>>> b = torch.from_numpy(a)
>>> b
tensor([1], dtype=torch.int32)
>>> type(b)
<class 'torch.Tensor'>

numpy.ndarray➡list

list = ndarray.tolist()

>>> import numpy as np
>>> a = np.array([1])
>>> a
array([1])
>>> type(a)
<class 'numpy.ndarray'>
>>> b = a.tolist()
>>> b
[1]
>>> type(b)
<class 'list'>

list➡torch.Tensor

tensor = torch.Tensor(list)

>>> import torch
>>> a = [1]
>>> a
[1]
>>> type(a)
<class 'list'>
>>> b = torch.Tensor(a)
>>> b
tensor([1.])
>>> type(b)
<class 'torch.Tensor'>

list➡numpy.ndarray

ndarray = np.array(list)

>>> import numpy as np
>>> a = [1]
>>> a
[1]
>>> type(a)
<class 'list'>
>>> b = np.array(a)
>>> b
array([1])
>>> type(b)
<class 'numpy.ndarray'>

你可能感兴趣的:(python,python)