作业二:ex2答案解析
一、逻辑回归
第一部分:
ex2.m文件代码解读:
clear ;
close all;
clc;
data = load('ex2data1.txt'); %读取数据
X = data(:, [1, 2]); y = data(:, 3); %data是一个矩阵,X为第一到第二列所有的行的值组成一个矩阵
plotData(X, y); %调用函数(筛选的数据、画图的规则)
hold on;
%两个轴的名称
xlabel('Exam 1 score');
ylabel('Exam 2 score');
%标记符号所对应的名称,按先后顺序,即:加号是Admitted,圆圈是Not admitted,标记在图的右上角
legend('Admitted', 'Not admitted')
hold off;
fprintf('\nProgram paused. Press enter to continue.\n');%按压任意键继续
pause; %程序暂停
[m, n] = size(X); %m行n列
X = [ones(m, 1) X]; %m行一列的元素全为1向量
initial_theta = zeros(n + 1, 1);%初始化theta,都为0
%计算并显示初始成本和梯度
[cost, grad] = costFunction(initial_theta, X, y); %调用函数
fprintf('Cost at initial theta (zeros): %f\n', cost); %打印代价
fprintf('Expected cost (approx): 0.693\n');
fprintf('Gradient at initial theta (zeros): \n');
fprintf(' %f \n', grad); %打印梯度
fprintf('Expected gradients (approx):\n -0.1000\n -12.0092\n -11.2628\n');
%使用非零θ计算和显示成本和梯度
test_theta = [-24; 0.2; 0.2];
[cost, grad] = costFunction(test_theta, X, y);
fprintf('\nCost at test theta: %f\n', cost);
fprintf('Expected cost (approx): 0.218\n');
fprintf('Gradient at test theta: \n');
fprintf(' %f \n', grad);
fprintf('Expected gradients (approx):\n 0.043\n 2.566\n 2.647\n');
fprintf('\nProgram paused. Press enter to continue.\n');
pause;
%用内置函数找最佳参数theta
%?'GradObj','on':用户自己定义函数的梯度。
%?'MaxIter',400:允许的最大迭代次数为400
options = optimset('GradObj', 'on', 'MaxIter', 400);
%fminuc函数的作用为取最小值
%theta和代价
[theta, cost] = fminunc(@(t)(costFunction(t, X, y)), initial_theta, options);
%打印theta
fprintf('Cost at theta found by fminunc: %f\n', cost);
fprintf('Expected cost (approx): 0.203\n');
fprintf('theta: \n');
fprintf(' %f \n', theta);
fprintf('Expected theta (approx):\n');
fprintf(' -25.161\n 0.206\n 0.201\n');
%画出决策边界
plotDecisionBoundary(theta, X, y);
hold on;
xlabel('Exam 1