gpt4 book ai didi

python - numpy 数组可以在 GPU 中运行吗?

转载 作者:行者123 更新时间:2023-12-03 23:05:40 26 4
gpt4 key购买 nike

我正在使用 PyTorch。我有以下代码:

import numpy as np
import torch

X = np.array([[1, 3, 2, 3], [2, 3, 5, 6], [1, 2, 3, 4]])
X = torch.DoubleTensor(X).cuda()

X_split = np.array_split(X.numpy(),
indices_or_sections = 2,
axis = 0)
X_split
但我收到此错误:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-121-870b5d3f67b6> in <module>()
----> 1 X_prime_class_split = np.array_split(X_prime_class.numpy(),
2 indices_or_sections = 2,
3 axis = 0)
4 X_prime_class_split

TypeError: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.
错误消息很清楚,我知道如何通过包含 .cpu() 来修复此错误。 , IE。 X_prime_class.cpu().numpy() .我只是想知道这是否证实了 numpy 数组不能在 GPU/Cuda 中运行?

最佳答案

不,您通常不能在 GPU 阵列上运行 numpy 函数。 PyTorch 为 PyTorch 张量重新实现了 numpy 中的大部分功能。例如 torch.chunk np.array_split 类似所以你可以执行以下操作:

X = np.array([[1, 3, 2, 3], [2, 3, 5, 6], [1, 2, 3, 4]])
X = torch.DoubleTensor(X).cuda()
X_split = torch.chunk(X, chunks=2, dim=0)
split X无需移动 X 即可转换为多个张量关闭 GPU。

关于python - numpy 数组可以在 GPU 中运行吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62887574/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com