Tensor和Numpy互相转换

常用的API例子

1 tensor转为numpy

ps:  gpu下的tensor不能直接转numpy,需要先转到cpu tensor后再转为numpy.cpu().numpy()

1.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:

<class 'torch.Tensor'>

[[0.9542696  0.8235684  0.6300868 ]

[0.16127479 0.40761203 0.22885096]] <class 'numpy.ndarray'>

2 numpy转为tensor

2.1 torch.tensor(x)

x = np.array(3)

print(type(x))

x = torch.tensor(x)

print(type(x))

output:

<class 'numpy.ndarray'>

<class 'torch.Tensor'>

2.2 torch.as_tensor()

x = np.ones(5)

print(type(x))

x = torch.as_tensor(x,dtype=torch.float32)

print(x,type(x))

output:

<class 'numpy.ndarray'>

tensor([1., 1., 1., 1., 1.]) <class 'torch.Tensor'>

2.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.] <class 'numpy.ndarray'> tensor([1., 1., 1., 1., 1.]) <class 'torch.Tensor'>

tensor([1., 1., 1., 1., 1.], dtype=torch.float64) <class 'torch.Tensor'> torch.float64

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
心中带点小风骚的头像心中带点小风骚普通用户
上一篇 2023年3月5日 下午9:04
下一篇 2023年3月5日 下午9:05

相关推荐