1.cuda.tensor转为numpy
解决:
{TypeError}can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.
设定cuda_tensor
是cuda上的数据,转为numpy类代码如下:
np_data = cuda_tensor.detach().cpu().numpy()
转换为numpy格式后:
2. tensor转为numpy
设定cpu_tensor
是cpu上的数据, 且没有梯度,转为numpy类代码如下:
np_data = cpu_tensor.numpy()
3. numpy转为tensor
import torch
import numpy as np
np_data = np.ones((3, 3))
tensor_1 = torch.tensor(np_data)
tensor_2 = torch.from_numpy(np_data)
tensor_2 += 1
print(f'np_data: \n {np_data}')
print(f'tensor_1: \n {tensor_1}')
print(f'tensor_2: \n {tensor_2}')
print('两者id是否相同:', id(tensor_1) == id(tensor_2))
np_data:
[[2. 2. 2.]
[2. 2. 2.]
[2. 2. 2.]]
tensor_1:
tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]], dtype=torch.float64)
tensor_2:
tensor([[2., 2., 2.],
[2., 2., 2.],
[2., 2., 2.]], dtype=torch.float64)
两者id是否相同: False
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)