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.])
<class ‘torch.Tensor’>
[1. 1. 1. 1. 1.]
<class ‘numpy.ndarray’>
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.]
<class ‘numpy.ndarray’>
tensor([1., 1., 1., 1., 1.], dtype=torch.float64)
<class ‘torch.Tensor’>
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.]
<class ‘numpy.ndarray’>
tensor([1., 1., 1., 1., 1.], dtype=torch.float64)
<class ‘torch.Tensor’>