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 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
|
import numpy as np import time import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei'] plt.rcParams['axes.unicode_minus'] = False
def func_double_well(matrix_y): y = 0 l, k, h = 3.0, 0.5, 20.0 for i in matrix_y: y += h * pow((pow(i, 2) - pow(l, 2)), 2) / pow(l, 4) + k * i return y
def func_rastrigin(matrix_y): y = 10 * len(matrix_y) y += np.sum(matrix_y**2 - 10 * np.cos(2 * np.pi * matrix_y)) return y
def func_griewank(matrix_y): a, b, y = 0, 1, 0 index = 1 for i in matrix_y: a = a + i * i b = b * np.cos(i / np.sqrt(index)) index += 1 y = 1 + 1 / 4000 * a - b return y
def max_min_id(matrix, flag, func_to_use): if matrix.shape[1] == 0: return -1 walker_id = 0 temp = func_to_use(matrix[:, 0]) for j in range(matrix.shape[1] - 1): if temp < func_to_use(matrix[:, j + 1]) and flag == 0: walker_id = j + 1 temp = func_to_use(matrix[:, j + 1]) if temp > func_to_use(matrix[:, j + 1]) and flag == 1: walker_id = j + 1 temp = func_to_use(matrix[:, j + 1]) return walker_id
def mid_exchange(matrix, func_to_use): mid_walker = np.mean(matrix, axis=1) worst_id = max_min_id(matrix, 0, func_to_use) matrix[:, worst_id] = mid_walker return matrix
def qda_original_record(dim, walker_n, func_to_use, max_total_iter): acc = 1e-6 ite_times = 0 begin, end = -6, 6 scale = end - begin a = np.random.uniform(begin, end, (dim, walker_n)) b = np.zeros((dim, walker_n)) ite_flag = True convergence_data = []
while scale > acc and ite_times < max_total_iter: while ite_flag and ite_times < max_total_iter: ite_times += 1 for j in range(walker_n): for i in range(dim): b[i, j] = np.random.normal(a[i, j], scale) while not (begin <= b[i, j] <= end): b[i, j] = np.random.normal(a[i, j], scale) if func_to_use(b[:, j]) > func_to_use(a[:, j]): b[:, j] = a[:, j]
mid_exchange(b, func_to_use) a[:, :] = b[:, :] min_val = func_to_use(a[:, max_min_id(a, 1, func_to_use)]) convergence_data.append(min_val) ite_flag = False for i in range(dim): if np.var(a[i, :]) > pow(scale, 2): ite_flag = True scale /= 2 ite_flag = True return convergence_data
def qda_diff_accept_record(dim, walker_n, func_to_use, max_total_iter): acc = 1e-6 ite_times = 0 begin, end = -6, 6 scale = end - begin a = np.random.uniform(begin, end, (dim, walker_n)) b = np.zeros((dim, walker_n)) ite_flag = True convergence_data = []
while scale > acc and ite_times < max_total_iter: while ite_flag and ite_times < max_total_iter: ite_times += 1 for j in range(walker_n): old_fitness = func_to_use(a[:, j]) for i in range(dim): b[i, j] = np.random.normal(a[i, j], scale) while not (begin <= b[i, j] <= end): b[i, j] = np.random.normal(a[i, j], scale) new_fitness = func_to_use(b[:, j]) if new_fitness > old_fitness: acceptance_prob = 1.0 / (ite_times) if np.random.rand() >= acceptance_prob: b[:, j] = a[:, j] mid_exchange(b, func_to_use) a[:, :] = b[:, :] min_val = func_to_use(a[:, max_min_id(a, 1, func_to_use)]) convergence_data.append(min_val)
ite_flag = False for i in range(dim): if np.var(a[i, :]) > pow(scale, 2): ite_flag = True scale /= 2 ite_flag = True return convergence_data
def plot_multi_dim(dim_list, walker_n, func_to_use, func_name, num_runs, max_total_iter): print(f"--- QDA 算法对比测试 ---") print(f"目标函数: {func_name}") print(f"种群数: {walker_n}") print(f"每组运行次数: {num_runs}") print(f"最大迭代次数: {max_total_iter}") for dim in dim_list: print(f"--- 维度: {dim}D ---") print("-" * 25)
n = len(dim_list) rows = (n + 1) // 2 plt.figure(figsize=(15, 6 * rows)) for i, dim in enumerate(dim_list): start_time = time.time() standard_runs = [qda_original_record(dim, walker_n, func_to_use, max_total_iter) for _ in range(num_runs)] optimized_runs = [qda_diff_accept_record(dim, walker_n, func_to_use, max_total_iter) for _ in range(num_runs)] end_time = time.time() print(f"维度 {dim}D 测试完成,耗时: {end_time - start_time:.2f} 秒") max_len = max_total_iter standard_padded = np.array([run + [run[-1]] * (max_len - len(run)) for run in standard_runs]) optimized_padded = np.array([run + [run[-1]] * (max_len - len(run)) for run in optimized_runs])
if len(standard_padded) == 0 or len(optimized_padded) == 0: print(f"警告:维度 {dim}D 的收敛数据点过少,无法绘制有意义的曲线。") continue avg_orig = np.mean(standard_padded, axis=0) avg_diff = np.mean(optimized_padded, axis=0)
x_axis = np.arange(len(avg_orig))
ax = plt.subplot(rows, 2, i + 1) ax.plot(x_axis, avg_orig, label="标准版", color='blue', linewidth=2) ax.plot(x_axis, avg_diff, '--', label="优化版", color='red', linewidth=2) ax.set_title(f"维度: {dim}D", fontsize=14) ax.set_xlabel("迭代次数", fontsize=12) ax.set_ylabel("平均最优函数值", fontsize=12) all_values = np.concatenate((avg_orig, avg_diff)) if np.all(all_values > 0): ax.set_yscale('log') ax.grid(True, linestyle=':', alpha=0.6) ax.legend(loc='upper right', fontsize=10) plt.suptitle(f"QDA 算法收敛曲线对比 ({func_name})", fontsize=20) plt.tight_layout(rect=[0, 0, 1, 0.96]) plt.show()
if __name__ == "__main__": test_dimensions = [2, 5, 10, 20, 30] test_walker_n = 50 test_func = func_rastrigin test_func_name = "rastrigin" num_runs = 10 max_total_iter = 100000
plot_multi_dim(test_dimensions, test_walker_n, test_func, test_func_name, num_runs, max_total_iter)
|