用mathematica写一个遗传算法。
时间: 2023-10-06 14:14:36 浏览: 189
遗传算法是一种优化算法,用于在搜索空间中寻找最优解。下面是一个用Mathematica编写的遗传算法示例,用于求解二元函数的最小值。
首先,定义目标函数:
f[x_, y_] := x^2 + y^2
接下来,定义遗传算法所需的各个函数:
1. 随机种群生成函数
generatePopulation[size_, range_] :=
Table[RandomReal[range, 2], {size}]
2. 适应度函数
fitnessFunction[population_] :=
Map[f @@ # &, population]
3. 选择函数
selectParents[fitness_, numParents_] :=
RandomSample[fitness -> Range[Length[fitness]], numParents]
4. 交叉函数
crossover[parents_, crossoverRate_] :=
Module[{child1, child2},
If[RandomReal[] < crossoverRate,
{child1, child2} =
Transpose@
MapThread[
Join[#[[1 ;; 1]], #[[2 ;; 2]]] &,
Partition[parents, 2]];
{child1, child2}, parents]]
5. 变异函数
mutation[population_, mutationRate_, range_] :=
Module[{mutated},
mutated =
Map[If[RandomReal[] < mutationRate, # +
RandomReal[range {-1, 1}, 2], #] &, population];
mutated]
6. 求最优解函数
findMin[f_, populationSize_, crossoverRate_, mutationRate_,
numGenerations_, range_] :=
Module[{population, fitness, parents, children, elite,
eliteFitness},
population = generatePopulation[populationSize, range];
Do[
fitness = fitnessFunction[population];
parents = selectParents[fitness, 2];
children = crossover[parents, crossoverRate];
population = Join[population, children];
population = mutation[population, mutationRate, range];
fitness = fitnessFunction[population];
elite = First@SortBy[population, f @@ # &];
eliteFitness = f @@ elite;
population =
Take[SortBy[population, f @@ # &], populationSize];
If[Mod[i, 10] == 0,
Print["Generation ", i, ": Best fitness = ", eliteFitness]];
, {i, numGenerations}];
elite]
最后,运行算法:
findMin[f, 50, 0.8, 0.05, 100, {-5, 5}]
其中,50是种群大小,0.8是交叉概率,0.05是变异概率,100是迭代次数,{-5, 5}是搜索空间。
阅读全文