gpt4 book ai didi

python - 将 2D numpy 数组与随机分隔线组合

转载 作者:行者123 更新时间:2023-12-01 07:52:28 27 4
gpt4 key购买 nike

我有两个形状相同的 2D NumPy 数组:

>>> a.shape
(100, 100)
>>> b.shape
(100, 100)

我在遗传算法中使用这些,并希望实现 crossover 。我的想法是选择一条随机分隔线,一边为 a,一边为 b

该线将是经过 ptpt + delta 的线:

pt = np.random.uniform(a.shape)
angle = np.random.uniform(0, math.pi)
delta = np.array([math.cos(angle), math.sin(angle)])

如何创建一个新数组,使其等于该行上方的 a 且等于该行下方的 b?硬分界线很好,但对于奖励积分来说,将两者混合用于线上的像素将是理想的选择。

最佳答案

我正在与辅助数组分享一个想法,使用一个简单的线性函数:

# helper arrays for coordinate system
x = np.ones((100,100))
x[:,:] = np.arange(100)

y = np.ones((100,100))
y[:,:] = 100-np.arange(100).reshape(100,1) # 100- to invert y-axis

# linear function
def linfunc(x, m, n):
return x*m + n

其想法是在x 坐标上调用线性变换,然后检查结果是否等于、小于或大于y 坐标。然后可以使用此断言的结果来索引输入图像。

#test data:
a = np.ones((100,100))
b = np.zeros((100,100)) + 2
ab_mean = (a+b)/2

测试用例:

test_line = linfunc(x, 1, 0) #  y = x 
output = np.zeros_like(a)
output[y>test_line] = a[y>test_line] # assign above line to a
output[y<test_line] = b[y<test_line] # assign below line to b
output[y==test_line] = ab_mean[y==test_line] # assign coords on line to "interpolation"
plt.imshow(output)

enter image description here

test_line = linfunc(x, 1, 10) #  y = x + 10
output = np.zeros_like(a)
output[y>test_line] = a[y>test_line] # assign above line to a
output[y<test_line] = b[y<test_line] # assign below line to b
output[y==test_line] = ab_mean[y==test_line] # assign coords on line to "interpolation"
plt.imshow(output)

enter image description here

test_line = linfunc(x, -4, + 150) #  y = -4x + 150
output = np.zeros_like(a)
output[y>test_line] = a[y>test_line] # assign above line to a
output[y<test_line] = b[y<test_line] # assign below line to b
output[y==test_line] = ab_mean[y==test_line] # assign coords on line to "interpolation"
plt.imshow(output)

enter image description here

关于python - 将 2D numpy 数组与随机分隔线组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56135101/

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