Programming Exercise 1: Linear Regression
单变量线性回归
warmUpExercise
要求:输出5阶单位阵
直接使用eye(5,5)
即可
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,5);
% ===========================================
end
plotData
要求:读入若干组数据(x,y),将它们绘制成散点图
使用MATLAB的plot()
命令即可
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.
% ====================== YOUR CODE HERE ======================
% Instructions: Plot the training data into a figure using the
% "figure" and "plot" commands. Set the axes labels using
% the "xlabel" and "ylabel" commands. Assume the
% population and revenue data have been passed in
% as the x and y arguments of this function.
%
% Hint: You can use the 'rx' option with plot to have the markers
% appear as red crosses. Furthermore, you can make the
% markers larger by using plot(..., 'rx', 'MarkerSize', 10);
figure; % open a new figure window
data=load('ex1data1.txt');
[n,m]=size(data);
xdata=data(:,1);
ydata=data(:,2);
for i=1:n
plot(xdata,ydata,'rx');
end
xlabel('X Axis');
ylabel('Y Axis');
% ============================================================
end
输出结果:
computeCost
要求:读入\(m\)组数据(X,y),计算用\(y=\theta^T X(\theta=(\theta_0,\theta_1)^T,X=(1,x^{(i)})^T)\)拟合这组数据的均方误差\(J(\theta)\)
\[J(\theta)=\frac 1 {2m}\sum_{i=1}^m(\theta^T X^{(i)}-y^{(i)})^2\]
function J = computeCost(X, y, theta)
%传入:X,y为m维行向量,theta为二维列向量
%COMPUTECOST Compute cost for linear regression
% J = COMPUTECOST(X, y, theta) computes the cost of using theta as the
% parameter for linear regression to fit the data points in X and y
% Initialize some useful values
m = length(y); % number of training examples
% You need to return the following variables correctly
J = 0;
% ====================== YOUR CODE HERE ======================
% Instructions: Compute the cost of a particular choice of theta
% You should set J to the cost.
for i=1:m
J=J+(theta'*[1,X(i)]'-y(i))^2;
end
J=J/(2*m);
% =========================================================================
end