使用Cuda将Pytorch张量转换为Numpy数组 [英] Convert Pytorch Tensor to Numpy Array using Cuda
问题描述
我想使用cuda将Pytorch张量转换为numpy数组:
I would like to convert a Pytorch tensor to numpy array using cuda:
这是不使用cuda时的代码行:
this is the code line while not using cuda:
A = self.tensor.weight.data.numpy()
A = self.tensor.weight.data.numpy()
如何使用cuda进行相同的操作? 据此: https://discuss. pytorch.org/t/how-to-to-transform-variable-into-numpy/104/3 似乎:
How can I do the same operation using cuda? According to this: https://discuss.pytorch.org/t/how-to-transform-variable-into-numpy/104/3 it seems:
A = self.tensor.weight.data.cpu().numpy()
A = self.tensor.weight.data.cpu().numpy()
推荐答案
我相信您还必须使用 .detach().我必须在使用CUDA和GPU的Colab上将Tensor转换为numpy数组.我这样做如下:
I believe you also have to use .detach(). I had to convert my Tensor to a numpy array on Colab which uses CUDA and GPU. 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()
这篇关于使用Cuda将Pytorch张量转换为Numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!