python - 使用 Cupy 的 GPU FFT 卷积
问题描述
我正在尝试使用 Cupy 在 GPU 上执行 FFT 卷积操作。
使用 scipy.signal.fftconvolve 的源代码,我想出了以下基于 Numpy 的函数,它运行良好:
import numpy as np
def FFTConvolve(in1, in2):
if in1.ndim == in2.ndim == 0: # scalar inputs
return in1 * in2
elif not in1.ndim == in2.ndim:
raise ValueError("Dimensions do not match.")
elif in1.size == 0 or in2.size == 0: # empty arrays
return array([])
s1 = np.asarray(in1.shape)
s2 = np.asarray(in2.shape)
shape = s1 + s2 - 1
fsize = 2 ** np.ceil(np.log2(shape)).astype(int)
fslice = tuple([slice(0, int(sz)) for sz in shape])
ret = np.fft.ifft(np.fft.fft(in1, fsize) * np.fft.fft(in2, fsize))[fslice].copy()
return ret
我天真地为 Cupy 编写了如下程序:
import cupy as cp
def FFTConvolve(in1, in2):
if in1.ndim == in2.ndim == 0: # scalar inputs
return in1 * in2
elif not in1.ndim == in2.ndim:
raise ValueError("Dimensions do not match.")
elif in1.size == 0 or in2.size == 0: # empty arrays
return array([])
in1 = cp.asarray(in1)
in2 = cp.asarray(in2)
s1 = cp.asarray(in1.shape)
s2 = cp.asarray(in2.shape)
shape = s1 + s2 - 1
fsize = 2 ** cp.ceil(cp.log2(shape)).astype(int)
fslice = tuple([slice(0, int(sz)) for sz in shape])
ret = cp.fft.ifftn(cp.fft.fftn(in1, fsize) * cp.fft.fftn(in2, fsize))[fslice].copy()
return ret
后者在行上给了我以下错误enter code here
:
TypeError: 'cupy.core.core.ndarray' object cannot be interpreted as an integer
cupy.fft.ftt的文档声明它接受元组作为范围,但由于某种原因将其读取为 cupy.ndarray。
有人可以指出我正确的方向吗?
解决方案
解决方案是使用以下cp.asnumpy()
命令:
def FFTConvolve(in1, in2):
if in1.ndim == in2.ndim == 0: # scalar inputs
return in1 * in2
elif not in1.ndim == in2.ndim:
raise ValueError("Dimensions do not match.")
elif in1.size == 0 or in2.size == 0: # empty arrays
return array([])
s1 = np.asarray(in1.shape)
s2 = np.asarray(in2.shape)
shape = s1 + s2 - 1
fsize = 2 ** np.ceil(np.log2(shape)).astype(int)
fslice = tuple([slice(0, int(sz)) for sz in shape])
ret = cp.fft.ifftn(cp.fft.fftn(in1, np.asarray(fsize)) * cp.fft.fftn(in2, np.asarray(fsize)))[fslice].copy()
return ret
推荐阅读
- reactjs - React map() 多维数组
- python - 错误:字符串索引必须是整数
- python - 为什么在其列表元素中添加元素后元组大小不会改变
- php - Codeigniter 中的电子邮件发送错误“ fwrite(): send of 6 bytes failed with errno=10054 现有连接被远程主机强行关闭。”
- c - 为什么 strcmp() 在我的程序中不起作用?
- swift - SwiftUI - 等到 Firestore getDocuments() 完成后再继续
- visual-studio-code - 如何安装两个 VS Code?
- python - python 在聊天程序中,我必须按回车才能看到第二个人的消息,如何实时做到这一点?
- python - For循环不断让jupyter卡住
- utf-8 - 以前在 CodeIgniter 4 中将 URL 编码为 UTF-8