如何通过多数投票将 filter/resample 与 类 排列?

How to filter/resample array with classes by majority voting?

假设我有一个包含 4 个 class 的数组或 pandas 系列,但 class 每一步变化很大。这只是一个例子(如果你愿意,你可以生成一个更真实的例子):

import numpy as np

np.random.seed(seed=0) # to generate always the same numbers
x = np.random.randint(4, size=(100))

由于它们差异很大,我想通过多数表决技术或其他方法对它们进行升级(或过滤或重新采样)。也许查看 5 个最近的样本,然后该特定样本将具有最频繁的 class。最后我会得到一个数组 'packed' 面。

这个方案应该代表我的意思:

有人能帮帮我吗?

我不会说这很漂亮,但它似乎可以解决问题。

import numpy as np    

def majorityVoting(index, array, groupSize=5):
    groupSizeFloor = groupSize // 2
    arrayCount = len(array)

    if index <= groupSizeFloor:
        first = 0
        last = groupSize
    elif index >= arrayCount - (groupSize // 2):
        first = arrayCount - groupSize
        last = arrayCount
    else:
        first = index - groupSizeFloor
        last = index + groupSizeFloor + 1

    return np.bincount(array[first:last]).argmax()

np.random.seed(seed=0)
arr = np.random.randint(4, size=100)
majoritySorted = [majorityVoting(i, arr) for i in range(len(arr))]