- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一系列长度为 n = 36,000 的信号,我需要对其执行互相关。目前,我在 numpy 中的 cpu 实现有点慢。我听说 Pytorch 可以大大加快张量运算,并提供了一种在 GPU 上并行执行计算的方法。我想探索这个选项,但我不太确定如何使用该框架完成此操作。
由于这些信号的长度,我更愿意在频域中执行互相关操作。
通常使用 numpy 我会像这样执行操作:
import numpy as np
signal_length=36000
# make the signals
signal_1 = np.random.uniform(-1,1, signal_length)
signal_2 = np.random.uniform(-1,1, signal_length)
# output target length of crosscorrelation
x_cor_sig_length = signal_length*2 - 1
# get optimized array length for fft computation
fast_length = np.fftpack.next_fast_len(x_cor_sig_length)
# move data into the frequency domain. axis=-1 to perform
# along last dimension
fft_1 = np.fft.rfft(src_data, fast_length, axis=-1)
fft_2 = np.fft.rfft(src_data, fast_length, axis=-1)
# take the complex conjugate of one of the spectrums. Which one you choose depends on domain specific conventions
fft_1 = np.conj(fft_1)
fft_multiplied = fft_1 * fft_2
# back to time domain.
prelim_correlation = np.fft.irfft(result, x_corr_sig_length, axis=-1)
# shift the signal to make it look like a proper crosscorrelation,
# and transform the output to be purely real
final_result = np.real(np.fft.fftshift(prelim_correlation),axes=-1)).astype(np.float64)
查看 Pytorch 文档,似乎没有 numpy.conj() 的等效项。我也不确定在 irfft 操作后是否/如何需要实现 fftshift。
那么您将如何使用傅立叶方法在 Pytorch 中编写一维互相关?
最佳答案
需要考虑的几件事。
Python 解释器非常慢,这些矢量化库所做的是将工作负载转移到本地实现。为了有所作为,您需要能够在一条 python 指令中执行许多操作。在 GPU 上评估事物遵循相同的原则,虽然 GPU 具有更多的计算能力,但将数据复制到 GPU 或从 GPU 复制数据的速度较慢。
我调整了您的示例以同时处理多个信号。
import numpy as np
def numpy_xcorr(BATCH=1, signal_length=36000):
# make the signals
signal_1 = np.random.uniform(-1,1, (BATCH, signal_length))
signal_2 = np.random.uniform(-1,1, (BATCH, signal_length))
# output target length of crosscorrelation
x_cor_sig_length = signal_length*2 - 1
# get optimized array length for fft computation
fast_length = next_fast_len(x_cor_sig_length)
# move data into the frequency domain. axis=-1 to perform
# along last dimension
fft_1 = np.fft.rfft(signal_1, fast_length, axis=-1)
fft_2 = np.fft.rfft(signal_2 + 0.1 * signal_1, fast_length, axis=-1)
# take the complex conjugate of one of the spectrums.
fft_1 = np.conj(fft_1)
fft_multiplied = fft_1 * fft_2
# back to time domain.
prelim_correlation = np.fft.irfft(fft_multiplied, fast_length, axis=-1)
# shift the signal to make it look like a proper crosscorrelation,
# and transform the output to be purely real
final_result = np.fft.fftshift(np.real(prelim_correlation), axes=-1)
return final_result, np.sum(final_result)
从 torch 1.7 开始,我们有了 torch.fft提供类似于 numpy.fft 的接口(interface)的模块,缺少 fftshift 但可以使用 torch.roll 获得相同的结果.另一点是 numpy 默认使用 64 位精度,而 torch 将使用 32 位精度。
快速长度在于选择平滑数(那些被分解为小质数的数,我想你对这个主题很熟悉)。
def next_fast_len(n, factors=[2, 3, 5, 7]):
'''
Returns the minimum integer not smaller than n that can
be written as a product (possibly with repettitions) of
the given factors.
'''
best = float('inf')
stack = [1]
while len(stack):
a = stack.pop()
if a >= n:
if a < best:
best = a;
if best == n:
break; # no reason to keep searching
else:
for p in factors:
b = a * p;
if b < best:
stack.append(b)
return best;
然后 torch 实现开始
import torch;
import torch.fft
def torch_xcorr(BATCH=1, signal_length=36000, device='cpu', factors=[2,3,5], dtype=torch.float):
signal_length=36000
# torch.rand is random in the range (0, 1)
signal_1 = 1 - 2*torch.rand((BATCH, signal_length), device=device, dtype=dtype)
signal_2 = 1 - 2*torch.rand((BATCH, signal_length), device=device, dtype=dtype)
# just make the cross correlation more interesting
signal_2 += 0.1 * signal_1;
# output target length of crosscorrelation
x_cor_sig_length = signal_length*2 - 1
# get optimized array length for fft computation
fast_length = next_fast_len(x_cor_sig_length, [2, 3])
# the last signal_ndim axes (1,2 or 3) will be transformed
fft_1 = torch.fft.rfft(signal_1, fast_length, dim=-1)
fft_2 = torch.fft.rfft(signal_2, fast_length, dim=-1)
# take the complex conjugate of one of the spectrums. Which one you choose depends on domain specific conventions
fft_multiplied = torch.conj(fft_1) * fft_2
# back to time domain.
prelim_correlation = torch.fft.irfft(fft_multiplied, dim=-1)
# shift the signal to make it look like a proper crosscorrelation,
# and transform the output to be purely real
final_result = torch.roll(prelim_correlation, (fast_length//2,))
return final_result, torch.sum(final_result);
这里是测试结果的代码
import time
funcs = {'numpy-f64': lambda b: numpy_xcorr(b, factors=[2,3,5], dtype=np.float64),
'numpy-f32': lambda b: numpy_xcorr(b, factors=[2,3,5], dtype=np.float32),
'torch-cpu-f64': lambda b: torch_xcorr(b, device='cpu', factors=[2,3,5], dtype=torch.float64),
'torch-cpu': lambda b: torch_xcorr(b, device='cpu', factors=[2,3,5], dtype=torch.float32),
'torch-gpu-f64': lambda b: torch_xcorr(b, device='cuda', factors=[2,3,5], dtype=torch.float64),
'torch-gpu': lambda b: torch_xcorr(b, device='cuda', factors=[2,3,5], dtype=torch.float32),
}
times ={}
for batch in [1, 10, 100]:
times[batch] = {}
for l, f in funcs.items():
t0 = time.time()
t1, t2 = f(batch)
tf = time.time()
del t1
del t2
times[batch][l] = 1000 * (tf - t0) / batch;
我得到了如下结果
令我惊讶的是当数字不是那么平滑时的结果,例如使用 17 平滑长度的 torch 实现要好得多,所以我在这里使用对数刻度(批量大小为 100 时,torch gpu 比批量大小为 1 的 numpy 快 10000 倍)。
请记住,这些函数通常在 GPU 上生成数据,我们希望将最终结果复制到 CPU,如果我们考虑将最终结果复制到 CPU 所花费的时间,我观察到的时间比互相关高 10 倍计算(随机数据生成 + 三个 FFT)。
关于python-3.x - 如何在傅立叶域中实现长信号的 Pytorch 一维互相关?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56711772/
我有一个 Haskell 程序,它用 Metropolis 模拟 Ising 模型 算法。主要操作是一个模板操作,它需要下一个的总和 2D 中的邻居,然后将其与中心元素相乘。那么 元素可能已更新。 在
对于卷积,我想在一个维度上应用圆形填充,在所有其他维度上应用零填充。我该怎么做? 对于卷积,有 28 个 channel ,并且数据在球形箱中描述。半径时间有 20 个箱子,极地时间有 20 个箱子,
假设您有一个数组并想创建另一个数组,该数组的值连续等于第一个数组的 10 个元素的标准差。在 for 循环的帮助下,它可以像下面的代码一样轻松编写。我想要做的是避免使用 for 循环来加快执行时间。有
我有一个长度为size * size的一维数组,表示值的平方字段。 我的目标是将数组旋转到位(previous question)。我目前在获取正确的内圈索引方面遇到问题。我的算法有什么错误? 这是我
stride = 1 和 1 个过滤器的 1D CNN 的输出长度不应该等于输入长度而不需要填充吗? 我认为是这种情况,但创建了一个具有这些规范的 Keras 模型,当输入形状为 (17910,1)
我有一个零散布的一维数组。想创建第二个数组,其中包含最后一个零的位置,如下所示: >>> a = np.array([1, 0, 3, 2, 0, 3, 5, 8, 0, 7, 12]) >>> fo
我试着去理解卡尔曼滤波器是如何工作的,因为多维变量太混乱了,一开始我从一维的例子开始。 我发现有3个不同的来源解释温度计的情况,但所有这些情况实现的方程略有不同,我没有得到重点。 我实现了解决方案2,
我有一个二维数组,我需要将它转换为一个列表(同一对象)。我不想使用 for 或 foreach 循环来执行此操作,它们将获取每个元素并将其添加到列表中。还有其他方法吗? 最佳答案 好吧,你可以让它使用
我正在使用 Keras 构建一个 CNN,将以下 Conv1D 作为我的第一层: cnn.add(Conv1D( filters=512, kernel_size=3, str
在 Python 中使用 TensorFlow,我正在制作一个以一维数组作为输入的神经网络。我想在网络中添加一个卷积层,但似乎无法让它工作。 我的训练数据如下所示: n_samples = 20 le
我有一个简单的一维数组,但我想使用 jQuery 将长列表分成两列。我怎样才能实现这个目标? var articles = ['article10','article9','article8','ar
我有一个刚从文件中读入的 float 的一维 vector 。 std::vector result(s.size() / sizeof(float)); 我想像这样使用这些数据 myTable[rl
使用 numpy 将 data reshape 为 fencepost 的最有效方法是什么? data = np.array([1, 2, 3, 4, 5])
我正在尝试通过删除 for 循环并仅在处理大型数据集时使用 numpy 数组来优化一些代码。 我想采用一维 numpy 数组,例如: a = [1, 2, 3, 4, 5] 并生成一个 2D nump
我正在尝试为两个数组 Pages 和 Price 赋值。 #include int main() { static int pages[3]; static int price[3];
我是深度学习、keras API 和卷积网络的新手,如果这些错误是幼稚的,请事先致歉。我正在尝试构建一个用于分类的简单卷积神经网络。输入数据 X 有 286 个样本,每个样本有 500 个时间点,4
假设我有 Numpy 数组 p 和一个 Scipy 稀疏矩阵 q 这样 >>> p.shape (10,) >>> q.shape (10,100) 我想做 p 和 q 的点积。当我尝试使用 nump
我需要一些行为类似于 std::vector 的东西(界面/功能/等)但我需要它是平坦的,即它不能动态分配缓冲区。显然,这通常不起作用,因为可用大小必须在编译时确定。但我希望类型能够处理N没有额外分配
作为我正在运行的一些模拟的一部分,我需要最终对一些非常长的(实数)数字序列执行以下操作。这是要点: 给定一个长的一维 NumPy 数组,对于数组中的每个位置,我想对该位置前后的值进行平均,取平均值之间
这个问题在这里已经有了答案: Concatenating two one-dimensional NumPy arrays (6 个答案) 关闭 5 年前。 我想将 numpy 数组存储到另一个 n
我是一名优秀的程序员,十分优秀!