Pythontorch.Tensornumpy.ndarraylist三者之间的相互转换

Posted Xavier Jiezou

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Pythontorch.Tensornumpy.ndarraylist三者之间的相互转换相关的知识,希望对你有一定的参考价值。


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'>

以上是关于Pythontorch.Tensornumpy.ndarraylist三者之间的相互转换的主要内容,如果未能解决你的问题,请参考以下文章