【问题标题】:Indexing list of cuda tensors gives error - "can't convert cuda:0 device type tensor to numpy"cuda 张量的索引列表给出错误 - “无法将 cuda:0 设备类型张量转换为 numpy”
【发布时间】:2022-01-03 07:18:54
【问题描述】:

我有一个 cuda 张量列表:

>>> X_train
[tensor([  101,  3533...='cuda:0'), tensor([  101,  3422...='cuda:0'), tensor([  101,  2054...='cuda:0'), tensor([ 101, 1019, ...='cuda:0'), tensor([  101, 14674...='cuda:0'), tensor([  101,  9246...='cuda:0'), tensor([  101,  2054...='cuda:0'), tensor([  101,  2339...='cuda:0), ... ]

我正在尝试应用 k 折交叉验证。所以我想使用 k-fold 索引列表来索引这个列表:

>>> X_train[train_index]

但它给了我错误:

TypeError: only integer scalar arrays can be converted to a scalar index

根据this 的回答,问题是我无法使用索引列表来索引列表。在 numpy 中是允许的。

所以我尝试将其转换为 numpy:

np.array(X_train)

但它给了我错误:

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

我真的必须在索引之前将这些单独的 cuda 张量移动到 cpu 吗? 如何轻松索引此 cuda 张量列表,同时将它们保留在 cuda 上(以利用 GPU 进行训练模型)?或者它不可能,我应该首先索引它们(首先将它们形成为numpy数组)然后将索引的移动到cuda?是否有任何标准/首选做法来处理数据?

【问题讨论】:

  • 您是否尝试过使用torch.stack(X_train, dim=0) 将列表转换为张量?

标签: python numpy pytorch


【解决方案1】:

仅仅为了索引而转换为 确实是一个糟糕的选择: 这会导致 GPU 和 CPU 之间的复制操作,通常可以disrupt PyTorch's computational graph

你可以做的是使用list comprehension:

subset = [X_train[i_] for i_ in train_index]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-19
    • 2020-09-09
    • 1970-01-01
    • 1970-01-01
    • 2019-04-27
    • 2020-07-09
    • 2019-05-22
    相关资源
    最近更新 更多