计算代价函数
function J = computeCost( X,y,theta)
%X为设计矩阵 m行2列 第一列为1,第二列表示特征量x theta为2*1矩阵
m=length(y)%m为样本数
%X*theta结果为m*1矩阵,每一行代表一个样本的预测值
%-y结果为与真实值的差值
J=sum( (X*theta-y).^2 )/(2*m)
end
梯度下降法迭代theta
function [ theta,J_history ] = gradientDescent(X, y, theta, alpha, iterations)
m=length(y);
J_history=zeros(iterations,1);%初始化大小 防止迭代时不停改变长度
for num=1:iterations
%取出theta是为了实现同步更新
theta0=theta(1);
theta1=theta(2);
x=X(:,2);%用于theta更新时的点乘
theta0=theta0-alpha*sum( X*theta-y )/m;
theta1=theta1-alpha*sum( (X*theta-y).*x )/m;
theta=[theta0;theta1];
J_history(num)=computeCost(X,y,theta);%代价函数的历史值
end
end
绘制预测直线与原始数据图、参数与代价函数三维曲面图与等高线图、迭代次数与代价函数关系图。
clear;clc;
data=load('ex1data1.txt')
%散点图
X=data(:,1);
y=data(:,2);
plot(X,y,'rx','MarkerSize',5);
hold on;
%预测曲线
m=length(y);
X=[ones(m,1),X];
theta=[0;0];
alpha=0.01;
iterations=1500;
[theta,J]=gradientDescent(X,y,theta,alpha,iterations);
plot(data(:,1),X*theta);
title('预测曲线与散点图');
%迭代次数与代价函数关系图
figure;
plot((1:1500),J);
title('迭代次数与代价函数关系图');
%参数与代价函数三维曲面与等高线图
theta0=linspace(-10,10,100);
theta1=linspace(-4,4,100);
Jval=zeros(100,100);
for i=1:100
for j=1:100
Jval(i,j)=computeCost(X,y,[theta0(i);theta1(j)]);
end
end
figure;
Jval=Jval';%必须转置 否则X Y是反的 surf函数第三个参数 是在线性存储中心固定y移动x Z(i,j)是x(j) y(i)取到的
surf(theta0, theta1, Jval);
xlabel('\theta_0'); ylabel('\theta_1');
title('参数与代价函数三维曲面');
figure;
contour(theta0, theta1, Jval,logspace(-2, 3, 20))%指数方式等分等高线
xlabel('\theta_0'); ylabel('\theta_1');
hold on;
plot(theta(1),theta(2),'rx','MarkerSize',10)%梯度下降找到的点
title('参数与代价函数等高线图');