分析以下代码并给出注释function plotDecisionBoundary(theta, X, y) % Plot Data plotData(X(:,2:3), y);%绘制样本点 hold on if size(X, 2) <= 3%输入数据为2维 % Only need 2 points to define a line, so choose two endpoints plot_x = [min(X(:,2))-2, max(X(:,2))+2]; % Calculate the decision boundary line plot_y = (-1./theta(3)).*(theta(2).*plot_x + theta(1)); % Plot, and adjust axes for better viewing plot(plot_x, plot_y) % Legend, specific for the exercise legend('Admitted', 'Not admitted', 'Decision Boundary') axis([30, 100, 30, 100]) else % Here is the grid range u = linspace(-1, 1.5, 50); v = linspace(-1, 1.5, 50); z = zeros(length(u), length(v)); % Evaluate z = theta*x over the grid for i = 1:length(u) for j = 1:length(v) z(i,j) = mapFeature(u(i), v(j))*theta; end end z = z'; % important to transpose z before calling contour % Plot z = 0 % Notice you need to specify the range [0, 0] contour(u, v, z, [0, 0], 'LineWidth', 2) end hold off end
时间: 2023-07-15 15:10:20 浏览: 92
这段代码实现了绘制决策边界的功能。体注释如下:
`
function plotDecisionBoundary, X, y)
% 绘制决策界,传入参数为theta、样本特征X、标签y
% 绘制本点
plotData(:,2:3), y);
hold on
if size(X, 2) <= 3 % 如果输入数据为2维
% 只需要2个点就能定义一条直线
plot_x = [min(X(:,2))-2, max(X(:,2))+2];
% 计算决策边界直线
plot_y = (-1./theta(3)).*(theta(2).*plot_x + theta(1));
% 绘制直线,并调整坐标轴以便更好的观察
plot(plot_x, plot_y)
% 指定图例,用于本练习
legend('Admitted', 'Not admitted', 'Decision Boundary')
axis([30, 100, 30, 100])
else % 如果输入数据为3维及以上
% 定义网格范围
u = linspace(-1, 1.5, 50);
v = linspace(-1, 1.5, 50);
z = zeros(length(u), length(v));
% 在网格上计算z = theta*x的值
for i = 1:length(u)
for j = 1:length(v)
z(i,j) = mapFeature(u(i), v(j))*theta;
end
end
z = z'; % 在调用contour之前需要对z进行转置
% 绘制z = 0的等高线
% 注意需要指定范围[0, 0]
contour(u, v, z, [0, 0], 'LineWidth', 2)
end
hold off
end
```
阅读全文