当前位置: 首页 > 工具软件 > CuPy > 使用案例 >

cupy中tensor数据类型与numpy以及pytorch中相互转换

潘宪
2023-12-01

1.cupy与numpy互转

import cupy as cp
import numpy as np

#cupy->numpy
numpy_data = cp.asnumpy(cupy_data)

#numpy->cupy
cupy_data = cp.asarray(numpy_data)

2.cupy与pytorch互转

需要借助中间库 dlpack,三者关系是:cupy.array<–>Dlpack.Tensor<–>torch.Tensor

from cupy.core.dlpack import toDlpack
from cupy.core.dlpack import fromDlpack
from torch.utils.dlpack import to_dlpack
from torch.utils.dlpack import from_dlpack
import torch

#pytorch->cupy
cupy_data = fromDlpack(to_dlpack(tensor_data))

#cupy->pytorch
tensor_data = from_dlpack(toDlpack(cupy_data))

3.numpy与pytorch互转

import numpy as np
import torch

#pytorch->numpy
numpy_data = tensor_data.numpy()

#numpy->pytorch
tensor_data = torch.from_numpy(numpy_data)

此博客参考了https://blog.csdn.net/l297969586/article/details/102824246,如有侵权,请联系要求删除。

 类似资料: