使用Cuda将Pytorch张量转换为Numpy数组

时间:2018-11-25 12:01:06

标签: python numpy pytorch

我想使用cuda将Pytorch张量转换为numpy数组:

这是不使用cuda的代码行:

  

A = self.tensor.weight.data.numpy()

如何使用cuda进行相同的操作? 据此:https://discuss.pytorch.org/t/how-to-transform-variable-into-numpy/104/3 似乎:

  

A = self.tensor.weight.data.cpu()。numpy()

2 个答案:

答案 0 :(得分:1)

如您所说,如果张量在gpucuda上。

您可以使用self.tensor.weight.data.cpu().numpy(),它将张量复制到cpu并将其转换为numpy数组。

如果张量已经在cpu上,则可以按照正确的方法进行self.tensor.weight.data.numpy(),但是在这种情况下,由于张量已经在{{1}上,因此您也可以执行self.tensor.weight.data.cpu().numpy() },cpu操作将无效。这可以用作将张量转换为numpy数组的与设备无关的方法。

答案 1 :(得分:1)

我相信您还必须使用 .detach()。我必须在使用CUDA和GPU的Colab上将Tensor转换为numpy数组。我这样做如下:

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()