如何 np.concatenate 列出张量?

How to np.concatenate list with tensors?

我有张量列表:

[tensor([[0.4839, 0.3282, 0.1773,  ..., 0.2931, 1.2194, 1.3533],
        [0.4395, 0.3462, 0.1832,  ..., 0.7184, 0.4948, 0.3998]],
        device='cuda:0'),
 tensor([[1.0586, 0.2390, 0.2315,  ..., 0.9662, 0.1495, 0.7092],
        [0.6403, 0.0527, 0.1832,  ..., 0.1467, 0.8238, 0.4422]],
        device='cuda:0')]

我想通过 np.concatenate(X) 将所有 [1xfeatures] 矩阵堆叠为一个。但出现此错误:

TypeError: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.

如何解决?

您的张量仍在 GPU 上,而 numpy 操作发生在 CPU 上。您可以先将两个张量发送回 cpu numpy.concatenate((a.cpu(), b.cpu()),如错误消息所示。

或者您可以避免离开 GPU 而使用 torch.cat()

a = torch.ones((6),)
b = torch.zeros((6),)

torch.cat([a,b], dim=0)
# tensor([1., 1., 1., 1., 1., 1., 0., 0., 0., 0., 0., 0.])

NumPy 函数 np.concatenate() 要求输入为 NumPy 数组,但您的数据包含在张量中。错误来自 NumPy 函数在尝试将数据转换为 NumPy 数组时失败,这本身是由于张量位于 GPU 上。

您可能希望将这些张量保留在您的 GPU 上,在这种情况下,您可以使用:

  • torch.cat() function 如果您使用的是 PyTorch
  • tf.concat() function 如果您使用的是 TensorFlow

或者,您可以将张量移动到 CPU。为此,只需在使用 np.concatenate() 之前将 .cpu() 添加到您的张量,如错误所示。

Numpy 在 CPU 上运行,但您的张量在 GPU 上。

改用torch.cat()