1 作業(yè)內容描述
1.1 背景
-
現在有一個函數 3 ? s i n 2 ( j x 1 ) ? s i n 2 ( j x 2 ) 3-sin^2(jx_1)-sin^2(jx_2) 3?sin2(jx1?)?sin2(jx2?),有兩個變量 x 1 x_1 x1? 和 x 2 x_2 x2?,它們的定義域為 x 1 , x 2 ∈ [ 0 , 6 ] x_1,x_2\in[0,6] x1?,x2?∈[0,6],并且 j = 2 j=2 j=2,對于此例,所致對于 j = 2 , 3 , 4 , 5 j=2,3,4,5 j=2,3,4,5分別有 16,36,64,100 個全局最優(yōu)解。
-
現在有一個Shubert函數 ∏ i = 1 n ∑ j = 1 5 j cos ? [ ( j + 1 ) x i + j ] \prod_{i=1}^{n}\sum_{j=1}^{5}j\cos[(j+1)x_i+j] ∏i=1n?∑j=15?jcos[(j+1)xi?+j],其中定義域為 ? 10 < x i < 10 -10<x_i<10 ?10<xi?<10,對于此問題,當n=2時有18個不同的全局最優(yōu)解
1.2 要求
- 求該函數的最小值即 m i n ( 3 ? s i n 2 ( j x 1 ) ? s i n 2 ( j x 2 ) ) min(3-sin^2(jx_1)-sin^2(jx_2)) min(3?sin2(jx1?)?sin2(jx2?)),j=2,精確到小數點后6位。
- 求該Shubert函數的最小值即 m i n ( ∏ i = 1 2 ∑ j = 1 5 j cos ? [ ( j + 1 ) x i + j ] ) min(\prod_{i=1}^{2}\sum_{j=1}^{5}j\cos[(j+1)x_i+j]) min(∏i=12?∑j=15?jcos[(j+1)xi?+j]),精確到小數點后6位
2 作業(yè)已完成部分和未完成部分
該作業(yè)已經全部完成,沒有未完成的部分。
![]() |
![]() |
---|---|
Colab Notebook | Github Rep |
3. 作業(yè)運行結果截圖
最后跑出的結果如下:
- 第一個函數的最小值為 1.0000000569262162
- 第二個函數的最小值為-186.73042323192567
4 核心代碼和步驟
4.1 基本的步驟
- 定義目標函數
objective_function
:使用了一個二維的目標函數,即 3 ? s i n 2 ( j x 1 ) ? s i n 2 ( j x 2 ) 3-sin^2(jx_1)-sin^2(jx_2) 3?sin2(jx1?)?sin2(jx2?)。 - 定義選擇函數
crossover
:用于交叉操作,通過交叉率(crossover_rate)確定需要進行交
叉的父母對的數量,并在這些父母對中交換某些變量的值。
- 定義變異函數
mutate
:用于變異操作,通過變異率(mutation_rate)確定需要進行變異
的父母對的數量,并在這些父母對中隨機改變某些變量的值。
- 定義進化算法
evolutionary_algorithm
:初始化種群,其中每個個體都是一個二維向量。在
每一代中,計算每個個體的適應度值,繪制三維圖表展示種群分布和最佳解。
- 更新全局最佳解。根據適應度值確定復制的數量并形成繁殖池。選擇父母、進行交叉和變
異,更新種群。重復上述步驟直到達到指定的迭代次數。
- 設置算法參數:
population_size
:種群大小。;num_generations:迭代的次數。;muta
tion_rate:變異率。;crossover_rate:交叉率。
- 運行進化算法
evolutionary_algorithm
:調用進化算法函數并獲得最終的最佳解、最佳適
應度值和每一代的演化數據。
-
輸出結果:打印最終的最佳解和最佳適應度值。輸出每個迭代步驟的最佳適應度值。
-
可視化結果:繪制函數曲面和最優(yōu)解的三維圖表。繪制適應度值隨迭代次數的變化曲線。
4.2 第一個函數 3 ? s i n 2 ( j x 1 ) ? s i n 2 ( j x 2 ) 3-sin^2(jx_1)-sin^2(jx_2) 3?sin2(jx1?)?sin2(jx2?)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# 定義目標函數
def objective_function(x):
j = 2
return 3 - np.sin(j * x[0])**2 - np.sin(j * x[1])**2 # 3 - sin(2x1)^2 - sin(2x2)^2
# 定義選擇函數
def crossover(parents_1, parents_2, crossover_rate):
num_parents = len(parents_1) # 父母的數量
num_crossover = int(crossover_rate * num_parents) # 選擇進行交叉的父母對的數量
# 選擇進行交叉的父母對
crossover_indices = np.random.choice(num_parents, size=num_crossover, replace=False) # 選擇進行交叉的父母對的索引
# 復制父母
copy_parents_1 = np.copy(parents_1)
copy_parents_2 = np.copy(parents_2)
# 進行交叉操作
for i in crossover_indices:
parents_1[i][1] = copy_parents_2[i][1] # 交叉變量x2
parents_2[i][1] = copy_parents_1[i][1] # 交叉變量x2
return parents_1, parents_2
# 定義變異函數
def mutate(parents_1, parents_2, mutation_rate):
num_parents = len(parents_1) # 父母的數量
num_mutations = int(mutation_rate * num_parents) # 選擇進行變異的父母對的數量
# 選擇進行變異的父母對
mutation_indices = np.random.choice(num_parents, size=num_mutations, replace=False) # 選擇進行變異的父母對的索引
# 進行變異操作
for i in mutation_indices:
parents_1[i][1] = np.random.uniform(0, 6) # 變異變量x2
parents_2[i][1] = np.random.uniform(0, 6) # 變異變量x2
return parents_1, parents_2
# 定義進化算法
def evolutionary_algorithm(population_size, num_generations, mutation_rate, crossover_rate):
bounds = [(0, 6), (0, 6)] # 變量的取值范圍
# 保存每個迭代步驟的信息
evolution_data = []
# 初始化種群
population = np.random.uniform(bounds[0][0], bounds[0][1], size=(population_size, 2))
# 設置初始的 best_solution
best_solution = population[0] # 選擇種群中的第一個個體作為初始值
best_fitness = objective_function(best_solution) # 計算初始值的適應度值
for generation in range(num_generations):
# 計算適應度
fitness_values = np.apply_along_axis(objective_function, 1, population)
# 找到當前最佳解
current_best_index = np.argmin(fitness_values)
current_best_solution = population[current_best_index]
current_best_fitness = fitness_values[current_best_index]
# 繪制每次迭代的三維分布圖
fig = plt.figure() # 創(chuàng)建一個新的圖形
ax = fig.add_subplot(111, projection='3d') # 創(chuàng)建一個三維的坐標系
ax.scatter(population[:, 0], population[:, 1], fitness_values, color='black', marker='.', label='Population') # 繪制種群的分布圖
ax.scatter(best_solution[0], best_solution[1], best_fitness, s=100, color='red', marker='o', label='Best Solution') # 繪制最佳解的分布圖
# 設置坐標軸的標簽
ax.set_xlabel('X1')
ax.set_ylabel('X2')
ax.set_zlabel('f(x)')
ax.set_title(f'Generation {generation} - Best Fitness: {best_fitness:.6f}')
ax.legend() # 顯示圖例
plt.show() # 顯示圖形
# 更新全局最佳解
if current_best_fitness < best_fitness: # 如果當前的最佳解的適應度值小于全局最佳解的適應度值
best_solution = current_best_solution
best_fitness = current_best_fitness
# 保存當前迭代步驟的信息
evolution_data.append({
'generation': generation,
'best_solution': best_solution,
'best_fitness': best_fitness
})
# 根據適應度值確定復制的數量并且形成繁殖池
reproduction_ratios = fitness_values / np.sum(fitness_values) # 計算每個個體的適應度值占總適應度值的比例
sorted_index_ratios = np.argsort(reproduction_ratios) # 對比例進行排序
half_length = len(sorted_index_ratios) // 2 # 選擇前一半的個體
first_half_index = sorted_index_ratios[:half_length] # 選擇前一半的個體的索引
new_half_population = population[first_half_index] # 選擇前一半的個體
breeding_pool = np.concatenate((new_half_population, new_half_population)) # 將前一半的個體復制一份,形成繁殖池
# 選擇父母
parents_1 = breeding_pool[:half_length]
parents_2 = breeding_pool[half_length:] # 先獲取最后一半的父母
parents_2 = np.flip(parents_2, axis=0) # 再將父母的順序反轉
# 選擇和交叉
parents_1, parents_2 = crossover(parents_1, parents_2, crossover_rate)
# 變異
parents_1, parents_2 = mutate(parents_1, parents_2, mutation_rate)
# 更新種群
population = np.vstack([parents_1, parents_2])
return best_solution, best_fitness, evolution_data
# 設置算法參數
population_size = 10000
num_generations = 40
mutation_rate = 0.1 # 變異率
crossover_rate = 0.4 # 交叉率
# 運行進化算法
best_solution, best_fitness, evolution_data = evolutionary_algorithm(population_size, num_generations, mutation_rate, crossover_rate)
# 輸出結果
print("最小值:", best_fitness)
print("最優(yōu)解:", best_solution)
# 輸出每個迭代步驟的最佳適應度值
print("每個迭代步驟的最佳適應度值:")
for step in evolution_data:
print(f"Generation {step['generation']}: {step['best_fitness']}")
# 可視化函數曲面和最優(yōu)解
x1_vals = np.linspace(0, 6, 100)
x2_vals = np.linspace(0, 6, 100)
X1, X2 = np.meshgrid(x1_vals, x2_vals)
Z = 3 - np.sin(2 * X1)**2 - np.sin(2 * X2)**2
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X1, X2, Z, alpha=0.5, cmap='viridis')
ax.scatter(best_solution[0], best_solution[1], best_fitness, color='red', marker='o', label='Best Solution')
ax.set_xlabel('X1')
ax.set_ylabel('X2')
ax.set_zlabel('f(x)')
ax.set_title('Objective Function and Best Solution')
ax.legend()
# 繪制適應度值的變化曲線
evolution_df = pd.DataFrame(evolution_data)
plt.figure()
plt.plot(evolution_df['generation'], evolution_df['best_fitness'], label='Best Fitness')
plt.xlabel('Generation')
plt.ylabel('Fitness')
plt.title('Evolution of Fitness')
plt.legend()
plt.show()
4.3 Shubert 函數的最小值
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# 定義目標函數
def objective_function(x):
result = 1
for i in range(1, 3):
inner_sum = 0
for j in range(1, 6):
inner_sum += j * np.cos((j + 1) * x[i - 1] + j)
result *= inner_sum
return result
# 定義選擇函數
def crossover(parents_1, parents_2, crossover_rate):
num_parents = len(parents_1) # 父母的數量
num_crossover = int(crossover_rate * num_parents) # 選擇進行交叉的父母對的數量
# 選擇進行交叉的父母對
crossover_indices = np.random.choice(num_parents, size=num_crossover, replace=False) # 選擇進行交叉的父母對的索引
# 復制父母
copy_parents_1 = np.copy(parents_1)
copy_parents_2 = np.copy(parents_2)
# 進行交叉操作
for i in crossover_indices:
parents_1[i][1] = copy_parents_2[i][1] # 交叉變量x2
parents_2[i][1] = copy_parents_1[i][1] # 交叉變量x2
return parents_1, parents_2
# 定義變異函數
def mutate(parents_1, parents_2, mutation_rate):
num_parents = len(parents_1) # 父母的數量
num_mutations = int(mutation_rate * num_parents) # 選擇進行變異的父母對的數量
# 選擇進行變異的父母對
mutation_indices = np.random.choice(num_parents, size=num_mutations, replace=False) # 選擇進行變異的父母對的索引
# 進行變異操作
for i in mutation_indices:
parents_1[i][1] = np.random.uniform(-10, 10) # 變異變量x2
parents_2[i][1] = np.random.uniform(-10, 10) # 變異變量x2
return parents_1, parents_2
# 定義進化算法
def evolutionary_algorithm(population_size, num_generations, mutation_rate, crossover_rate):
bounds = [(-10, 10), (-10, 10)] # 變量的取值范圍
# 保存每個迭代步驟的信息
evolution_data = []
# 初始化種群
population = np.random.uniform(bounds[0][0], bounds[0][1], size=(population_size, 2))
# 設置初始的 best_solution
best_solution = population[0] # 選擇種群中的第一個個體作為初始值
best_fitness = objective_function(best_solution) # 計算初始值的適應度值
for generation in range(num_generations):
# 計算適應度
fitness_values = np.apply_along_axis(objective_function, 1, population)
# 找到當前最佳解
current_best_index = np.argmin(fitness_values)
current_best_solution = population[current_best_index]
current_best_fitness = fitness_values[current_best_index]
# 繪制每次迭代的三維分布圖
fig = plt.figure() # 創(chuàng)建一個新的圖形
ax = fig.add_subplot(111, projection='3d') # 創(chuàng)建一個三維的坐標系
ax.scatter(population[:, 0], population[:, 1], fitness_values, color='black', marker='.', label='Population') # 繪制種群的分布圖
ax.scatter(current_best_solution[0], current_best_solution[1], current_best_fitness, s=100, color='red', marker='o', label='Best Solution') # 繪制最佳解的分布圖
# 設置坐標軸的標簽
ax.set_xlabel('X1')
ax.set_ylabel('X2')
ax.set_zlabel('f(x)')
ax.set_title(f'Generation {generation} - Best Fitness: {current_best_fitness:.6f}')
ax.legend() # 顯示圖例
plt.show() # 顯示圖形
# 更新全局最佳解
if current_best_fitness < best_fitness: # 如果當前的最佳解的適應度值小于全局最佳解的適應度值
best_solution = current_best_solution
best_fitness = current_best_fitness
# 保存當前迭代步驟的信息
evolution_data.append({
'generation': generation,
'best_solution': best_solution,
'best_fitness': best_fitness
})
# 根據適應度值確定復制的數量并且形成繁殖池
reproduction_ratios = fitness_values / np.sum(fitness_values) # 計算每個個體的適應度值占總適應度值的比例
sorted_index_ratios = np.argsort(reproduction_ratios) # 對比例進行排序
half_length = len(sorted_index_ratios) // 2 # 選擇后一半的個體
first_half_index = sorted_index_ratios[half_length:] # 選擇后一半的個體的索引
new_half_population = population[first_half_index] # 選擇后一半的個體
breeding_pool = np.concatenate((new_half_population, new_half_population)) # 將后一半的個體復制一份,形成繁殖池
# 選擇父母
parents_1 = breeding_pool[:half_length]
parents_2 = breeding_pool[half_length:] # 先獲取最后一半的父母
parents_2 = np.flip(parents_2, axis=0) # 再將父母的順序反轉
# 選擇和交叉
parents_1, parents_2 = crossover(parents_1, parents_2, crossover_rate)
# 變異
parents_1, parents_2 = mutate(parents_1, parents_2, mutation_rate)
# 更新種群
population = np.vstack([parents_1, parents_2])
return best_solution, best_fitness, evolution_data
# 設置算法參數
population_size = 15000
num_generations = 40
mutation_rate = 0.08 # 變異率
crossover_rate = 0.2 # 交叉率
# 運行進化算法
best_solution, best_fitness, evolution_data = evolutionary_algorithm(population_size, num_generations, mutation_rate, crossover_rate)
# 輸出結果
print("最小值:", best_fitness)
print("最優(yōu)解:", best_solution)
# 輸出每個迭代步驟的最佳適應度值
print("每個迭代步驟的最佳適應度值:")
for step in evolution_data:
print(f"Generation {step['generation']}: {step['best_fitness']}")
# 可視化函數曲面和最優(yōu)解
x1_vals = np.linspace(-10, 10, 100)
x2_vals = np.linspace(-10, 10, 100)
X1, X2 = np.meshgrid(x1_vals, x2_vals)
Z = np.zeros_like(X1)
for i in range(Z.shape[0]):
for j in range(Z.shape[1]):
Z[i, j] = objective_function([X1[i, j], X2[i, j]])
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X1, X2, Z, alpha=0.5, cmap='viridis')
ax.scatter(best_solution[0], best_solution[1], best_fitness, color='red', marker='o', label='Best Solution')
ax.set_xlabel('X1')
ax.set_ylabel('X2')
ax.set_zlabel('f(x)')
ax.set_title('Objective Function and Best Solution')
ax.legend()
# 繪制適應度值的變化曲線
evolution_df = pd.DataFrame(evolution_data)
plt.figure()
plt.plot(evolution_df['generation'], evolution_df['best_fitness'], label='Best Fitness')
plt.xlabel('Generation')
plt.ylabel('Fitness')
plt.title('Evolution of Fitness')
plt.legend()
plt.show()
5 附錄
5.1 In[1] 輸出
最小值: 1.0000002473000187
最優(yōu)解: [0.78562713 0.7854951 ]
每個迭代步驟的最佳適應度值:
Generation 0: 1.0000153042180673
Generation 1: 1.0000153042180673
Generation 2: 1.0000153042180673
Generation 3: 1.0000136942409763
Generation 4: 1.0000136942409763
Generation 5: 1.0000136942409763
Generation 6: 1.0000136942409763
Generation 7: 1.0000100419077742
Generation 8: 1.000005565304546
Generation 9: 1.000002458099502
Generation 10: 1.0000022366988228
Generation 11: 1.0000007727585987
Generation 12: 1.0000007727585987
Generation 13: 1.0000007091648468
Generation 14: 1.0000007091648468
Generation 15: 1.0000004471760704
Generation 16: 1.0000004471760704
Generation 17: 1.0000004471760704
Generation 18: 1.0000004471760704
Generation 19: 1.0000002609708571
Generation 20: 1.0000002609708571
Generation 21: 1.0000002609708571
Generation 22: 1.0000002609708571
Generation 23: 1.0000002609708571
Generation 24: 1.0000002609708571
Generation 25: 1.0000002609708571
Generation 26: 1.0000002609708571
Generation 27: 1.0000002609708571
Generation 28: 1.0000002609708571
Generation 29: 1.0000002473000187
Generation 30: 1.0000002473000187
Generation 31: 1.0000002473000187
Generation 32: 1.0000002473000187
Generation 33: 1.0000002473000187
Generation 34: 1.0000002473000187
Generation 35: 1.0000002473000187
Generation 36: 1.0000002473000187
Generation 37: 1.0000002473000187
Generation 38: 1.0000002473000187
Generation 39: 1.0000002473000187
5.2 In[2] 輸出
最小值: -186.73042323192567
最優(yōu)解: [-7.70876845 -7.08354764]
每個迭代步驟的最佳適應度值:
Generation 0: -186.59098010602338
Generation 1: -186.59098010602338
Generation 2: -186.59098010602338
Generation 3: -186.59098010602338
Generation 4: -186.70224634663253
Generation 5: -186.70224634663253
Generation 6: -186.70224634663253
Generation 7: -186.70224634663253
Generation 8: -186.70224634663253
Generation 9: -186.70224634663253
Generation 10: -186.70224634663253
Generation 11: -186.71507272172664
Generation 12: -186.71507272172664
Generation 13: -186.7289048406221
Generation 14: -186.73006643615773
Generation 15: -186.73006643615773
Generation 16: -186.73006643615773
Generation 17: -186.73006643615773
Generation 18: -186.73009038074477
Generation 19: -186.73009038074477
Generation 20: -186.73009038074477
Generation 21: -186.73009038074477
Generation 22: -186.73009038074477
Generation 23: -186.73042323192567
Generation 24: -186.73042323192567
Generation 25: -186.73042323192567
Generation 26: -186.73042323192567
Generation 27: -186.73042323192567
Generation 28: -186.73042323192567
Generation 29: -186.73042323192567
Generation 30: -186.73042323192567
Generation 31: -186.73042323192567
Generation 32: -186.73042323192567
Generation 33: -186.73042323192567
Generation 34: -186.73042323192567
Generation 35: -186.73042323192567
Generation 36: -186.73042323192567
Generation 37: -186.73042323192567
Generation 38: -186.73042323192567
Generation 39: -186.73042323192567
文章來源:http://www.zghlxwxcb.cn/news/detail-807732.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-807732.html
到了這里,關于【Python】人工智能-機器學習——不調庫手撕演化算法解決函數最小值問題的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!