常用的API例子
1 tensor转为numpy
ps: gpu下的tensor不能直接转numpy,需要先转到cpu tensor后再转为numpy.cpu().numpy()
1 tensor.numpy()
x = torch.rand(6).view(2,3).type(torch.float32)
print(type(x))
x_array = x.numpy()
print(x_array,type(x_array))
output:
[[0.9542696 0.8235684 0.6300868 ]
[0.16127479 0.40761203 0.22885096]]
2 numpy转为tensor
1 torch.tensor(x)
x = np.array(3)
print(type(x))
x = torch.tensor(x)
print(type(x))
output:
2 torch.as_tensor()
x = np.ones(5)
print(type(x))
x = torch.as_tensor(x,dtype=torch.float32)
print(x,type(x))
output:
tensor([1., 1., 1., 1., 1.])
3 torch.from_numpy()
x = np.ones(5)
y = torch.ones(5)
print(x,type(x),y,type(y))
# numpy-->tensor
y = torch.from_numpy(x)
print(y,type(y),y.dtype)
output:
[1. 1. 1. 1. 1.]
tensor([1., 1., 1., 1., 1.], dtype=torch.float64)
来源地址:https://blog.csdn.net/m0_56676881/article/details/126912457