cost function을 그래프로 어떻게 그려야 할지 모르겠습니다.

5 次查看(过去 30 天)
병현 문
병현 문 2022-5-25
回答: Pavan Sahith 2023-10-17
3개의 data (1,1), (2,3), (2,2)를 이용해 직선 y=ax+b의 parameter estimation을 하는 문제입니다.
이의 cost fuction을 3차원에 plot을 해야하는데요
a, b의 구간은 둘 다 [0,5]라고 합니다.
estimate한 직선을 y=1.5x-0.5라고 구했는데
여기서 cost function을 구하라는게 무슨말인지 모르겠습니다.

回答(1 个)

Pavan Sahith
Pavan Sahith 2023-10-17
Hello,
I understand you want to estimate the parameters of a linear equation y= ax + b using three data points (1,1), (2,3), and (2,2). You want to plot the cost function in 3d space.
Commonly used cost functions for linear regression problems include mean squared error (MSE).
Please refer to this example code to plot an example cost function for some sample data:
% Data points
data = [1, 1; 2, 3; 2, 2];
% Function to compute the cost (MSE)
cost_function = @(a, b) mean((data(:, 2) - (a * data(:, 1) + b)).^2);
% Grid of 'a' and ‘b’ values
a_values = linspace(0, 5, 100);
b_values = linspace(0, 5, 100);
% Create a meshgrid for 3D plotting
[a_grid, b_grid] = meshgrid(a_values, b_values);
cost_grid = zeros(size(a_grid));
for i = 1:numel(a_grid)
cost_grid(i) = cost_function(a_grid(i), b_grid(i));
end
figure;
surf(a_grid, b_grid, cost_grid);
xlabel('a');
ylabel('b');
zlabel('Cost');
title('Cost Function Plot');
% you can also find best a and best b
[min_cost, min_index] = min(cost_grid(:));
best_a = a_grid(min_index);
best_b = b_grid(min_index);
Please refer to the MathWorks documentation links to know more about

类别

Help CenterFile Exchange 中查找有关 기술 통계량 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!