如何np.用张量连接列表?



我有一个张量列表:

[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()函数,如果你使用PyTorch
  • tf.concat()函数,如果你使用TensorFlow

或者,您可以将张量移动到CPU。要做到这一点,只需在使用np.concatenate()之前将.cpu()添加到张量中,如错误所示。

Numpy在CPU上工作,但你的张量在GPU上。

torch.cat()代替。

最新更新