请提供一段代码:使用Geatpy进行单目标优化
时间: 2024-05-13 08:21:10 浏览: 15
Sure, here's an example code for single objective optimization using Geatpy:
```
import geatpy as ga
import numpy as np
# Define the fitness function
def fitness_function(x):
return np.sum(x**2)
# Define the problem
problem = ga.Problem(fitness_function, # Objective function
np.array([[-10]*5, [10]*5]), # Domain bounds
np.array(['max']*1), # Objective sense (maximize)
np.array([5]*1), # Number of variables
np.array([1]*1), # Number of objectives
np.array([0]*5), # Lower bounds of variables
np.array([1]*5) # Upper bounds of variables
)
# Initialize the genetic algorithm
algorithm = ga.GA()
algorithm.setProblem(problem)
algorithm.setPopulationSize(50)
algorithm.setMaxGeneration(1000)
algorithm.setMutationProb(0.1)
algorithm.setSelection('tournament')
# Run the genetic algorithm
algorithm.run()
# Print the best solution and its fitness value
best_solution, best_fitness = algorithm.bestIndividual()
print("Best solution:", best_solution)
print("Best fitness:", best_fitness)
```
This code defines a fitness function that calculates the sum of squares of `x`, sets up a single-objective optimization problem with 5 variables, and applies a genetic algorithm to find the best solution. The algorithm runs for 1000 generations with a population size of 50 and a mutation probability of 0.1, and the tournament selection mechanism is employed. The best solution and its fitness value are printed at the end.
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)