在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的代码的更多相关文章

  1. THINKPHP_(2)_TP模型的多表关联查询和多表字段的关键字搜索。

    问题: 上述内容中,标题和学年属于一个数据表.分类则属于另外一个数据表,并且是利用id关联后,另外一个数据表中的title字段. 需要设置关键字搜索,实现多表关联查询和多表字段的关键字搜索. 解决方法 ...

  2. [原创]用“人话”解释不精确线搜索中的Armijo-Goldstein准则及Wolfe-Powell准则

    [原创]用“人话”解释不精确线搜索中的Armijo-Goldstein准则及Wolfe-Powell准则 转载请注明出处:http://www.codelast.com/ line search(一维 ...

  3. 【原创】回溯线搜索 Backtracking line search

    机器学习中很多数值优化算法都会用到线搜索(line search).线搜索的目的是在搜索方向上找到是目标函数\(f(x)\)最小的点.然而,精确找到最小点比较耗时,由于搜索方向本来就是近似,所以用较小 ...

  4. 用“人话”解释不精确线搜索中的Armijo-Goldstein准则及Wolfe-Powell准则

    转载请注明出处:http://www.codelast.com/ line search(一维搜索,或线搜索)是最优化(Optimization)算法中的一个基础步骤/算法.它可以分为精确的一维搜索以 ...

  5. 线搜索(line search)方法

    在机器学习中, 通常需要求某个函数的最值(比如最大似然中需要求的似然的最大值). 线搜索(line search)是求得一个函数\(f(x)\)的最值的两种常用迭代方法之一(另外一个是trust re ...

  6. 50个必备的实用jQuery代码段+ 可以直接拿来用的15个jQuery代码片段

    50个必备的实用jQuery代码段+ 可以直接拿来用的15个jQuery代码片段 本文会给你们展示50个jquery代码片段,这些代码能够给你的javascript项目提供帮助.其中的一些代码段是从j ...

  7. [转]numpy线性代数基础 - Python和MATLAB矩阵处理的不同

    转自:http://blog.csdn.net/pipisorry/article/details/45563695 http://blog.csdn.net/pipisorry/article/de ...

  8. 如何调用另一个python文件中的代码

    模块的搜索路径 模块的搜索路径都放在了sys.path列表中,如果缺省的sys.path中没有含有自己的模块或包的路径,可以动态的加入(sys.path.apend)即可.下面是sys.path在Wi ...

  9. 利用Python编写Windows恶意代码!自娱自乐!勿用于非法用途!

    本文主要展示的是通过使用python和PyInstaller来构建恶意软件的一些poc. 利用Python编写Windows恶意代码!自娱自乐!勿用于非法用途!众所周知的,恶意软件如果影响到了他人的生 ...

随机推荐

  1. sort(()=>{return Math.random()-0.5)}乱序数组不准确

    为什么sort(()=>{return Math.random()-0.5)}乱序数组不准确.(注意结合插入排序原理来理解) @1.chrome浏览器对于数组长度10以内为插入排序.反之则快速排 ...

  2. [LuoguP2157][SDOI2009]学校食堂_状压dp

    学校食堂 题目链接:https://www.luogu.org/problem/P2157 数据范围:略. 题解: 发现$B$特别小,很容易想到状压. 即在$dp$的时候弄出来$f_{(i,j,k)} ...

  3. sql数据库的基础语句

    1, 创建数据库 create database database-name 2, 删除数据库 drop database dbname 3, 备份sql server 创建 备份数据的device ...

  4. HashMap集合-遍历方法

    # HashMap集合-遍历方法 先定义好集合: public static void main(String[] args) { Map<String,String> onemap=ne ...

  5. Python 基础(十六)--随机数模块

    random随机数模块 random.randint(1,10):随机1-10包括10 random.randrange(1,10,2):在1.3.5.7.9中随机,类似切片,不包括10 random ...

  6. VS2013 + Nunit 安装搭建

    Nunit 官方给我提供了Nunit 3的四种安装方式 第一种 通过NuGet进行Full Nunit安装 第二种 通过NuGet进行轻量级 NunitLite 安装 第三种 通过Zip 压缩包下载安 ...

  7. nginx做为web容器部署静态资源以及做负载均衡反向代理实现

    需求:  此时前台开发完成打包生成静态资源文件,要做到以下方面: 使用nginx部署静态资源,同时nginx要实现端口转发,隐藏真实后台地址,同时后台需要做一个负载均衡. localhost:7001 ...

  8. 完全卸载RabbitMQ和Erlang

    要从计算机中完全卸载RabbitMQ和Erlang,请执行以下操作:(1)打开Windows控制面板,双击“程序和功能”. (2)在当前安装的程序列表中,右键单击RabbitMQ Server,然后单 ...

  9. windows服务与log4net应用

    有时候我们需要用到window服务来执行定时任务,然后配合log4net记录程序运行情况,这里简单记录下配置的整个过程以及注意要点: 一.添加windows服务 1.设计页面,右键添加安装程序

  10. css选择器找亲戚

    1.first-child first-child表示选择列表中的第一个标签.代码如下: li:first-child{background:#090} 上面的意思是,li 列表中的 第一个li模块的 ...