二维阵列上滑动窗口分类器1-inn分类的有效多数表决

2024-06-28 20:02:08 发布

您现在位置:Python中文网/ 问答频道 /正文

简短版本:我想使用2D数组中的值来索引一个更大数组的相应子集的第三维度,然后递增这些元素。在

我会很感激帮助使这两个合并投票算法更快。实际上,在数组上滑动分类器并计算最佳步长并不是这里的重点。在

长版: 我有一个算法,它将R1xC1 2D数组中的每个元素分类为N个类中的1个。在

我想分类一个更大的2D数组大小R2xC2。与其将较大的数组细分为多个R1xC1 2D数组,不如将分类器滑动到更大的数组上,这样就可以对较大数组中的每个元素进行多次分类。这意味着我将有一个r2xcxn数组来存储结果,当窗口在大数组中滑动时,窗口中的每个像素将增加一个三维元素(即N个类中的一个)。在

在所有的滑动完成后,我们可以简单地得到对应于分类的维度中的argmax,从而得到每个元素的分类。在

我打算将其放大,将几百万像素的数组与几十个像素进行分类,因此我关心的是使用分类结果在每个元素的分类维度中增加一个值的效率。在

下面是我用Python3制作的问题的玩具版本。它有一个简单的double for-loop实现,还有一个稍微好一点的通过索引切换和一些智能索引实现的实现。分类器只是随机的。在

import numpy as np

map_rows = 8
map_cols = 10
num_candidates = 3
vote_rows = 6
vote_cols = 5


def display_tally(the_tally):
    print("{:25s}{:25s}{:25s}".format("Class 0", "Class 1", "Class 2"))
    for i in range(map_rows):
        for k in range(num_candidates):
            for j in range(map_cols):
                print("{:<2}".format(the_tally[i, j, k]), end='')
            print("     ", end='')
        print("")


def incorporate_votes(current_tally, this_vote, left, top):
    for i in range(vote_rows):
        for j in range(vote_cols):
            current_tally[top + i, left + j, this_vote[i, j]] += 1
    return current_tally


def incorporate_votes2(current_tally, this_vote, left, top):
    for i in range(num_candidates):
        current_tally[i, top:top + vote_rows, left:left + vote_cols][this_vote == i] += 1
    return current_tally


tally = np.zeros((map_rows, map_cols, num_candidates), dtype=int)
swizzled_tally = np.zeros((num_candidates, map_rows, map_cols), dtype=int)
print("Before voting")
display_tally(tally)

print("\n Votes from classifier A (centered at (2,2))")
votes = np.random.randint(num_candidates, size=vote_rows*vote_cols).reshape((vote_rows, vote_cols))
print(votes)

tally = incorporate_votes(tally, votes, 0, 0)
swizzled_tally = incorporate_votes2(swizzled_tally, votes, 0, 0)

print("\nAfter classifier A voting (centered at (2,2))")
display_tally(tally)

print("\n Votes from classifier B (Centered at (5, 4))")
votes2 = np.random.randint(num_candidates, size=vote_rows*vote_cols).reshape((vote_rows, vote_cols))
print(votes2)

tally = incorporate_votes(tally, votes2, 3, 2)
swizzled_tally = incorporate_votes2(swizzled_tally, votes2, 3, 2)

print("\nAfter classifier B voting (Centered at (5, 4))")
print("Naive vote counting")
display_tally(tally)
print("\nSwizzled vote counting")
display_tally(np.moveaxis(swizzled_tally, [-2, -1], [0, 1]))

new_tally = np.moveaxis(tally, -1, 0)
classifications = np.argmax(swizzled_tally, axis=0)
print("\nNaive classifications")
print(classifications)

print("\nSwizzled classifications")
classifications = np.argmax(tally, axis=2)
print(classifications)

以及一些示例输出:

^{pr2}$

Tags: mapfornp分类数组numrowsprint