多元线性回归
提交作业情况:

背景:预测房价
数据集:房屋大小,卧室的数量,房价。

Loading data ...
First 10 examples from the dataset: x = [2104 3], y = 399900 x = [1600 3], y = 329900 x = [2400 3], y = 369000 x = [1416 2], y = 232000 x = [3000 4], y = 539900 x = [1985 4], y = 299900 x = [1534 3], y = 314900 x = [1427 3], y = 198999 x = [1380 3], y = 212000 x = [1494 3], y = 242500
Program paused. Press enter to continue.

数值归一化

减去均值,然后除以标准差。
两者在matlab中有对应的函数,均值的函数名mean,标准差的函数名std
featureNormalize.m文件

function [X_norm, mu, sigma] = featureNormalize(X)
%FEATURENORMALIZE Normalizes the features in X
%   FEATURENORMALIZE(X) returns a normalized version of X where
%   the mean value of each feature is 0 and the standard deviation
%   is 1. This is often a good preprocessing step to do when
%   working with learning algorithms.% You need to set these values correctly
X_norm = X;%房子大小,卧室的数量
mu = zeros(1, size(X, 2));
sigma = zeros(1, size(X, 2));% ====================== YOUR CODE HERE ======================
% Instructions: First, for each feature dimension, compute the mean
%               of the feature and subtract it from the dataset,
%               storing the mean value in mu. Next, compute the
%               standard deviation of each feature and divide
%               each feature by it's standard deviation, storing
%               the standard deviation in sigma.
%
%               Note that X is a matrix where each column is a
%               feature and each row is an example. You need
%               to perform the normalization separately for
%               each feature.
%
% Hint: You might find the 'mean' and 'std' functions useful.
%
mu=mean(X);
sigma=std(X);
X_norm=(X-mu)./sigma;
% ============================================================end

多元线性回归的代价函数

矩阵形式
J(θ)=12m(Xθ−y)T(Xθ−y)J(\theta)=\frac{1}{2m}(X\theta-y)^T(X\theta-y)J(θ)=2m1​(Xθ−y)T(Xθ−y)

其中
X是一个矩阵,维度是(m×(n+1))(m\times (n+1))(m×(n+1)),
θ\thetaθ是一个向量,维度是((n+1)×1)((n+1)\times 1)((n+1)×1)
y是一个列向量,维度是(m×1)(m\times 1)(m×1)

computeCostMulti.m文件

function J = computeCostMulti(X, y, theta)
%COMPUTECOSTMULTI Compute cost for linear regression with multiple variables
%   J = COMPUTECOSTMULTI(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.J=1/(2*m)*(X*theta-y)'*(X*theta-y);% =========================================================================end

多元线性回归梯度

梯度下降法求θ\thetaθ:

θ=θ−1mXT(Xθ−y)\theta=\theta-\frac{1}{m}X^T(X\theta-y) θ=θ−m1​XT(Xθ−y)
下面的代码主要用来实现此公式
gradientDescentMulti.m文件

function [theta, J_history] = gradientDescentMulti(X, y, theta, alpha, num_iters)
%GRADIENTDESCENTMULTI Performs gradient descent to learn theta
%   theta = GRADIENTDESCENTMULTI(x, y, theta, alpha, num_iters) updates theta by
%   taking num_iters gradient steps with learning rate alpha% Initialize some useful values
m = length(y); % number of training examples
J_history = zeros(num_iters, 1);for iter = 1:num_iters% ====================== YOUR CODE HERE ======================% Instructions: Perform a single gradient step on the parameter vector%               theta. %% Hint: While debugging, it can be useful to print out the values%       of the cost function (computeCostMulti) and gradient here.%theta=theta-alpha/m*X'*(X*theta-y);% ============================================================% Save the cost J in every iteration    J_history(iter) = computeCostMulti(X, y, theta);endend

选择(这也是学习率和迭代次数比较合理的选择)

% Choose some alpha value
alpha = 0.09;
num_iters = 50;

得到的收敛图

得到的收敛图

% Choose some alpha value
alpha = 0.12;
num_iters = 50;

% Choose some alpha value
alpha = 0.15;
num_iters = 50;

得到的收敛图

part2完整代码

%% ================ Part 2: Gradient Descent ================% ====================== YOUR CODE HERE ======================
% Instructions: We have provided you with the following starter
%               code that runs gradient descent with a particular
%               learning rate (alpha).
%
%               Your task is to first make sure that your functions -
%               computeCost and gradientDescent already work with
%               this starter code and support multiple variables.
%
%               After that, try running gradient descent with
%               different values of alpha and see which one gives
%               you the best result.
%
%               Finally, you should complete the code at the end
%               to predict the price of a 1650 sq-ft, 3 br house.
%
% Hint: By using the 'hold on' command, you can plot multiple
%       graphs on the same figure.
%
% Hint: At prediction, make sure you do the same feature normalization.
%fprintf('Running gradient descent ...\n');% Choose some alpha value
alpha = 0.12;
num_iters = 50;% Init Theta and Run Gradient Descent
theta = zeros(3, 1);
[theta, J_history] = gradientDescentMulti(X, y, theta, alpha, num_iters);% Plot the convergence graph
figure;
hold on;
plot(1:numel(J_history), J_history, '-g', 'LineWidth', 2);
xlabel('Number of iterations');
ylabel('Cost J');% Display gradient descent's result
fprintf('Theta computed from gradient descent: \n');
fprintf(' %f \n', theta);
fprintf('\n');% Estimate the price of a 1650 sq-ft, 3 br house
% ====================== YOUR CODE HERE ======================
% Recall that the first column of X is all-ones. Thus, it does
% not need to be normalized.
price = 0; % You should change this
price=[1 ([1650 3]-mu)./sigma]*theta;% ============================================================fprintf(['Predicted price of a 1650 sq-ft, 3 br house ' ...'(using gradient descent):\n $%f\n'], price);fprintf('Program paused. Press enter to continue.\n');
pause;

梯度下降法预测房价的代码

price=[1 ([1650 3]-mu)./sigma]*theta;

得到的结果

Running gradient descent ...
Theta computed from gradient descent: 339842.312379 106499.134141 -2521.749858 Predicted price of a 1650 sq-ft, 3 br house (using gradient descent):$293411.151468

使用正规方程

正规方程求解θ\thetaθ 的公式为
θ=(XTX)−1XTy\theta=(X^TX)^{-1}X^T yθ=(XTX)−1XTy

function [theta] = normalEqn(X, y)
%NORMALEQN Computes the closed-form solution to linear regression
%   NORMALEQN(X,y) computes the closed-form solution to linear
%   regression using the normal equations.theta = zeros(size(X, 2), 1);% ====================== YOUR CODE HERE ======================
% Instructions: Complete the code to compute the closed form solution
%               to linear regression and put the result in theta.
%% ---------------------- Sample Solution ----------------------theta=pinv(X'*X)*X'*y;% -------------------------------------------------------------% ============================================================end

part3完整代码

%% ================ Part 3: Normal Equations ================fprintf('Solving with normal equations...\n');% ====================== YOUR CODE HERE ======================
% Instructions: The following code computes the closed form
%               solution for linear regression using the normal
%               equations. You should complete the code in
%               normalEqn.m
%
%               After doing so, you should complete this code
%               to predict the price of a 1650 sq-ft, 3 br house.
%%% Load Data
data = csvread('ex1data2.txt');
X = data(:, 1:2);
y = data(:, 3);
m = length(y);% Add intercept term to X
X = [ones(m, 1) X];% Calculate the parameters from the normal equation
theta = normalEqn(X, y);% Display normal equation's result
fprintf('Theta computed from the normal equations: \n');
fprintf(' %f \n', theta);
fprintf('\n');% Estimate the price of a 1650 sq-ft, 3 br house
% ====================== YOUR CODE HERE ======================
price = 0; % You should change this
%price=[1 ([1650 3]-mu)./sigma]*theta;
price=[1 1650 3]*theta;
% ============================================================fprintf(['Predicted price of a 1650 sq-ft, 3 br house ' ...'(using normal equations):\n $%f\n'], price);

预测房价的代码

price=[1 1650 3]*theta;

这里不需要再进行归一化,

得到的结果```cpp
Solving with normal equations...
Theta computed from the normal equations: 89597.909544 139.210674 -8738.019113 Predicted price of a 1650 sq-ft, 3 br house (using normal equations):$293081.464335

最后两者的结果进行比较,得到不同的θ\thetaθ值,最后预测的房价结果差不多,使用梯度下降法预测的房价是 $293411.151468,使用正规方程预测的房价是$293081.464335

Normalizing Features ...
Running gradient descent ...
Theta computed from gradient descent: 339842.312379 106499.134141 -2521.749858 Predicted price of a 1650 sq-ft, 3 br house (using gradient descent):$293411.151468
Program paused. Press enter to continue.
Solving with normal equations...
Theta computed from the normal equations: 89597.909544 139.210674 -8738.019113 Predicted price of a 1650 sq-ft, 3 br house (using normal equations):$293081.464335

请注意预测房价的代码差别

%梯度下降法
%需要归一化
price=[1 ([1650 3]-mu)./sigma]*theta;
%正规方程
price=[1 1650 3]*theta;


当特征数量不大(小于10000)时,通常采用正规方程方法来计算参数θ\thetaθ,而不是用梯度下降法。

图片来源:黄海广,机器学习笔记

吴恩达机器学习Ex1多元回归部分相关推荐

  1. 吴恩达机器学习ex1——通过人口预测小摊经济状况

    吴恩达机器学习ex1 完整代码 代码输出 完整代码 import numpy as np import pandas as pd import matplotlib.pyplot as plt#获取一 ...

  2. 吴恩达机器学习ex1 Python实现

    ** ** 机器学习小白入门,在看吴恩达机器学习课程的同时找到了课后的练习.开贴用于记录学习(copy)过程. 学习参考:吴恩达机器学习ex1 单变量线性回归 题目描述:在本部分的练习中,您将使用一个 ...

  3. 吴恩达机器学习Ex1

    本次是week2 Linear Regression 的作业情况. 作业得分情况 作业代码 通过执行ex1.m文件获得想要的结果,其他函数为该文件所调用. ex1.m文件 %% Machine Lea ...

  4. 吴恩达机器学习MATLAB代码笔记(1)梯度下降

    吴恩达机器学习MATLAB代码笔记(1)梯度下降 单变量线性回归 1.标记数据点(Plotting the Date) fprintf('Plotting Data') data = load('D: ...

  5. 吴恩达机器学习中文版课后题(中文题目+数据集+python版答案)week1 线性回归

    一.单线性回归问题 参考:https://blog.csdn.net/qq_42333474/article/details/119100860 题目一: 您将使用一元线性回归来预测食品车的利润.假设 ...

  6. 吴恩达机器学习作业ex2-python实现

    系列文章目录 吴恩达机器学习作业ex1-python实现 吴恩达机器学习作业ex2-python实现 吴恩达机器学习作业ex3-python实现 作业说明及数据集 链接:https://pan.bai ...

  7. 吴恩达机器学习视频作业(Matlab实现)

    吴恩达机器学习视频的课后作业,使用matlab实现 ex1  线性回归 1.热身 建立一个5*5矩阵 A=eye(5); 2.单变量的线性回归 需要根据城市人口数量,预测开小吃店的利润 数据在ex1d ...

  8. 吴恩达机器学习课后作业——线性回归(Python实现)

    1.写在前面 吴恩达机器学习的课后作业及数据可以在coursera平台上进行下载,只要注册一下就可以添加课程了.所以这里就不写题目和数据了,有需要的小伙伴自行去下载就可以了. 作业及数据下载网址:吴恩 ...

  9. 吴恩达机器学习手写笔记(持续更新ing)

    吴恩达机器学习笔记 文章目录 吴恩达机器学习笔记 1.Introduction 2.Linear regression with one variable 3.Linear Algebra revie ...

最新文章

  1. 进程通信之 Binder 机制浅析
  2. 回文字符串(Palindromic_String)
  3. java中no1_Java程序设计实验(NO.1).doc
  4. MapReduce运行流程分析
  5. MVPArms官方首发一键生成组件化,体验纯傻瓜式组件化开发
  6. java模拟借书系统E R图_作业—模拟借书系统
  7. 视频教程-Docker 基础与实践(DevOps系列)-Linux
  8. 计算几何05_B样条曲线
  9. C# :弧度角度转换
  10. 《三国空城计》何为真知己真智慧
  11. 快速了解Mybatis Plus 的用法以及使用举例
  12. 网线水晶头两种标准的接法
  13. [博学谷学习记录]超强总结,用心分享|人工智能机械学习基础知识线性回归总结分享
  14. Android 12 Watchdog(1) 介绍与启动
  15. UNIX环境高级编程——1.UNIX基础知识
  16. 网络信息安全模型概述
  17. win10搜索框突然不能使用了
  18. 语音识别数据预处理(添加噪音)和特征提取
  19. OpenGL学习随笔(三)——2022.1.24
  20. 需求精益思想在项目管理中的实战应用

热门文章

  1. Cocos Creator实现的《点我+1》
  2. Openlayers 2.X加载高德地图
  3. SQL Server Window Function 窗体函数读书笔记二 - A Detailed Look at Window Functions
  4. MySQL errno: 145 错误修复
  5. java加密解密代码_base64位加密解密原理及js代码实现
  6. python怎么显示结果_python中plot实现即时数据动态显示方法
  7. unity怎么显示骨骼_骨骼动画的原理及在Unity中的使用
  8. 卷积神经网络图像卷积池化尺寸计算器
  9. 【PC工具】Windows下用RaiDrive挂载各种网盘为本地硬盘,挂载Google Drive网盘为本地硬盘使用...
  10. 【维纳滤波】通过MATLAB自带的维纳滤波函数进行滤波