如何使用给定范围删除重复项并强制 numpy 数组中的元素是唯一的



在差异进化的情况下,在突变过程中,最常用的公式是

arr[a] = (arr[b] + M * (arr[c] - arr[d])) % arr.shape[1]

哪里
arr 是一个由非负整数组成的二维数组,使得每行中的所有元素都是唯一的,
a表示每一行arr
M突变常数的范围在 0 到 2 之间,并且
bcd是3个唯一的随机数。

但是,在使用此公式时,我看到arr[a]具有基于arr[b]arr[c]arr[d]的值的重复值。我希望在arr[a]中只有唯一的数字。如何使用 Numpy?

例如

arr[a] = [2, 8, 4, 9, 1, 6, 7, 3, 0, 5]
arr[b] = [3, 5, 1, 2, 9, 8, 0, 6, 7, 4]
arr[c] = [2, 3, 8, 4, 5, 1, 0, 6, 9, 7]
arr[d] = [6, 1, 9, 2, 7, 5, 8, 0, 3, 4]

应用公式时,arr[a]变得[9, 7, 0, 4, 7, 4, 2, 2, 3, 7] .但我希望它只有 0arr.shape[1] 之间的唯一编号。如果需要,如果M,arr[b],arr[c]和arr[d]都被有意义地使用,我愿意修改突变函数。

这是一种相当不同的问题方法,但由于您似乎正在使用排列,我不确定数字差异是否有意义。但是,您可以从排列方面看到问题,即向量的重新排序。您可以考虑将您从一个向量带到另一个向量的排列,而不是两个向量之间的差异,而不是添加两个向量,您可以考虑对向量应用排列。如果你想有一个M参数,也许这可能是你应用排列的次数?(假设这是一个非负整数(

以下是如何实现它的基本思想:

import numpy as np
# Finds the permutation that takes you from vector a to vector b.
# Returns a vector p such that a[p] = b.
def permutation_diff(a, b):
    p = np.zeros_like(a)
    p[a] = np.arange(len(p), dtype=p.dtype)
    return p[b]
# Applies permutation p to vector a, m times.
def permutation_apply(a, p, m=1):
    out = a.copy()
    for _ in range(m):
        out = out[p]
    return out
# Combination function
def combine(b, c, d, m):
    return permutation_apply(b, permutation_diff(d, c), m)
# Test
b = np.array([3, 5, 1, 2, 9, 8, 0, 6, 7, 4])
c = np.array([2, 3, 8, 4, 5, 1, 0, 6, 9, 7])
d = np.array([6, 1, 9, 2, 7, 5, 8, 0, 3, 4])
m = 1
a = combine(b, c, d, m)
print(a)
# [2 7 0 4 8 5 6 3 1 9]

由于您正在使用排列在矩阵中的许多向量,因此您可能更喜欢上述函数的矢量化版本。你可以用这样的东西来获得它(这里我假设 M 是整个算法的固定参数,而不是每个单独的参数(:

import numpy as np
# Finds the permutations that takes you from vectors in a to vectors in b.
def permutation_diff_vec(a, b):
    p = np.zeros_like(a)
    i = np.arange(len(p))[:, np.newaxis]
    p[i, a] = np.arange(p.shape[-1], dtype=p.dtype)
    return p[i, b]
# Applies permutations in p to vectors a, m times.
def permutation_apply_vec(a, p, m=1):
    out = a.copy()
    i = np.arange(len(out))[:, np.newaxis]
    for _ in range(m):
        out = out[i, p]
    return out
# Combination function
def combine_vec(b, c, d, m):
    return permutation_apply_vec(b, permutation_diff_vec(d, c), m)
# Test
np.random.seed(100)
arr = np.array([[2, 8, 4, 9, 1, 6, 7, 3, 0, 5],
                [3, 5, 1, 2, 9, 8, 0, 6, 7, 4],
                [2, 3, 8, 4, 5, 1, 0, 6, 9, 7],
                [6, 1, 9, 2, 7, 5, 8, 0, 3, 4]])
n = len(arr)
b = arr[np.random.choice(n, size=n)]
c = arr[np.random.choice(n, size=n)]
d = arr[np.random.choice(n, size=n)]
m = 1
arr[:] = combine_vec(b, c, d, m)
print(arr)
# [[3 6 0 2 5 1 4 7 8 9]
#  [6 1 9 2 7 5 8 0 3 4]
#  [6 9 2 3 5 0 4 1 8 7]
#  [2 6 5 4 1 9 8 0 7 3]]

尝试这样做:

list(set(arr[a])) 

下面是一个可以做什么的例子:

array = np.array([9, 7, 0, 4, 7, 4, 2, 2, 3, 7])
shape = array.shape[0]
array = list(set(array))
for i in range(shape):
    if i not in array:
        array.append(i)
array = np.array(array)

如果要填写索引的数字是重复的,逻辑上有点不同。但想法是这样的。我希望我能帮助你。

最新更新