我需要什么过滤器?只想保留高频值

What filter do I need? Want to keep high frequency values only

我问这个问题是因为我不太确定我应该使用哪个过滤器。

我的只是一个由离散值组成的信号 s = [1 2 2 2 3 4 2 4 3 4 5 3 2 3 3]。然后,我想要每个 window 大小的过滤信号。所以例如如果我对 s 使用大小为 5 的 window 那么我会得到; s_filtered = [2 2 2 2 2 4 4 4 4 4 3 3 3 3 3]。因此,我想保留每个块中频率最高的值。对于索引 0:4(window 大小 5),最高频率的值为 2,所以我希望我的 "filtered" 信号(如果这确实是正确的术语)在所有索引中都有 2 0:4 用于 "filtered" 信号。

目前我只使用中值滤波器,但我认为这不是正确的方法。

这里有一些 python 代码来演示我在做什么(但如上所述,我认为这是错误的)。

import numpy as np
import pylab *
from scipy.signal import medfilt

test = np.random.randint(10, size=1000)

fig, ax1 = plt.subplots(1,sharey=True, sharex=True, figsize=(15,5))
ax1.plot(test)
ax1.plot(medfilt(test,[99]),'r')
plt.show()

其中红线是 window 大小为 99 的过滤信号。

解决方案:

import itertools
import collections

def grouper(iterable, n, fillvalue=None):
    args = [iter(iterable)] * n
    return itertools.izip_longest(*args, fillvalue=fillvalue)

s = [1, 2, 2, 2, 3, 4, 2, 4, 3, 4, 5, 3, 2, 3, 3]

list(chain.from_iterable(repeat(collections.Counter(x).most_common(1)[0][0],5) for x in grouper(s,5)))

您可以使用 itertools recipes 中的 grouper 函数根据指定的长度对数组进行分组,然后使用 collections.Counter.most_common() 方法找到最常见的项目并使用 itertools.repeat重复你的项目 5 次,最后用 itertools.chain.from_iterable 链接重复的对象:

def grouper(iterable, n, fillvalue=None):
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

演示:

>>> list(chain.from_iterable(repeat(Counter(x).most_common(1)[0][0],5) for x in grouper(s,5)))
[2, 2, 2, 2, 2, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3]