您当前的位置: 首页 >  Python

Xavier Jiezou

暂无认证

  • 4浏览

    0关注

    394博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

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

Xavier Jiezou 发布时间:2021-06-23 18:19:01 ,浏览量:4

文章目录
  • 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)

>>> b = a.numpy()
>>> b
array([1.], dtype=float32)
>>> type(b)

torch.Tensor➡list

list = tensor.tolist()

>>> import torch
>>> a = torch.Tensor([1])
>>> a
tensor([1.])
>>> type(a)

>>> b = a.tolist()
>>> b
[1.0]
>>> type(b)

numpy.ndarray➡torch.Tensor

tensor = torch.from_numpy(ndarray)

>>> import numpy as np
>>> import torch
>>> a = np.array([1])
>>> a
array([1])
>>> type(a)

>>> b = torch.from_numpy(a)
>>> b
tensor([1], dtype=torch.int32)
>>> type(b)

numpy.ndarray➡list

list = ndarray.tolist()

>>> import numpy as np
>>> a = np.array([1])
>>> a
array([1])
>>> type(a)

>>> b = a.tolist()
>>> b
[1]
>>> type(b)

list➡torch.Tensor

tensor = torch.Tensor(list)

>>> import torch
>>> a = [1]
>>> a
[1]
>>> type(a)

>>> b = torch.Tensor(a)
>>> b
tensor([1.])
>>> type(b)

list➡numpy.ndarray

ndarray = np.array(list)

>>> import numpy as np
>>> a = [1]
>>> a
[1]
>>> type(a)

>>> b = np.array(a)
>>> b
array([1])
>>> type(b)

关注
打赏
1661408149
查看更多评论
立即登录/注册

微信扫码登录

0.0402s