Loss函数

题目一:完成computeCost.m

function J = computeCost(X, y, 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. J = (1 / (2 * m))* sum((X * theta - y).^ 2); % ========================================================================= end

直接套用公式编写:

\[J = \frac{1}{2m} \sum_{i=0}^{m}(wx - y)^2
\]

Loss函数升级版: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))* sum((X * theta - y).^ 2); % ========================================================================= end

其实写法一模一样……

GD算法:gradientDescent.m

function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)
%GRADIENTDESCENT Performs gradient descent to learn theta
% theta = GRADIENTDESCENT(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 (computeCost) and gradient here.
%
temp = zeros(length(theta), 1);
for i = 1:length(theta)
temp(i, 1) = theta(i, 1) + alpha * (sum((y - X * theta) .* X(:, i))) / length(X);
end
theta = temp;
% ============================================================ % Save the cost J in every iteration
J_history(iter) = computeCost(X, y, theta); end end

由于当时写题目的时候就直接按照矩阵的写法写,所以其实复杂版写法也是一样的

GD复杂版算法:gradientDescent.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.
% temp = zeros(length(theta), 1);
for i = 1:length(theta)
temp(i, 1) = theta(i, 1) + alpha * (sum((y - X * theta) .* X(:, i))) / length(X);
end
theta = temp; % ============================================================ % Save the cost J in every iteration
J_history(iter) = computeCostMulti(X, y, theta); end end

特征缩放: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); for i = 1:length(X)
X(i, :) = (X(i, :) - mu) ./ sigma;
end
X_norm = X; % ============================================================ end

公式采用:

\[X = \frac{X - \mu}{\sigma} \\
\mu:avg \\
\sigma:std
\]

公式法:normalEqn.m

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 = (X' * X)^-1 * X' * y; % ------------------------------------------------------------- % ============================================================ end

线性回归与梯度下降(ML作业)的更多相关文章

  1. 线性回归、梯度下降(Linear Regression、Gradient Descent)

    转载请注明出自BYRans博客:http://www.cnblogs.com/BYRans/ 实例 首先举个例子,假设我们有一个二手房交易记录的数据集,已知房屋面积.卧室数量和房屋的交易价格,如下表: ...

  2. Andrew Ng机器学习公开课笔记 -- 线性回归和梯度下降

    网易公开课,监督学习应用.梯度下降 notes,http://cs229.stanford.edu/notes/cs229-notes1.pdf 线性回归(Linear Regression) 先看个 ...

  3. 机器学习算法整理(一)线性回归与梯度下降 python实现

    回归算法 以下均为自己看视频做的笔记,自用,侵删! 一.线性回归 θ是bias(偏置项) 线性回归算法代码实现 # coding: utf-8 ​ get_ipython().run_line_mag ...

  4. 斯坦福机器学习视频笔记 Week1 线性回归和梯度下降 Linear Regression and Gradient Descent

    最近开始学习Coursera上的斯坦福机器学习视频,我是刚刚接触机器学习,对此比较感兴趣:准备将我的学习笔记写下来, 作为我每天学习的签到吧,也希望和各位朋友交流学习. 这一系列的博客,我会不定期的更 ...

  5. 线性回归和梯度下降代码demo

    程序所用文件:https://files.cnblogs.com/files/henuliulei/%E5%9B%9E%E5%BD%92%E5%88%86%E7%B1%BB%E6%95%B0%E6%8 ...

  6. Machine Learning--week2 多元线性回归、梯度下降改进、特征缩放、均值归一化、多项式回归、正规方程与设计矩阵

    对于multiple features 的问题(设有n个feature),hypothesis 应该改写成 \[ \mathit{h} _{\theta}(x) = \theta_{0} + \the ...

  7. 2018.4.23-ml笔记(线性回归、梯度下降)

    线性回归:找到最合适的一条线来最好的拟合我们的数据点. hθ(x) = θixi=θTx    θ被称之为权重参数    θ0为拟合参数 对每个样本yi=θTxi + εi    误差ε是独立并且具有 ...

  8. 机器学习算法(优化)之一:梯度下降算法、随机梯度下降(应用于线性回归、Logistic回归等等)

    本文介绍了机器学习中基本的优化算法—梯度下降算法和随机梯度下降算法,以及实际应用到线性回归.Logistic回归.矩阵分解推荐算法等ML中. 梯度下降算法基本公式 常见的符号说明和损失函数 X :所有 ...

  9. 从梯度下降到Fista

    前言: FISTA(A fast iterative shrinkage-thresholding algorithm)是一种快速的迭代阈值收缩算法(ISTA).FISTA和ISTA都是基于梯度下降的 ...

随机推荐

  1. UiPath中恢复依赖项失败的解决方法

    目录 序言 正文 什么是依赖包? 如何查看项目使用了哪些版本的依赖包? 一.项目内查看 二.查看项目的 JSON 文件 问题根源 解决方法 一.「等」字诀 二.切换网络环境(根治) 三.手动复制依赖包 ...

  2. 使用Flutter设计一个好看的"我"页面

    近期遇到一些很烦的琐事,状态比较down,很多原本计划好的事情都耽搁了,实在是难顶-- 看到后台一直有朋友问怎么博客和公众号没有更新,所以我忙完得闲就来更了! 前言 起因是最近重拾以前的旧项目(业余做 ...

  3. SpringBoot2配置文件application.yaml

    源码基于SpringBoot 2.4.4 1.认识配置文件 1.1 配置文件的加载 创建SpringBoot项目的时候,会自动创建一个application.properties文件,该文件是Spri ...

  4. sql优化问题

    一.分析阶段 一 般来说,在系统分析阶段往往有太多需要关注的地方,系统各种功能性.可用性.可靠性.安全性需求往往吸引了我们大部分的注意力,但是,我们必须注意,性能 是很重要的非功能性需求,必须根据系统 ...

  5. 安装Apache、Nginx和PHP-基于Centos7环境

    使用的软件:putty或Xshell都可. 一.搭建Apache 1.编译安装 (1).安装编译器 yum install -y gcc (2)安装Opensll 查询官网得到OpenSSL下载网址h ...

  6. 题解 P6622 [省选联考 2020 A/B 卷] 信号传递

    洛谷 P6622 [省选联考 2020 A/B 卷] 信号传递 题解 某次模拟赛的T2,考场上懒得想正解 (其实是不会QAQ), 打了个暴力就骗了\(30pts\) 就火速溜了,参考了一下某位强者的题 ...

  7. 基于ABP落地领域驱动设计-02.聚合和聚合根的最佳实践和原则

    目录 前言 聚合 聚合和聚合根原则 包含业务原则 单个单元原则 事务边界原则 可序列化原则 聚合和聚合根最佳实践 只通过ID引用其他聚合 用于 EF Core 和 关系型数据库 保持聚合根足够小 聚合 ...

  8. 『无为则无心』Python基础 — 11、Python中的数据类型转换

    目录 1.为什么要进行数据类型转换 2.数据类型转换本质 3.数据类型转换用到的函数 4.常用数据类型转换的函数 (1)int()函数 (2)float()函数 (3)str()函数 (4)bool( ...

  9. 解决两个相邻的span,或者input和button中间有间隙,在css中还看不到

    <span id="time"></span><span id="second"></span> <inp ...

  10. 浏览器中js怎么将图片下载而不是直接打开

    网上找了好多方法都是不能用的,经过试验在Chrome中都是直接打开. 经过自己的摸索,找到了一套能用的解决方案 var database = "data:image/jpg;base64,& ...