博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Multivariate Linear Regression
阅读量:4149 次
发布时间:2019-05-25

本文共 1834 字,大约阅读时间需要 6 分钟。

clear,clc%梯度下降法x = load('ex3x.dat');y = load('ex3y.dat');m = length(y);x = [ones(m,1),x];%归一化数据feature scalingsigma = std(x); %求标准差mu = mean(x);   %求均值x(:,2) = (x(:,2) - mu(2))./ sigma(2); x(:,3) = (x(:,3) - mu(3))./ sigma(3);n = 50;    %n为迭代次数J = zeros(n , 1); alpha =[0.01, 0.03, 0.1, 0.3, 1, 1.3]; plotstyle = {'b', 'r', 'g', 'k', 'b--', 'r--'};for alpha_i = 1: size(alpha,2)    theta = zeros(size(x(1,:)))'  % initialize fitting parameters    for k=1:n  %n为迭代次数             J(k) = 1/(2*m).* (x * theta - y)' * (x * theta - y);          theta = theta - alpha(alpha_i)*(1/m)*(x'*(x*theta - y));      end        if(1 == alpha(alpha_i)) %通过实验发现alpha为1时效果最好,则此时的迭代后的theta值为所求的值        theta_grad_descent = theta    end        plot(0:n-1, J(1:n), char(plotstyle(alpha_i)),'LineWidth',2)    hold onend% now plot J% technically, the first J starts at the zero-eth iteration% but Matlab/Octave doesn't have a zero indexlegend('0.01','0.03','0.1','0.3','1','1.3');xlabel('Number of iterations')ylabel('Cost J')%预测:1650平方米,3个卧室的价格%测试数据x=[1,1650,3]x_test=[1,1650,3];price_grad_descend = theta_grad_descent'*[1 (x_test(2)-mu(2))/sigma(2) (x_test(3)-mu(3)/sigma(3))]'%Normal Equationsx = load('ex3x.dat');y = load('ex3y.dat');x = [ones(size(x,1),1) x];format long g %取消matlab的科学计数法theta_norequ = inv((x'*x))*x'*y;price_norequ = theta_norequ'*x_test'

运行结果如下:

图 1 学习速率alpha为不同值得时候,代价函数J的变换曲线

图2 梯度下降法和最小二乘法的预测结果

由上面的图可以知道当学习率alpha=1的时候,梯度下降时最快的,并且梯度下降法和最小二乘法的对于测试数据[1,1650,3]的预测结果是一样的。。

Gradient Descent Vs Normal Equation

Gradient Descent的特点:

(1)需要预先设定Learning rate;

(2)需要多次iteration

(3)需要Feature Scaling(如归一化处理:0-1之间),如果不做处理的话,梯度下降困难。

Normal Equation的特点:

(1)简单

(2)方便

(3)不需要Feature Scaling;

(4)需要大量的矩阵运算,特别是逆运算,在矩阵很大的情况相下会增加计算复杂度和内存容量

在Feature较少的时候,可以使用Normal Equation

如:当feature > 100000时 使用Gradient Descent ,feature < 100000时,使用Normal Equation

你可能感兴趣的文章
[LeetCode]3Sum
查看>>
[LeetCode]Add Two Numbers
查看>>
[LeetCode]Anagrams
查看>>
[LeetCode]Balanced Binary Tree
查看>>
[LeetCode]Best Time to Buy and Sell Stock
查看>>
[LeetCode]Best Time to Buy and Sell Stock II
查看>>
[LeetCode]Best Time to Buy and Sell Stock III
查看>>
[LeetCode]Binary Tree Inorder Traversal
查看>>
[LeetCode]Binary Tree Level Order Traversal
查看>>
[LeetCode]Climbing Stairs
查看>>
[LeetCode]Combination Sum II
查看>>
[LeetCode]Combinations
查看>>
[LeetCode]Construct Binary Tree from Inorder and Postorder Traversal
查看>>
[LeetCode]Convert Sorted Array to Binary Search Tree
查看>>
[LeetCode]Longest Valid Parentheses
查看>>
[LeetCode]Maximal Rectangle
查看>>
[LeetCode]Maximum Subarray
查看>>
[LeetCode]Median of Two Sorted Arrays
查看>>
[LeetCode]Merge Intervals
查看>>
[LeetCode]Merge k Sorted Lists
查看>>