Tensor和numpy相互转换

tensor转成numpy

import torch
import numpy as np
a = torch.ones(5)
b = a.numpy()
print(a)
print(type(a))
print(b)
print(type(b))

tensor([1., 1., 1., 1., 1.])

[1. 1. 1. 1. 1.]

numpy转成tensor

import torch
import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
print(a)
print(type(a))
print(b)
print(type(b))

[1. 1. 1. 1. 1.]

tensor([1., 1., 1., 1., 1.], dtype=torch.float64)

import torch
import numpy as np
a = np.ones(5)
b = torch.tensor(a)
print(a)
print(type(a))
print(b)
print(type(b))

[1. 1. 1. 1. 1.]

tensor([1., 1., 1., 1., 1.], dtype=torch.float64)

你可能感兴趣的:(Tensor和numpy相互转换)