(吴恩达)机器学习课后练习二代码解析(ex2)

本文详细解析了吴恩达机器学习课程的第二课后练习ex2,涵盖逻辑回归及其多项式回归的代码解读,包括ex2.m、plotData.m、sigmoid.m、costFunction.m、fminunc()、plotDecisionBoundary.m和predict.m等函数的使用,以及绘制决策边界和计算模型精确度的过程。同时介绍了如何进行最大似然估计和代价函数的计算。

作业二: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 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值