多变量线性回归——梯度下降MATLAB矩阵实现

参考吴恩达机器学习视频,此为其线性回归作业。
ex1_2
多变量的假设h表示为:

多变量线性回归——梯度下降MATLAB矩阵实现
代价函数:
多变量线性回归——梯度下降MATLAB矩阵实现
找出使得代价函数最小的一系列参数。
多变量线性回归的批量梯度下降算法为:
多变量线性回归——梯度下降MATLAB矩阵实现
求导后得到:
多变量线性回归——梯度下降MATLAB矩阵实现
作业:
取出ex1data2.txt中的数据,第一列为房子尺寸,第二列为卧室数量,第三列为房子价格。
clear
clc
data = load('ex1data2.txt'); % read comma separated data
x1 = data(:, 1);  % the size of the house
x2 = data(:, 2);  % the number of bedrooms
yT = data(:, 3);  % the price of the house
y = yT.';
m = length(y); % number of training examples
figure(1) %图1
plot3(x1,x2,y, 'rx', 'MarkerSize', 10); % Plot the data
xlabel('the size of the house'); % Set the x axis label
ylabel('the number of bedrooms'); % Set the y axis label
zlabel('the price of the house'); % Set the z axis label
grid on;

多变量线性回归——梯度下降MATLAB矩阵实现
梯度下降程序:
在x前乘系数,使x在[0,1]范围内
%使x1、x2在[0,1]范围内
x = [ones(1,m); 0.0001*x1.'; 0.1*x2.']; % 加第一列为全1,之后为x1、x2
theta = zeros(3, 1); % initialize fitting parameters

iterations = 1000; %迭代最大次数
alpha = 0.01; %学习率  %改变学习率,结果不一样
s = zeros(iterations, 1);  %代价函数中的累加值
J = zeros(iterations, 1);  %代价函数值

for k = 1:1:iterations
    p = zeros(3, 1);  %迭代一次,累计清零
    for i = 1:1:m
        s(k) = s(k)+(theta.'*x(:,i)-y(i)).^2; %求J函数的累加
        %求偏导
        p = p+(theta.'*x(:,i)-y(:,i))*x(:,i); %对theta求偏导的累加
    end
    J(k) = s(k)/(2*m);  %代价函数
    theta = theta-(alpha/m)*p;  %更新theta参数
    if k>1  %为了下面k-1有索引
        if J(k-1)-J(k)<1e+2   %若误差小于10^2,则停止迭代
             break;
        end
    end
end

theta  %输出显示theta的值

得到的θ参数矩阵:

theta =
1.0e+05 *

2.7824
1.2992
1.2073

画出代价函数J:

figure(2)  %图2
plot(J)  %画出代价函数
ylabel('J(θ)'); % Set the y axis label
xlabel('iterations'); % Set the x axis label
grid on

多变量线性回归——梯度下降MATLAB矩阵实现

代价函数J的数值过大,需迭代很多次才能减到足够小。

Original: https://blog.csdn.net/c11556913/article/details/111594278
Author: Phyllis_C
Title: 多变量线性回归——梯度下降MATLAB矩阵实现

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/635678/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球