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)