MATLAB 实现,结合神经网络和遗传算法来寻找非线性函数的极值。这种方法特别适合处理高维、非线性、多峰的复杂函数优化问题。
算法原理
神经网络(NN)作为代理模型 → 遗传算法(GA)进行全局优化 → 得到最优解
流程概述:
- 神经网络:学习非线性函数的映射关系
- 遗传算法:在神经网络模型上进行全局寻优
- 混合策略:NN 的预测能力 + GA 的全局搜索能力
完整 MATLAB 实现
主程序:神经网络遗传算法函数优化
matlab
%% 神经网络遗传算法函数极值寻优
% 目标:寻找非线性函数 f(x) 的最小值/最大值
% 方法:神经网络代理模型 + 遗传算法优化
% 适用于:高维、非线性、多峰函数
clear; clc; close all;
warning off;
%% 参数设置
n = 2; % 变量维度(可修改)
population_size = 50; % 遗传算法种群大小
max_generations = 100; % 最大迭代次数
train_size = 1000; % 神经网络训练样本数
lb = -10 * ones(1, n); % 变量下界
ub = 10 * ones(1, n); % 变量上界
%% 定义测试函数(可选择不同的非线性函数)
fprintf('===== 神经网络遗传算法函数极值寻优 =====\n');
fprintf('变量维度: %d, 搜索空间: [%.1f, %.1f]^%d\n', n, lb(1), ub(1), n);
% 选择测试函数
fprintf('请选择测试函数:\n');
fprintf('1. Rastrigin 函数 (多峰)\n');
fprintf('2. Ackley 函数 (多峰)\n');
fprintf('3. Rosenbrock 函数 (山谷)\n');
fprintf('4. Schwefel 函数 (多峰)\n');
fprintf('5. Griewank 函数 (多峰)\n');
fprintf('6. 自定义函数\n');
choice = input('请输入选择 (1-6): ');
% 定义测试函数
if choice == 1
% Rastrigin 函数(全局最小值在原点)
test_func = @(x) 10*size(x,2) + sum(x.^2 - 10*cos(2*pi*x), 2);
func_name = 'Rastrigin 函数';
global_opt = zeros(1, n);
f_opt = 0;
elseif choice == 2
% Ackley 函数
test_func = @(x) -20*exp(-0.2*sqrt(mean(x.^2, 2))) - ...
exp(mean(cos(2*pi*x), 2)) + 20 + exp(1);
func_name = 'Ackley 函数';
global_opt = zeros(1, n);
f_opt = 0;
elseif choice == 3
% Rosenbrock 函数
test_func = @(x) sum(100*(x(:,2:end) - x(:,1:end-1).^2).^2 + ...
(1 - x(:,1:end-1)).^2, 2);
func_name = 'Rosenbrock 函数';
global_opt = ones(1, n);
f_opt = 0;
elseif choice == 4
% Schwefel 函数
test_func = @(x) 418.9829*size(x,2) - sum(x .* sin(sqrt(abs(x))), 2);
func_name = 'Schwefel 函数';
global_opt = 420.9687 * ones(1, n);
f_opt = 0;
elseif choice == 5
% Griewank 函数
test_func = @(x) 1 + sum(x.^2, 2)/4000 - ...
prod(cos(x ./ sqrt(1:size(x,2))), 2);
func_name = 'Griewank 函数';
global_opt = zeros(1, n);
f_opt = 0;
else
% 自定义函数
fprintf('\n请输入自定义函数(MATLAB表达式)\n');
fprintf('例如: x(:,1).^2 + x(:,2).^2 - 10*cos(2*pi*x(:,1)).*cos(2*pi*x(:,2))\n');
func_str = input('函数表达式: ', 's');
test_func = str2func(['@(x) ' func_str]);
func_name = '自定义函数';
global_opt = NaN;
f_opt = NaN;
end
fprintf('\n正在优化: %s\n', func_name);
%% 第一阶段:生成训练数据并训练神经网络
fprintf('\n=== 第一阶段:训练神经网络代理模型 ===\n');
% 生成训练数据
X_train = zeros(train_size, n);
for i = 1:n
X_train(:, i) = lb(i) + (ub(i) - lb(i)) * rand(train_size, 1);
end
y_train = test_func(X_train);
% 数据标准化
X_mean = mean(X_train);
X_std = std(X_train);
y_mean = mean(y_train);
y_std = std(y_train);
X_train_norm = (X_train - X_mean) ./ X_std;
y_train_norm = (y_train - y_mean) ./ y_std;
% 神经网络结构
hidden_layers = [20, 10]; % 两个隐藏层,神经元数分别为20和10
net = feedforwardnet(hidden_layers);
% 设置训练参数
net.trainFcn = 'trainlm'; % Levenberg-Marquardt
net.trainParam.epochs = 200;
net.trainParam.goal = 1e-6;
net.trainParam.show = 10;
net.trainParam.showWindow = false; % 不显示GUI
net.divideParam.trainRatio = 0.8;
net.divideParam.valRatio = 0.1;
net.divideParam.testRatio = 0.1;
% 训练神经网络
fprintf('正在训练神经网络...\n');
[net, tr] = train(net, X_train_norm', y_train_norm');
% 测试神经网络性能
y_pred_norm = net(X_train_norm');
y_pred = y_pred_norm * y_std + y_mean;
% 计算训练误差
mse = mean((y_pred' - y_train).^2);
rmse = sqrt(mse);
r2 = 1 - sum((y_train - y_pred').^2) / sum((y_train - mean(y_train)).^2);
fprintf('神经网络训练完成!\n');
fprintf('训练集大小: %d\n', train_size);
fprintf('MSE: %.6f, RMSE: %.6f, R²: %.6f\n', mse, rmse, r2);
% 神经网络预测函数
nn_predict = @(x) predict_with_nn(net, x, X_mean, X_std, y_mean, y_std);
%% 第二阶段:遗传算法优化
fprintf('\n=== 第二阶段:遗传算法在神经网络上优化 ===\n');
% 遗传算法参数
ga_options = optimoptions('ga');
ga_options.PopulationSize = population_size;
ga_options.MaxGenerations = max_generations;
ga_options.FunctionTolerance = 1e-8;
ga_options.Display = 'iter';
ga_options.PlotFcn = {@gaplotbestf, @gaplotbestindiv};
ga_options.UseVectorized = false;
% 适应度函数(使用神经网络预测)
fitness_func = @(x) nn_fitness(x, nn_predict, n);
% 运行遗传算法
fprintf('开始遗传算法优化...\n');
[x_ga_nn, fval_ga_nn, exitflag, output] = ga(fitness_func, n, ...
[], [], [], [], lb, ub, [], [], ga_options);
% 在真实函数上评估结果
fval_true = test_func(x_ga_nn);
fprintf('\n=== 优化结果(神经网络+遗传算法)===\n');
fprintf('最优解: [');
fprintf('%.6f ', x_ga_nn);
fprintf(']\n');
fprintf('神经网络预测值: %.10f\n', fval_ga_nn);
fprintf('真实函数值: %.10f\n', fval_true);
if ~isnan(f_opt)
fprintf('理论最优值: %.10f\n', f_opt);
fprintf('误差: %.6f\n', abs(fval_true - f_opt));
end
%% 第三阶段:与纯遗传算法对比
fprintf('\n=== 第三阶段:纯遗传算法对比 ===\n');
% 使用真实函数作为适应度
fitness_true = @(x) test_func(x);
% 运行遗传算法(真实函数)
[x_ga_true, fval_ga_true] = ga(fitness_true, n, ...
[], [], [], [], lb, ub, [], [], ga_options);
fprintf('纯遗传算法结果:\n');
fprintf('最优解: [');
fprintf('%.6f ', x_ga_true);
fprintf(']\n');
fprintf('函数值: %.10f\n', fval_ga_true);
if ~isnan(f_opt)
fprintf('误差: %.6f\n', abs(fval_ga_true - f_opt));
end
%% 第四阶段:可视化结果
fprintf('\n=== 第四阶段:结果可视化 ===\n');
% 如果是2维问题,绘制等高线图
if n == 2
% 创建网格
[X1, X2] = meshgrid(linspace(lb(1), ub(1), 100), ...
linspace(lb(2), ub(2), 100));
% 计算真实函数值
Z_true = zeros(size(X1));
for i = 1:size(X1, 1)
for j = 1:size(X1, 2)
Z_true(i, j) = test_func([X1(i, j), X2(i, j)]);
end
end
% 计算神经网络预测值
Z_nn = zeros(size(X1));
for i = 1:size(X1, 1)
for j = 1:size(X1, 2)
Z_nn(i, j) = nn_predict([X1(i, j), X2(i, j)]);
end
end
% 创建图形
figure('Position', [100, 100, 1200, 500]);
% 子图1:真实函数
subplot(1, 3, 1);
contourf(X1, X2, Z_true, 50, 'LineStyle', 'none');
hold on;
colormap(jet);
colorbar;
plot(x_ga_true(1), x_ga_true(2), 'rp', 'MarkerSize', 15, ...
'MarkerFaceColor', 'r', 'DisplayName', 'GA最优解');
plot(global_opt(1), global_opt(2), 'g*', 'MarkerSize', 15, ...
'LineWidth', 2, 'DisplayName', '理论最优');
xlabel('x_1'); ylabel('x_2');
title(sprintf('真实函数: %s', func_name));
legend('Location', 'best');
grid on;
% 子图2:神经网络近似
subplot(1, 3, 2);
contourf(X1, X2, Z_nn, 50, 'LineStyle', 'none');
hold on;
colormap(jet);
colorbar;
plot(x_ga_nn(1), x_ga_nn(2), 'rp', 'MarkerSize', 15, ...
'MarkerFaceColor', 'r', 'DisplayName', 'NN-GA最优解');
plot(global_opt(1), global_opt(2), 'g*', 'MarkerSize', 15, ...
'LineWidth', 2, 'DisplayName', '理论最优');
xlabel('x_1'); ylabel('x_2');
title('神经网络近似');
legend('Location', 'best');
grid on;
% 子图3:误差图
subplot(1, 3, 3);
error_map = abs(Z_nn - Z_true);
contourf(X1, X2, error_map, 50, 'LineStyle', 'none');
colormap(jet);
colorbar;
xlabel('x_1'); ylabel('x_2');
title('神经网络近似误差');
grid on;
sgtitle('神经网络遗传算法函数极值寻优');
end
% 绘制收敛曲线
figure('Position', [100, 100, 800, 600]);
% 训练集预测 vs 真实值
subplot(2, 2, 1);
plot(y_train, y_pred, 'b.', 'MarkerSize', 10);
hold on;
plot([min(y_train), max(y_train)], [min(y_train), max(y_train)], 'r-', 'LineWidth', 2);
xlabel('真实值');
ylabel('神经网络预测值');
title(sprintf('神经网络拟合效果 (R²=%.4f)', r2));
grid on;
axis equal;
% 残差图
subplot(2, 2, 2);
residuals = y_pred' - y_train;
histogram(residuals, 30, 'FaceColor', 'b', 'EdgeColor', 'k');
xlabel('残差');
ylabel('频数');
title('神经网络预测残差分布');
grid on;
% 训练过程
subplot(2, 2, 3);
plot(tr.epoch, tr.perf, 'b-', 'LineWidth', 2);
hold on;
plot(tr.epoch, tr.vperf, 'r-', 'LineWidth', 2);
plot(tr.epoch, tr.tperf, 'g-', 'LineWidth', 2);
xlabel('训练轮数');
ylabel('均方误差');
title('神经网络训练过程');
legend({'训练集', '验证集', '测试集'}, 'Location', 'best');
grid on;
% 结果比较
subplot(2, 2, 4);
methods = {'NN+GA', '纯GA'};
if ~isnan(f_opt)
values = [fval_true, fval_ga_true];
errors = [abs(fval_true - f_opt), abs(fval_ga_true - f_opt)];
yyaxis left;
bar(values);
ylabel('函数值');
set(gca, 'XTickLabel', methods);
title('优化结果比较');
grid on;
yyaxis right;
plot(errors, 'ro-', 'LineWidth', 2, 'MarkerSize', 10, 'MarkerFaceColor', 'r');
ylabel('与理论最优的误差');
else
values = [fval_true, fval_ga_true];
bar(values);
ylabel('函数值');
set(gca, 'XTickLabel', methods);
title('优化结果比较');
grid on;
end
%% 第五阶段:敏感性分析
fprintf('\n=== 第五阶段:参数敏感性分析 ===\n');
% 神经网络结构敏感性
fprintf('\n神经网络结构敏感性:\n');
hidden_sizes = {[5], [10], [20], [10, 5], [20, 10]};
for i = 1:length(hidden_sizes)
net_test = feedforwardnet(hidden_sizes{i});
net_test.trainParam.showWindow = false;
net_test.divideParam.trainRatio = 0.8;
net_test.divideParam.valRatio = 0.1;
net_test.divideParam.testRatio = 0.1;
[net_test, tr_test] = train(net_test, X_train_norm', y_train_norm');
y_pred_test_norm = net_test(X_train_norm');
y_pred_test = y_pred_test_norm * y_std + y_mean;
mse_test = mean((y_pred_test' - y_train).^2);
fprintf('隐藏层结构: [%s], MSE: %.6f\n', ...
num2str(hidden_sizes{i}), mse_test);
end
fprintf('\n优化完成!\n');
%% 辅助函数
function y_pred = predict_with_nn(net, x, X_mean, X_std, y_mean, y_std)
% 使用训练好的神经网络进行预测
if size(x, 2) ~= length(X_mean)
x = x';
end
x_norm = (x - X_mean) ./ X_std;
y_pred_norm = net(x_norm')';
y_pred = y_pred_norm * y_std + y_mean;
end
function f = nn_fitness(x, nn_predict, n)
% 遗传算法的适应度函数
if size(x, 1) > 1
% 向量化计算
f = zeros(size(x, 1), 1);
for i = 1:size(x, 1)
f(i) = nn_predict(x(i, :));
end
else
% 单个个体
f = nn_predict(x);
end
end
扩展:增强版神经网络遗传算法
matlab
%% 增强版 NN-GA 优化器(支持并行计算和自适应策略)
classdef EnhancedNNOptimizer
% 增强版神经网络遗传算法优化器
properties
net % 神经网络模型
X_mean % 输入均值
X_std % 输入标准差
y_mean % 输出均值
y_std % 输出标准差
func % 真实函数
bounds % 变量边界
n_vars % 变量维度
end
methods
function obj = EnhancedNNOptimizer(func, bounds)
% 构造函数
obj.func = func;
obj.bounds = bounds;
obj.n_vars = size(bounds, 1);
end
function train_surrogate(obj, n_samples, hidden_sizes)
% 训练神经网络代理模型
fprintf('训练神经网络代理模型...\n');
% 生成训练样本
X = zeros(n_samples, obj.n_vars);
for i = 1:obj.n_vars
X(:, i) = obj.bounds(i, 1) + ...
(obj.bounds(i, 2) - obj.bounds(i, 1)) * rand(n_samples, 1);
end
y = obj.func(X);
% 数据标准化
obj.X_mean = mean(X);
obj.X_std = std(X);
obj.y_mean = mean(y);
obj.y_std = std(y);
X_norm = (X - obj.X_mean) ./ obj.X_std;
y_norm = (y - obj.y_mean) ./ obj.y_std;
% 创建和训练神经网络
obj.net = feedforwardnet(hidden_sizes);
obj.net.trainFcn = 'trainlm';
obj.net.trainParam.showWindow = false;
obj.net.trainParam.epochs = 300;
obj.net.trainParam.goal = 1e-8;
[obj.net, ~] = train(obj.net, X_norm', y_norm');
% 评估模型
y_pred = obj.predict(X);
mse = mean((y_pred - y).^2);
fprintf('代理模型训练完成,MSE: %.6e\n', mse);
end
function y_pred = predict(obj, x)
% 使用代理模型预测
if size(x, 2) ~= obj.n_vars
x = x';
end
x_norm = (x - obj.X_mean) ./ obj.X_std;
y_norm = obj.net(x_norm')';
y_pred = y_norm * obj.y_std + obj.y_mean;
end
function [x_opt, f_opt, history] = optimize_ga(obj, pop_size, max_gen)
% 遗传算法优化
fprintf('开始遗传算法优化...\n');
% 适应度函数
fitness_func = @(x) obj.predict(x);
% 遗传算法选项
options = optimoptions('ga');
options.PopulationSize = pop_size;
options.MaxGenerations = max_gen;
options.Display = 'iter';
options.FunctionTolerance = 1e-10;
options.UseParallel = true; % 启用并行计算
% 约束
A = [];
b = [];
Aeq = [];
beq = [];
nonlcon = [];
% 变量边界
lb = obj.bounds(:, 1)';
ub = obj.bounds(:, 2)';
% 运行遗传算法
[x_opt, f_opt, exitflag, output, population, scores] = ...
ga(fitness_func, obj.n_vars, A, b, Aeq, beq, lb, ub, nonlcon, options);
% 记录优化历史
history.best_fval = output.bestfval;
history.mean_fval = output.meanfval;
history.population = population;
history.scores = scores;
% 在真实函数上验证
f_true = obj.func(x_opt);
fprintf('优化完成!\n');
fprintf('代理模型预测: %.10f\n', f_opt);
fprintf('真实函数值: %.10f\n', f_true);
end
function [x_opt, f_opt] = hybrid_optimization(obj, n_samples, pop_size, max_gen)
% 混合优化:代理模型 + 局部优化
fprintf('开始混合优化...\n');
% 步骤1:训练代理模型
obj.train_surrogate(n_samples, [20, 10]);
% 步骤2:遗传算法在代理模型上全局搜索
[x_ga, ~, history] = obj.optimize_ga(pop_size, max_gen);
% 步骤3:在最优解附近进行局部搜索
fprintf('执行局部优化...\n');
options = optimoptions('fmincon');
options.Display = 'iter';
options.Algorithm = 'sqp';
[x_opt, f_opt] = fmincon(obj.func, x_ga, ...
[], [], [], [], ...
obj.bounds(:, 1)', obj.bounds(:, 2)', [], options);
fprintf('混合优化完成!\n');
fprintf('最优解: [');
fprintf('%.6f ', x_opt);
fprintf(']\n');
fprintf('最优值: %.10f\n', f_opt);
end
function plot_results(obj, x_opt)
% 可视化结果
if obj.n_vars == 1
% 1D 情况
x = linspace(obj.bounds(1), obj.bounds(2), 1000)';
y_true = obj.func(x);
y_pred = obj.predict(x);
figure;
plot(x, y_true, 'b-', 'LineWidth', 2, 'DisplayName', '真实函数');
hold on;
plot(x, y_pred, 'r--', 'LineWidth', 2, 'DisplayName', '神经网络预测');
plot(x_opt, obj.func(x_opt), 'ro', 'MarkerSize', 10, ...
'MarkerFaceColor', 'r', 'DisplayName', '最优解');
xlabel('x'); ylabel('f(x)');
title('神经网络遗传算法优化结果');
legend('Location', 'best');
grid on;
elseif obj.n_vars == 2
% 2D 情况
[X1, X2] = meshgrid(linspace(obj.bounds(1,1), obj.bounds(1,2), 100), ...
linspace(obj.bounds(2,1), obj.bounds(2,2), 100));
Z_true = zeros(size(X1));
Z_pred = zeros(size(X1));
for i = 1:size(X1, 1)
for j = 1:size(X1, 2)
x = [X1(i,j), X2(i,j)];
Z_true(i,j) = obj.func(x);
Z_pred(i,j) = obj.predict(x);
end
end
figure('Position', [100, 100, 1200, 400]);
subplot(1, 3, 1);
contourf(X1, X2, Z_true, 50, 'LineStyle', 'none');
colorbar;
hold on;
plot(x_opt(1), x_opt(2), 'rp', 'MarkerSize', 15, 'MarkerFaceColor', 'r');
xlabel('x_1'); ylabel('x_2');
title('真实函数');
grid on;
subplot(1, 3, 2);
contourf(X1, X2, Z_pred, 50, 'LineStyle', 'none');
colorbar;
hold on;
plot(x_opt(1), x_opt(2), 'rp', 'MarkerSize', 15, 'MarkerFaceColor', 'r');
xlabel('x_1'); ylabel('x_2');
title('神经网络预测');
grid on;
subplot(1, 3, 3);
error = abs(Z_pred - Z_true);
contourf(X1, X2, error, 50, 'LineStyle', 'none');
colorbar;
xlabel('x_1'); ylabel('x_2');
title('预测误差');
grid on;
sgtitle('神经网络遗传算法优化结果');
end
end
end
end
参考代码 神经网络遗传算法函数极值寻优-非线性函数极值 www.youwenfan.com/contentcst/122200.html
使用示例
matlab
%% 示例1:Rastrigin 函数优化
% 这是一个典型的多峰测试函数
% 定义函数
rastrigin = @(x) 10*size(x,2) + sum(x.^2 - 10*cos(2*pi*x), 2);
% 设置边界
bounds = [-5.12, 5.12; -5.12, 5.12]; % 2D Rastrigin
% 创建优化器
optimizer = EnhancedNNOptimizer(rastrigin, bounds);
% 执行混合优化
[x_opt, f_opt] = optimizer.hybrid_optimization(...
1000, % 训练样本数
50, % 遗传算法种群大小
100 % 最大迭代次数
);
% 可视化
optimizer.plot_results(x_opt);
%% 示例2:高维优化(10维)
fprintf('\n=== 10维Rastrigin函数优化 ===\n');
% 10维Rastrigin函数
n_dim = 10;
rastrigin_nd = @(x) 10*n_dim + sum(x.^2 - 10*cos(2*pi*x), 2);
bounds_nd = repmat([-5.12, 5.12], n_dim, 1);
optimizer_nd = EnhancedNNOptimizer(rastrigin_nd, bounds_nd);
% 训练代理模型
optimizer_nd.train_surrogate(5000, [30, 20, 10]);
% 优化
[x_opt_nd, f_opt_nd] = optimizer_nd.optimize_ga(100, 200);
fprintf('最优值: %.6f\n', f_opt_nd);
fprintf('理论最优: 0.000000\n');
fprintf('误差: %.6f\n', abs(f_opt_nd));
%% 示例3:复杂非线性函数
fprintf('\n=== 复杂非线性函数优化 ===\n');
% 定义复杂函数
complex_func = @(x) x(:,1).*sin(sqrt(abs(x(:,1)))) + ...
x(:,2).*cos(sqrt(abs(x(:,2)))) + ...
0.1*(x(:,1).^2 + x(:,2).^2) - ...
5*sin(0.5*x(:,1).*x(:,2));
bounds_complex = [-10, 10; -10, 10];
optimizer_complex = EnhancedNNOptimizer(complex_func, bounds_complex);
[x_opt_complex, f_opt_complex] = optimizer_complex.hybrid_optimization(2000, 100, 150);
% 绘制3D图形
figure;
[X, Y] = meshgrid(linspace(-10, 10, 100), linspace(-10, 10, 100));
Z = complex_func([X(:), Y(:)]);
Z = reshape(Z, size(X));
surf(X, Y, Z, 'EdgeColor', 'none', 'FaceAlpha', 0.8);
hold on;
plot3(x_opt_complex(1), x_opt_complex(2), f_opt_complex, ...
'rp', 'MarkerSize', 20, 'MarkerFaceColor', 'r');
xlabel('x_1'); ylabel('x_2'); zlabel('f(x)');
title('复杂非线性函数优化结果');
colorbar;
view(45, 30);
grid on;
性能评估
matlab
%% 性能评估脚本
function performance_evaluation()
% 测试不同优化方法的性能
% 测试函数列表
test_functions = {
{@(x) sum(x.^2, 2), 'Sphere', repmat([-5, 5], 5, 1), zeros(5,1), 0}, % 5维
{@(x) 10*size(x,2) + sum(x.^2 - 10*cos(2*pi*x), 2), 'Rastrigin', ...
repmat([-5.12, 5.12], 2, 1), zeros(2,1), 0}, % 2维
{@(x) -20*exp(-0.2*sqrt(mean(x.^2, 2))) - ...
exp(mean(cos(2*pi*x), 2)) + 20 + exp(1), 'Ackley', ...
repmat([-5, 5], 3, 1), zeros(3,1), 0} % 3维
};
methods = {'NN-GA', '纯GA', 'PSO', 'SA'};
results = cell(length(test_functions), length(methods));
for func_idx = 1:length(test_functions)
func = test_functions{func_idx};
fprintf('\n测试函数: %s (维度: %d)\n', func{2}, size(func{3}, 1));
% 创建优化器
optimizer = EnhancedNNOptimizer(func{1}, func{3});
% NN-GA
tic;
[x_opt, f_opt] = optimizer.hybrid_optimization(1000, 50, 100);
time_nnga = toc;
error_nnga = abs(f_opt - func{5});
results{func_idx, 1} = struct('value', f_opt, 'time', time_nnga, 'error', error_nnga);
% 其他方法类似实现...
fprintf('NN-GA: 最优值=%.6f, 误差=%.6f, 时间=%.2fs\n', ...
f_opt, error_nnga, time_nnga);
end
% 绘制比较图
figure;
subplot(1, 2, 1);
bar_data = zeros(length(test_functions), 4);
for i = 1:length(test_functions)
for j = 1:4
if ~isempty(results{i, j})
bar_data(i, j) = results{i, j}.error;
end
end
end
bar(bar_data);
set(gca, 'XTickLabel', {test_functions{:,2}});
ylabel('误差');
title('不同优化方法的误差比较');
legend(methods, 'Location', 'best');
grid on;
subplot(1, 2, 2);
time_data = zeros(length(test_functions), 4);
for i = 1:length(test_functions)
for j = 1:4
if ~isempty(results{i, j})
time_data(i, j) = results{i, j}.time;
end
end
end
bar(time_data);
set(gca, 'XTickLabel', {test_functions{:,2}});
ylabel('计算时间 (s)');
title('不同优化方法的时间比较');
legend(methods, 'Location', 'best');
grid on;
end
结果解释
算法优势:
- 处理高维问题:神经网络可以学习高维非线性映射
- 避免局部最优:遗传算法提供全局搜索能力
- 计算效率:神经网络预测比函数计算更快
- 适用于黑箱函数:不需要知道函数的具体形式
适用场景:
- 工程设计优化
- 金融建模
- 机器学习超参数优化
- 控制系统设计
- 信号处理参数优化
参数调整建议:
- 神经网络结构:隐藏层神经元越多,拟合能力越强,但可能过拟合
- 训练样本数:样本越多,代理模型越准确
- 遗传算法参数 :
- 种群大小:30-100
- 迭代次数:50-200
- 交叉概率:0.7-0.9
- 变异概率:0.01-0.1
扩展方向:
- 使用深度学习代替浅层神经网络
- 结合贝叶斯优化改进采样
- 实现并行计算加速
- 加入自适应机制调整参数
- 支持约束优化问题