import numpy as np
# Define the fitness function
def fitness(x):
# Maximize the functionf(x)= x^2return x**2
1.
2.
3.
4.
5.
6.
遗传算法参数:
# Define the GA parameters
POP_SIZE=100GENS=100CROSSOVER_PROB=0.8MUTATION_PROB=0.2
1.
2.
3.
4.
5.
初始种群:
# Initialize the population
pop = np.random.rand(POP_SIZE)
# Evaluate the fitness of the initial population
fitness_values = np.array([fitness(x)for x in pop])
for i inrange(len(offspring)): # Iterate over the correct range of offspring
if np.random.rand()<MUTATION_PROB:
offspring[i]+= np.random.normal(0,0.1)
1.
2.
3.
这里是完整的实现:
import numpy as np
# Define the fitness function
def fitness(x):
# Maximize the functionf(x)= x^2return x**2
# Define the GA parameters
POP_SIZE=100GENS=100CROSSOVER_PROB=0.8MUTATION_PROB=0.2
# Initialize the population
pop = np.random.rand(POP_SIZE)
# Evaluate the fitness of the initial population
fitness_values = np.array([fitness(x)for x in pop])
# Main GA loop
for gen inrange(GENS):
# Selection
parents = np.array([pop[np.argmax(fitness_values)]for _ inrange(POP_SIZE//2)])
# Crossover
offspring =[]for _ inrange(POP_SIZE//2):
parent1, parent2 = parents[np.random.randint(0,len(parents),2)]
child =(parent1 + parent2)/2
offspring.append(child)
# Mutation
for i inrange(len(offspring)): # Iterate over the correct range of offspring
if np.random.rand()<MUTATION_PROB:
offspring[i]+= np.random.normal(0,0.1)
# Replace the population with the newoffspring
pop = offspring
# Evaluate the fitness of the newpopulation
fitness_values = np.array([fitness(x)for x in pop])
# Print the best fitness value
print(f"Generation {gen+1}, Best Fitness: {np.max(fitness_values)}")
# Print the final best solution
print(f"Final Best Solution: {pop[np.argmax(fitness_values)]}")
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
输出:
Generation 1, Best Fitness:1.4650152220573687
Generation 2, Best Fitness:1.8054426063247935
Generation 3, Best Fitness:2.1124584418178354
Generation 4, Best Fitness:2.34514080269685.....
Generation 99, Best Fitness:254.58556629300833
Generation 100, Best Fitness:260.9705918019082
Final Best Solution:16.154584234882314
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import cross_val_score
from sklearn.ensemble import RandomForestClassifier
from deap import base, creator, tools, algorithms
# Load the iris dataset
iris =load_iris()X= iris.data
y = iris.target
# Define the number of features to select
num_features =3
# Define the fitness function
def fitness(individual):
# Select the features based on the individual
selected_indices =[i for i, x inenumerate(individual)if x ==1]
# Handle the case where no features are selected
if not selected_indices:return0, # Return a low fitness value if no features are selected
selected_features = np.array([X[:, i]for i in selected_indices]).T
# Create a random forest classifier with the selected features
clf =RandomForestClassifier(n_estimators=100)
# Evaluate the model using cross-validation
scores =cross_val_score(clf, selected_features, y, cv=5)
# Return the mean score as the fitness value
return np.mean(scores),
# Create a DEAP creator for the fitness function
creator.create("FitnessMax", base.Fitness, weights=(1.0,))
creator.create("Individual", list, fitness=creator.FitnessMax)
# Create a DEAP toolbox for the GA
toolbox = base.Toolbox()
toolbox.register("attr_bool", np.random.choice,[0,1])
toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_bool, n=len(X[0]))
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
toolbox.register("mate", tools.cxTwoPoint)
toolbox.register("mutate", tools.mutFlipBit, indpb=0.05)
toolbox.register("select", tools.selTournament, tournsize=3)
toolbox.register("evaluate", fitness)
# Create a population of50 individuals
pop = toolbox.population(n=50)
# Evaluate the initial population
fitnesses = toolbox.map(toolbox.evaluate, pop)for ind, fit inzip(pop, fitnesses):
ind.fitness.values = fit
# Run the GAfor20 generations
for g inrange(20):
offspring = algorithms.varAnd(pop, toolbox, cxpb=0.5, mutpb=0.1)
fits = toolbox.map(toolbox.evaluate, offspring)for fit, ind inzip(fits, offspring):
ind.fitness.values = fit
pop = toolbox.select(offspring, k=len(pop))
# Print the best individual and the corresponding fitness value
best_individual = tools.selBest(pop, k=1)[0]print("Best Individual:", best_individual)print("Best Fitness:", best_individual.fitness.values[0])
# Select the features based on the best individual
selected_features = np.array([X[:, i]for i, x inenumerate(best_individual)if x ==1]).T
# Print the selected features
print("Selected Features:", selected_features)
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
输出:
Best Individual:[0,0,1,1]
Best Fitness:0.9666666666666668
Selected Features:[[1.40.2][1.40.2]...[5.11.8]]