在numpy数组Python之间查找一对匹配项

2024-09-27 09:33:00 发布

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

我在Python中有一个numpy数组,其中包含分类问题的标签。两个初始相同数组合并后派生的数组。在

labels = np.concatenate((labels1, labels2)) #labels1 and labels2 are identical

我想生成正/负对,它将包含来自标签(其中labels1和labels2相等)的所有索引,以及包含负索引的对。例如,如果我的输入如下:

^{pr2}$

然后我想以正数对的形式返回:

positive_pairs = {{1, 6}, {1, 7}, {2, 6}, {2, 7}, {3, 8}, {3, 9}, {4, 8}, {4, 9}, {5, 10}} # i dont want to have {1,2} or {3, 4} in within the positives
negative_pairs = {{1, 8}, {1, 9}, ...}

如何在python中这样做?在

编辑:如果标签1和标签2不相等,该怎么办?在


Tags: andnumpylabelsnp分类标签数组are
3条回答
outp = []
len1 = len(labels) // 2 # assume initially labels was [label1, label1]
label1 = labels[:len1]
label2 = labels[len1:]
set1 = set(label1)
for v in set1:
    eq1 = np.where(label1 == v)[0] + 1
    eq2 = np.where(label2 == v)[0] + len1 + 1
    outp.append(np.transpose([np.tile(eq1, len(eq2)), np.repeat(eq2, len(eq1))]))
outp = np.concatenate(outp).tolist()

# Edit: Find "negative pairs"
eq3 = np.indices((len1, ))[0][np.in1d(label2, list(set1), invert=True)] + len1 + 1
outn = np.transpose([np.tile(np.arange(len1), len(eq3)), np.repeat(eq3, len1)]).tolist()

以下是positive_pairs的解决方案:

labels1 = np.array([1, 1, 2, 2, 3])
length1 = len(labels1)
positive_pairs = []
for ii, label in enumerate(labels1, 1):
    for other in np.where(labels1 == label)[0] + length1 + 1:
        positive_pairs.append((ii, other))

negative_pairs留作练习。在

你可以这样完成

labels_1 = np.array([1,1,2,2,3])
labels_2 = np.array([1,1,2,2,3])
n = len(labels_1)
positive_pairs = [(i1+1, i2+n+1) for i1, l in enumerate(labels_1) 
                                 for i2 in np.where(labels_2 == l)[0]]

[(1,6),(1,7),(2,6),(2,7),...]

^{pr2}$

[(1,8),(1,9),(1,10),(2,8),...]

不过,我不确定这是最有效的方法。在

相关问题 更多 >

    热门问题