【发布时间】:2021-04-01 21:13:09
【问题描述】:
我编写了一个简单的遗传算法,旨在执行拟合。也就是说,给定一些输入f(x),我可以在不知道f 的情况下求解x(实际上,f(x) 根本不存在)。我的流程如下:
-
我生成一些初始点,均匀分布在已知的解区间
0,1。 -
然后我进行迭代,直到达到某个最大代数。在每次迭代中,我:
a) 按最小误差(RSS 误差)对当前点集进行排序,将它们存储在
parents列表中b) 保留第一个
500,并从初始列表中随机选择几个点c)
parents列表中的 1/2 点我“涂抹”,通过生成一个从高斯分布中提取的新点,其平均值由所选点给出d) 我现在通过生成“children”来填充
parents列表中剩余的“空槽”。通过从parents列表中随机选择两个点并取其平均值 ((male + female)/2) 生成子代。e) 最后,我设置初始列表等于父母列表,然后跳回到 a)
最后,我对列表进行最后一次排序,并选择第一个元素作为解决方案。
见下面的代码
我最终得到了一个还不错的解决方案。它似乎以惊人的速度跳到了解决方案的附近,但从那里没有取得太大进展。我仍然使用蛮力获得更好(并且更快)的结果。所以,我想改进我的算法。
几个注意事项:
我很清楚,这在某种程度上取决于我将算法应用到的问题。我有兴趣将它用于一些不同的事情。忽略这个问题,我可以用我拥有的做什么来改进它?
我也知道(可能)存在更好/更容易/更快/等方法。我只是对这个话题感兴趣。
我的代码:
initial = []
# Generate random initial test points
for i in range(5000):
initial.append(random.uniform(0,1))
for i in range(max_generations):
# Sort according to some error function
initial.sort(key = error_func)
# Keep the "best" 500
parents = initial[:500]
# Throw in a few random points
for i in range(randint(10,100)):
parents.append(initial[randint(0,len(parents) - 1)])
# "Mutate" half the parents
for individual in parents:
if randint(0,1):
individual = random.gauss(individual, 1E-5)
children = []
while len(children) < (5000 - len(parents)):
# Randomly pick a male and female
male = parents[randint(0, len(parents) - 1)]
female = parents[randint(0, len(parents) - 1)]
# Produce a child
children.append((male + female) / 2)
parents.extend(children)
initial = parents
initial.sort(key = error_func)
print(initial[0])
我正在考虑的几点:
-
我知道遗传算法有几种不同的方式来选择“最合适的”点(个人/成员/等)。也许有比仅按最小错误排序更好的方法?
-
通常是有更多的起点,还是更多的迭代/世代更好?
目标
#1:提高准确性和精确度 #2:提高找到“好”解决方案的速度
【问题讨论】:
标签: python algorithm mathematical-optimization genetic-algorithm evolutionary-algorithm