Noa*_*kel 6 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()
如果张量为gpu或cuda,则将张量复制到cpu并使用以下方法将其转换为 numpy 数组:
tensor.data.cpu().numpy()
Run Code Online (Sandbox Code Playgroud)
如果张量已经打开,cpu你可以这样做tensor.data.numpy()。但是,您也可以这样做
tensor.data.cpu().numpy()。如果张量已经打开cpu,则该.cpu()操作将不起作用。这可以用作与设备无关的方式将张量转换为 numpy 数组。
我相信你也必须使用.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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17881 次 |
| 最近记录: |