爬山算法
使用爬山算法优化简单的数学函数 假设我们需要找到函数 𝑓(𝑥)=−𝑥^2+4𝑥的最大值。这是一个具有单个局部最大值的简单抛物线函数。步骤 1: 定义目标函数 首先,定义我们需要优化的函数。在MATLAB中,我们可以创建一个函数来计算给定x值的 𝑓(𝑥)。function y = myFunction(x)
y = -x^2 + 4*x;
end步骤 2: 实现爬山算法 接着,实现爬山算法。我们从一个随机点开始,然后在每一步尝试移动到一个“邻居”点,如果那里的值更高,就移动到那里。function = hillClimbing(func, initialX, stepSize, numIterations)
currentX = initialX;
currentY = func(currentX);
for i = 1:numIterations
% 尝试在两个方向上移动
newX = ;
newY = ;
% 找出最好的移动方向
= max(newY);
% 如果找到了更好的解,则更新当前解
if maxY > currentY
currentX = newX(idx);
currentY = maxY;
else
% 如果没有更好的解,结束搜索
break;
end
end
bestX = currentX;
bestY = currentY;
end
% 运行爬山算法
initialX = 0; % 初始点
stepSize = 0.1; % 步长
numIterations = 100; % 迭代次数
= hillClimbing(@myFunction, initialX, stepSize, numIterations);步骤 3: 输出结果 展示算法找到的最优解。disp(['The maximum value of f(x) is found at x = ', num2str(bestX)]);
disp(['The maximum value of f(x) is ', num2str(bestY)]);步骤 4: 可视化 可视化函数和算法找到的最大值点,以更好地理解算法的行为。x = 0:0.01:5;
y = myFunction(x);
figure;
plot(x, y, 'b-', bestX, bestY, 'ro');
title('Function Optimization using Hill Climbing');
xlabel('x');
ylabel('f(x)');
legend('Function', 'Maximum Point');
页:
[1]