一段有关线搜索的从python到matlab的代码
在Udacity上很多关于机器学习的课程几乎都是基于python语言的,博主“ttang”的博文“重新发现梯度下降法——backtracking line search”里对回溯线搜索的算法实现也是用python写的,这对没有接触过python的我来说,内心是非常“抓狂”的。看到代码有想看到运行结果的冲动,暂时又不想去下载软件,好在这段代码简单、清晰,不信,你看原代码【1】
# -*- coding: cp936 -*-
#optimization test, y = (x-3)^2
from matplotlib.pyplot import figure, hold, plot, show, xlabel, ylabel, legend
def f(x):
"The function we want to minimize"
return (x-3)**2
def f_grad(x):
"gradient of function f"
return 2*(x-3)
x = 0
y = f(x)
err = 1.0
maxIter = 300
curve = [y]
it = 0
step = 0.1
#下面展示的是我之前用的方法,看上去貌似还挺合理的,但是很慢
while err > 1e-4 and it < maxIter:
it += 1
gradient = f_grad(x)
new_x = x - gradient * step
new_y = f(new_x)
new_err = abs(new_y - y)
if new_y > y: #如果出现divergence的迹象,就减小step size
step *= 0.8
err, x, y = new_err, new_x, new_y
print 'err:', err, ', y:', y
curve.append(y) print 'iterations: ', it
figure(); hold(True); plot(curve, 'r*-')
xlabel('iterations'); ylabel('objective function value') #下面展示的是backtracking line search,速度很快
x = 0
y = f(x)
err = 1.0
alpha = 0.25
beta = 0.8
curve2 = [y]
it = 0 while err > 1e-4 and it < maxIter:
it += 1
gradient = f_grad(x)
step = 1.0
while f(x - step * gradient) > y - alpha * step * gradient**2:
step *= beta
x = x - step * gradient
new_y = f(x)
err = y - new_y
y = new_y
print 'err:', err, ', y:', y
curve2.append(y) print 'iterations: ', it
plot(curve2, 'bo-')
legend(['gradient descent I used', 'backtracking line search'])
show()
确实是为了观察实验结果,暂时又不想去装python,就把上面的代码改成了matlab code
% optimization test, y = (x-3)^2
% -*- zw -*-
f=@(x)(x-3)^2;
diff_f=@(x)2*(x-3);
x = 0;
y = f(x);
err = 1.0;
maxIter = 300;
curve = [];
iter = 0;
step = 0.1;
% 下面展示的是我之前用的方法,看上去貌似还挺合理的,但是很慢
while err > 1e-4 && iter < maxIter
iter=iter+ 1;
gradient = diff_f(x);
new_x = x - gradient * step;
new_y = f(new_x);
new_err = abs(new_y - y);
if new_y > y
% 如果出现divergence的迹象,就减小step size
step =step* 0.8;
end
err=new_err;
x=new_x;
y=new_y; fprintf('iteration: %d, err: %f, y: %f \n',iter, err, y);
curve(iter)=y;
end figure(); axes('linewidth',1, 'box', 'on', 'FontSize',16);
hold on; plot(curve, 'r*-')
xlabel('iterations'); ylabel('objective function value') % 下面展示的是backtracking line search,速度很快
x = 0;
y = f(x);
err = 1.0;
alpha = 0.25;
beta = 0.8;
curve2 = [];
iter = 0; while err > 1e-4 && iter < maxIter
iter =iter+ 1;
gradient = diff_f(x);
step = 1.0;
while f(x - step * gradient) > y - alpha * step * gradient^2
step =step* beta;
end
x = x - step * gradient;
new_y = f(x);
err = y - new_y;
y = new_y;
fprintf( 'iteration: %d, err: %f, y: %f \n', iter,err, y);
curve2(iter)=y;
end plot(curve2, 'bo-')
legend('gradient descent I used', 'backtracking line search')
Matlab代码运行的结果

部分细节问题可以参考和对比原博文【1】。
参考:
【1】http://www.cnblogs.com/fstang/p/4192735.html
一段有关线搜索的从python到matlab的代码的更多相关文章
- THINKPHP_(2)_TP模型的多表关联查询和多表字段的关键字搜索。
问题: 上述内容中,标题和学年属于一个数据表.分类则属于另外一个数据表,并且是利用id关联后,另外一个数据表中的title字段. 需要设置关键字搜索,实现多表关联查询和多表字段的关键字搜索. 解决方法 ...
- [原创]用“人话”解释不精确线搜索中的Armijo-Goldstein准则及Wolfe-Powell准则
[原创]用“人话”解释不精确线搜索中的Armijo-Goldstein准则及Wolfe-Powell准则 转载请注明出处:http://www.codelast.com/ line search(一维 ...
- 【原创】回溯线搜索 Backtracking line search
机器学习中很多数值优化算法都会用到线搜索(line search).线搜索的目的是在搜索方向上找到是目标函数\(f(x)\)最小的点.然而,精确找到最小点比较耗时,由于搜索方向本来就是近似,所以用较小 ...
- 用“人话”解释不精确线搜索中的Armijo-Goldstein准则及Wolfe-Powell准则
转载请注明出处:http://www.codelast.com/ line search(一维搜索,或线搜索)是最优化(Optimization)算法中的一个基础步骤/算法.它可以分为精确的一维搜索以 ...
- 线搜索(line search)方法
在机器学习中, 通常需要求某个函数的最值(比如最大似然中需要求的似然的最大值). 线搜索(line search)是求得一个函数\(f(x)\)的最值的两种常用迭代方法之一(另外一个是trust re ...
- 50个必备的实用jQuery代码段+ 可以直接拿来用的15个jQuery代码片段
50个必备的实用jQuery代码段+ 可以直接拿来用的15个jQuery代码片段 本文会给你们展示50个jquery代码片段,这些代码能够给你的javascript项目提供帮助.其中的一些代码段是从j ...
- [转]numpy线性代数基础 - Python和MATLAB矩阵处理的不同
转自:http://blog.csdn.net/pipisorry/article/details/45563695 http://blog.csdn.net/pipisorry/article/de ...
- 如何调用另一个python文件中的代码
模块的搜索路径 模块的搜索路径都放在了sys.path列表中,如果缺省的sys.path中没有含有自己的模块或包的路径,可以动态的加入(sys.path.apend)即可.下面是sys.path在Wi ...
- 利用Python编写Windows恶意代码!自娱自乐!勿用于非法用途!
本文主要展示的是通过使用python和PyInstaller来构建恶意软件的一些poc. 利用Python编写Windows恶意代码!自娱自乐!勿用于非法用途!众所周知的,恶意软件如果影响到了他人的生 ...
随机推荐
- 模板引擎doT.js用法详解
作为一名前端攻城师,经常会遇到从后台ajax拉取数据再显示在页面的情境,一开始我们都是从后台拉取再用字符串拼接的方式去更达到数据显示在页面! <!-- 显示区域 --> <div i ...
- 编写一个自定义事件类,包含on/off/emit/once方法
function Event() { this._events = {}; } Event.prototype.on = function(type, fn) { if (!this._events[ ...
- luogu P3031 [USACO11NOV]高于中位数Above the Median (树状数组优化dp)
链接:https://www.luogu.org/problemnew/show/P3031 题面: 题目描述 Farmer John has lined up his N (1 <= N &l ...
- Http请求头和响应头(Get和Post)
HTTP简介 HTTP协议是Hyper Text Transfer Protocol(超文本传输协议)的缩写,是用于从万维网(WWW:World Wide Web )服务器传输超文本到本地浏览器的传送 ...
- springboot @vaule注解失效解决办法
在Controller类里面通过@Value将参数注入进来,最后的确成功了.因此基于此经验,我便在其他使用的类里面也采用这样的方式注入参数,但是发现去失效了,报错为NULL,说明参数并没有我们料想的被 ...
- Kali Linux安装AWVS漏扫工具
Acunetix是全球排名前三的漏洞发现厂商,其全称(Acunetix Web Vulnerability Scanner)AWVS是业内领先的网络漏洞扫描器,其被广泛赞誉为包括最先进的SQL注入和X ...
- How does a browser know which response belongs to which request?
Today I knows that the server never send a request to a client! It just make response~ So,if the bro ...
- luogu4777[模板]拓展中国剩余定理题解
题目链接 https://www.luogu.org/problemnew/show/P4777 分析 扩展\(CRT\)就是解决模数不互质的情况,说是扩展\(CRT\),其实都是扩欧... 先来考虑 ...
- [转载]Grid Search
[转载]Grid Search 初学机器学习,之前的模型都是手动调参的,效果一般.同学和我说他用了一个叫grid search的方法.可以实现自动调参,顿时感觉非常高级.吃饭的时候想调参的话最差不过也 ...
- 【php设计模式】装饰器模式
装饰器模式,顾名思义,就是对已经存在的某些类进行装饰,以此来扩展一些功能.其结构图如下: Component为统一接口,也是装饰类和被装饰类的基本类型. ConcreteComponent为具体实现类 ...