1 listnumpy相互转换

  • list转numpy
import numpy as np

if __name__ == '__main__':
    a = [1,2,3,4]
    n = np.array(a)
    print(n)
  • numpy转list
import numpy as np

if __name__ == '__main__':
    n = np.arange(5)
    # 第一种方法
    #a = n.tolist()

    # 第二种方法
    a = list(n)

    print(a)

list与tensor相互转换

  • list转tensor
import numpy as np
import torch

if __name__ == '__main__':
    a = [1,2,3,4]

    t = torch.tensor(a)

    print(t)
  • tensor转list:

先转numpy再转list

import numpy as np
import torch

if __name__ == '__main__':

    t = torch.arange(5)

    a = t.numpy().tolist()

    print(a)

numpy与pytorch tensor相互转换

  • numpy转tensor
import numpy as np
import torch

if __name__ == '__main__':

    n = np.arange(5)

    t = torch.from_numpy(n)

    print(t)
  • tensor转numpy
import numpy as np
import torch

if __name__ == '__main__':

    t = torch.arange(5)

    n = t.numpy()

    print(n)

如果您觉得对您有帮助,可以请站长喝一杯咖啡哦!

记得在赞赏备注里写上您的昵称

您可在本站资助名单中查看你的打赏记录哦!

支付宝扫一扫

微信扫一扫

金额随意,礼清义重

当前分类随机文章推荐

全站随机文章推荐

关于本站站长 StubbornHuang
Python – list/numpy/pytorch tensor相互转换-StubbornHuang Blog纵使晴明无雨色,入云深处亦沾衣。