本博客内容是对Coursera上Andrew Ng的《机器学习》的编程作业的总结,本博文是在Matlab基础上对第一次编程作业的总结,随后的博文会对所有的编程作业进行一一总结。
本博文主要对作业中需要实现的代码进行讲解。
脚本文件ex1.m用来执行单变量线性回归,ex1_multi.m用来执行多变量线性回归。在这里先看ex1.m中的代码。
单变量线性回归
%% Initialization
clear ; close all; clc
初始化部分:clear 清除工作区的所有变量,还可以后面跟变量名来清除某个变量;close all 关闭所有窗口(显示图像的figure窗口);clc 清除命令窗口的内容(就是命令界面以前的命令);两个百分号%%是matlab中用来表示代码块的注释,从%%开始到下一个%%之间会作为一个代码块,在matlab中查看时会用黄白相间显示。
%% ==================== Part 1: Basic Function ====================
% Complete warmUpExercise.m
fprintf('Running warmUpExercise ... \n');
fprintf('5x5 Identity Matrix: \n');
warmUpExercise()
fprintf('Program paused. Press enter to continue.\n');
pause;
fprintf和c语言中的printf用法类似,也支持%d等占位符,也可以直接输出字符串,\n表示换行符,Matlab中字符串用单引号括起来;pause表示暂停。
中间调用了warmUpExercise函数,对应warmUpExercise.m,这个函数要求输出一个5*5的单位矩阵,直接使用eye函数就可以了。
warmUpExercise.m实现:
function A = warmUpExercise()
%WARMUPEXERCISE Example function in octave
% A = WARMUPEXERCISE() is an example function that returns the 5x5 identity matrix
A = [];
% ============= YOUR CODE HERE ==============
% Instructions: Return the 5x5 identity matrix
% In octave, we return values by defining which variables
% represent the return values (at the top of the file)
% and then set them accordingly.
A = eye(5);
% ===========================================
end
warmUpExercise函数无输入参数,返回值为A。
%% ======================= Part 2: Plotting =======================
fprintf('Plotting Data ...\n')
data = load('ex1data1.txt');
X = data(:, 1); y = data(:, 2);
m = length(y); % number of training examples
% Plot Data
% Note: You have to complete the code in plotData.m
plotData(X, y);
fprintf('Program paused. Press enter to continue.\n');
pause;
这一部分先通过load从文件读取数据,然后调用plotData来画图。
plotData.m实现:
function plotData(x, y)
%PLOTDATA Plots the data points x and y into a new figure
% PLOTDATA(x,y) plots the data points and gives the figure axes labels of
% population and profit.
% =========&#