简体   繁体   English

将 PyTorch CUDA 张量转换为 Z3B7F949B2343F9E5390​​E29F6EF5E1778Z 数组

[英]Convert PyTorch CUDA tensor to NumPy array

How do I convert a torch.Tensor (on GPU) to a numpy.ndarray (on CPU)?如何将torch.Tensor (在 GPU 上)转换为numpy.ndarray (在 CPU 上)?

I believe you also have to use .detach() . 我相信您也必须使用.detach() I had to convert my Tensor to a numpy array on Colab which uses CUDA and GPU. 我必须在使用CUDA和GPU的Colab上将Tensor转换为numpy数组。 I did it like the following: 我这样做如下:

embedding = learn.model.u_weight

embedding_list = list(range(0, 64382))

input = torch.cuda.LongTensor(embedding_list)
tensor_array = embedding(input)
# the output of the line bwlow is a numpy array
tensor_array.cpu().detach().numpy() 

If the tensor is on gpu or cuda as you say. 如果张量在gpucuda如您所说。

You can use self.tensor.weight.data.cpu().numpy() It will copy the tensor to cpu and convert it to numpy array. 您可以使用self.tensor.weight.data.cpu().numpy()将张量复制到cpu并将其转换为numpy数组。

If the tensor is on cpu already you can do self.tensor.weight.data.numpy() as you correctly figured out, but you can also do self.tensor.weight.data.cpu().numpy() in this case since tensor is already on cpu , .cpu() operation will have no effect. 如果张量已经在cpu ,则可以按照正确的方法执行self.tensor.weight.data.numpy() ,但在这种情况下也可以执行self.tensor.weight.data.cpu().numpy()由于张量已经在cpu ,因此.cpu()操作将无效。 and this could be used as a device-agnostic way to convert the tensor to numpy array. 这可以用作将张量转换为numpy数组的与设备无关的方法。

some_tensor.detach().cpu().numpy()

  • .detach() detaches from the backward graph to avoid copying gradients. .detach()从后向图中分离以避免复制梯度。
  • .cpu() moves the data to CPU. .cpu()将数据移动到 CPU。
  • .numpy() converts the torch.Tensor to a np.ndarray . .numpy()torch.Tensor转换为np.ndarray

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM