gpt4 book ai didi

python - 改变 numpy 数组中一致值的比例

转载 作者:行者123 更新时间:2023-12-05 06:50:47 26 4
gpt4 key购买 nike

我有一个问题一直在努力思考。假设我有一个看起来像这样的 numpy 数组(在实际实现中,len(array) 将在 4500 左右):

array = np.repeat([0, 1, 2], 2)
array >> [0, 0, 1, 1, 2, 2]

据此,我尝试生成一个新的(打乱的)数组,其中与 array 随机一致的值的比例是特定比例 p。假设 p = .5。然后,一个示例新数组将类似于

    array = [0, 0, 1, 1, 2, 2]
new_array = [0, 1, 2, 1, 0, 2]

您可以在其中看到 new_array 中恰好 50% 的值与 array 中的值一致。输出数组的要求是:

np.count_nonzero(array - new_array)/len(array) = p,和
set(np.unique(array)) == set(np.unique(new_array))

“同意”是指 array[i] == new_array[i] 同意索引 inew_array 中的所有值都应与 array 相同,只是打乱了顺序。

我确信有一种优雅的方式可以做到这一点——有人能想到什么吗?

谢谢!

最佳答案

你可以尝试类似的东西

import random

p = 0.5

arr = np.array([0, 0, 1, 1, 2, 2])

# number of similar elements required
num_sim_element = round(len(arr)*p)

# creating indeices of similar element
hp = {}
for i,e in enumerate(arr):
if(e in hp):
hp[e].append(i)
else:
hp[e] = [i]
#print(hp)

out_map = []

k = list(hp.keys())
v = list(hp.values())
index = 0

while(len(out_map) != num_sim_element):
if(len(v[index]) > 0):
k_ = k[index]
random.shuffle(v[index])
v_ = v[index].pop()

out_map.append((k_,v_))

index += 1
index %= len(k)

#print(out_map)

out_unique = set([i[0] for i in out_map])
out_indices = [i[-1] for i in out_map]

out_arr = arr.copy()
#for i in out_map:
# out_arr[i[-1]] = i[0]

for i in set(range(len(arr))).difference(out_indices):
out_arr[i] = random.choice(list(out_unique.difference([out_arr[i]])))


print(arr)
print(out_arr)

assert 1 - (np.count_nonzero(arr - out_arr) / len(arr)) == p
assert set(np.unique(arr)) == set(np.unique(out_arr))

[0 0 1 1 2 2]
[1 0 1 0 0 2]

关于python - 改变 numpy 数组中一致值的比例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66335622/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com