线性回归与梯度下降(ML作业)
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
直接套用公式编写:
\]
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
公式采用:
\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作业)的更多相关文章
- 线性回归、梯度下降(Linear Regression、Gradient Descent)
转载请注明出自BYRans博客:http://www.cnblogs.com/BYRans/ 实例 首先举个例子,假设我们有一个二手房交易记录的数据集,已知房屋面积.卧室数量和房屋的交易价格,如下表: ...
- Andrew Ng机器学习公开课笔记 -- 线性回归和梯度下降
网易公开课,监督学习应用.梯度下降 notes,http://cs229.stanford.edu/notes/cs229-notes1.pdf 线性回归(Linear Regression) 先看个 ...
- 机器学习算法整理(一)线性回归与梯度下降 python实现
回归算法 以下均为自己看视频做的笔记,自用,侵删! 一.线性回归 θ是bias(偏置项) 线性回归算法代码实现 # coding: utf-8 get_ipython().run_line_mag ...
- 斯坦福机器学习视频笔记 Week1 线性回归和梯度下降 Linear Regression and Gradient Descent
最近开始学习Coursera上的斯坦福机器学习视频,我是刚刚接触机器学习,对此比较感兴趣:准备将我的学习笔记写下来, 作为我每天学习的签到吧,也希望和各位朋友交流学习. 这一系列的博客,我会不定期的更 ...
- 线性回归和梯度下降代码demo
程序所用文件:https://files.cnblogs.com/files/henuliulei/%E5%9B%9E%E5%BD%92%E5%88%86%E7%B1%BB%E6%95%B0%E6%8 ...
- Machine Learning--week2 多元线性回归、梯度下降改进、特征缩放、均值归一化、多项式回归、正规方程与设计矩阵
对于multiple features 的问题(设有n个feature),hypothesis 应该改写成 \[ \mathit{h} _{\theta}(x) = \theta_{0} + \the ...
- 2018.4.23-ml笔记(线性回归、梯度下降)
线性回归:找到最合适的一条线来最好的拟合我们的数据点. hθ(x) = θixi=θTx θ被称之为权重参数 θ0为拟合参数 对每个样本yi=θTxi + εi 误差ε是独立并且具有 ...
- 机器学习算法(优化)之一:梯度下降算法、随机梯度下降(应用于线性回归、Logistic回归等等)
本文介绍了机器学习中基本的优化算法—梯度下降算法和随机梯度下降算法,以及实际应用到线性回归.Logistic回归.矩阵分解推荐算法等ML中. 梯度下降算法基本公式 常见的符号说明和损失函数 X :所有 ...
- 从梯度下降到Fista
前言: FISTA(A fast iterative shrinkage-thresholding algorithm)是一种快速的迭代阈值收缩算法(ISTA).FISTA和ISTA都是基于梯度下降的 ...
随机推荐
- GVS灵动系列家族上新 | 稳住,我们能“银”
用天赐的色库 给生活增加些艺术的气息 生活本应多点探索的乐趣 今天 GVS灵动系列家族流光银(白玻璃) 全新上线 用灵感朝圣自然之道 邂逅另一种柔性美学 与早前的经典黑.星耀灰 和而不同,美美与共 携 ...
- 理想的GVS智能照明体验,就在汕头迎宾花园酒店
汕头,依海而生,海在城中央是汕头特色. 汕头湾将汕头分为南北两岸,造就绝美市区海岸线,一碧万顷的海湾,焕然一新的海港,在市区就能直接看海. 在北山湾,动可结伴冲浪,静可观海吹风,动静都是一种快乐. 当 ...
- EasyExcel 框架使用-读
EasyExcel 框架使用 官方介绍:JAVA解析Excel工具EasyExcel Java解析.生成Excel比较有名的框架有Apache poi.jxl.但他们都存在一个严重的问题就是非常的耗内 ...
- 教你三种jQuery框架实现元素显示及隐藏动画方式
摘要:在jQuery框架中对元素对象进行显示和隐藏有三种方式,分别是"默认方式显示和隐藏"."滑动方式显示和隐藏"."淡入淡出显示和隐藏". ...
- mybatis设置自动提交事务
我们想要mybatis帮助我们自动提交事务其实很简单,只需要在SqlSessionFactory对象的openSession方法中设置参数为true就可以了,mybatis工具类如下: public ...
- 惊呆了,Spring Boot居然这么耗内存!
Spring Boot总体来说,搭建还是比较容易的,特别是Spring Cloud全家桶,简称亲民微服务,但在发展趋势中,容器化技术已经成熟,面对巨耗内存的Spring Boot,小公司表示用不起.如 ...
- Kubernetes集群安装
一.环境介绍 主机名 IP地址 master 192.168.0.100 node1 192.168.0.101 node2 192.168.0.102 1.1.操作系统: CensOS8.4.210 ...
- 数据泵导出报错ORA-31693 ORA-02354 ORA-01466
1.Oracle数据泵导出schema时有报错: Connected to: Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - P ...
- 【Javascript + Vue】实现随机生成迷宫图片
前言 成品预览:https://codesandbox.io/s/maze-vite-15-i7oik?file=/src/maze.js 不久前写了一篇文章介绍了如何解迷宫:https://www. ...
- Docker与k8s的恩怨情仇(三)—后浪Docker来势汹汹
转载请注明出处:葡萄城官网,葡萄城为开发者提供专业的开发工具.解决方案和服务,赋能开发者. 上一节我们为大家介绍了Cloud Foundry等最初的PaaS平台如何解决容器问题,本文将为大家展示Doc ...