我有一個張量串列:
[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.
如何解決?
uj5u.com熱心網友回復:
你的張量仍然在 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.])
uj5u.com熱心網友回復:
NumPy 函式np.concatenate()要求輸入為 NumPy 陣列,但您的資料包含在張量中。該錯誤來自以下事實:嘗試將資料轉換為 NumPy 陣列時 NumPy 函式失敗,這本身是由于張量位于 GPU 上。
您可能希望將這些張量保留在 GPU 上,在這種情況下,您可以使用以下任一方法:
- 使用 PyTorch 時的
torch.cat()函式 - 如果您使用的是 TensorFlow,則該
tf.concat()函式
或者,您可以將張量移動到 CPU。要做到這一點,只需.cpu()在使用之前添加到您的張量中,np.concatenate()如錯誤所示。
uj5u.com熱心網友回復:
Numpy 在 CPU 上作業,但你的張量在 GPU 上。
使用torch.cat()來代替。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/337848.html
