基于Python fminunc 的替代方法


Posted in Python onFebruary 29, 2020

最近闲着没事,想把coursera上斯坦福ML课程里面的练习,用Python来实现一下,一是加深ML的基础,二是熟悉一下numpy,matplotlib,scipy这些库。

在EX2中,优化theta使用了matlab里面的fminunc函数,不知道Python里面如何实现。搜索之后,发现stackflow上有人提到用scipy库里面的minimize函数来替代。我尝试直接调用我的costfunction和grad,程序报错,提示(3,)和(100,1)dim维度不等,gradient vector不对之类的,试了N多次后,终于发现问题何在。。

首先来看看使用np.info(minimize)查看函数的介绍,传入的参数有:

fun : callable
 The objective function to be minimized.
 
  ``fun(x, *args) -> float``
 
 where x is an 1-D array with shape (n,) and `args`
 is a tuple of the fixed parameters needed to completely
 specify the function.
x0 : ndarray, shape (n,)
 Initial guess. Array of real elements of size (n,),
 where 'n' is the number of independent variables.
args : tuple, optional
 Extra arguments passed to the objective function and its
 derivatives (`fun`, `jac` and `hess` functions).
method : str or callable, optional
 Type of solver. Should be one of
 
  - 'Nelder-Mead' :ref:`(see here) <optimize.minimize-neldermead>`
  - 'Powell'  :ref:`(see here) <optimize.minimize-powell>`
  - 'CG'   :ref:`(see here) <optimize.minimize-cg>`
  - 'BFGS'  :ref:`(see here) <optimize.minimize-bfgs>`
  - 'Newton-CG' :ref:`(see here) <optimize.minimize-newtoncg>`
  - 'L-BFGS-B' :ref:`(see here) <optimize.minimize-lbfgsb>`
  - 'TNC'   :ref:`(see here) <optimize.minimize-tnc>`
  - 'COBYLA'  :ref:`(see here) <optimize.minimize-cobyla>`
  - 'SLSQP'  :ref:`(see here) <optimize.minimize-slsqp>`
  - 'trust-constr':ref:`(see here) <optimize.minimize-trustconstr>`
  - 'dogleg'  :ref:`(see here) <optimize.minimize-dogleg>`
  - 'trust-ncg' :ref:`(see here) <optimize.minimize-trustncg>`
  - 'trust-exact' :ref:`(see here) <optimize.minimize-trustexact>`
  - 'trust-krylov' :ref:`(see here) <optimize.minimize-trustkrylov>`
  - custom - a callable object (added in version 0.14.0),
   see below for description.
 
 If not given, chosen to be one of ``BFGS``, ``L-BFGS-B``, ``SLSQP``,
 depending if the problem has constraints or bounds.
jac : {callable, '2-point', '3-point', 'cs', bool}, optional
 Method for computing the gradient vector. Only for CG, BFGS,
 Newton-CG, L-BFGS-B, TNC, SLSQP, dogleg, trust-ncg, trust-krylov,
 trust-exact and trust-constr. If it is a callable, it should be a
 function that returns the gradient vector:
 
  ``jac(x, *args) -> array_like, shape (n,)``
 
 where x is an array with shape (n,) and `args` is a tuple with
 the fixed parameters. Alternatively, the keywords
 {'2-point', '3-point', 'cs'} select a finite
 difference scheme for numerical estimation of the gradient. Options
 '3-point' and 'cs' are available only to 'trust-constr'.
 If `jac` is a Boolean and is True, `fun` is assumed to return the
 gradient along with the objective function. If False, the gradient
 will be estimated using '2-point' finite difference estimation.

需要注意的是fun关键词参数里面的函数,需要把优化的theta放在第一个位置,X,y,放到后面。并且,theta在传入的时候一定要是一个一维shape(n,)的数组,不然会出错。

然后jac是梯度,这里的有两个地方要注意,第一个是传入的theta依然要是一个一维shape(n,),第二个是返回的梯度也要是一个一维shape(n,)的数组。

总之,关键在于传入的theta一定要是一个1D shape(n,)的,不然就不行。我之前为了方便已经把theta塑造成了一个(n,1)的列向量,导致使用minimize时会报错。所以,学会用help看说明可谓是相当重要啊~

import numpy as np
import pandas as pd
import scipy.optimize as op
 
def LoadData(filename):
 data=pd.read_csv(filename,header=None)
 data=np.array(data)
 return data
 
def ReshapeData(data):
 m=np.size(data,0)
 X=data[:,0:2]
 Y=data[:,2]
 Y=Y.reshape((m,1))
 return X,Y
 
def InitData(X):
 m,n=X.shape
 initial_theta = np.zeros(n + 1)
 VecOnes = np.ones((m, 1))
 X = np.column_stack((VecOnes, X))
 return X,initial_theta
 
def sigmoid(x):
 z=1/(1+np.exp(-x))
 return z
 
def costFunction(theta,X,Y):
 m=X.shape[0]
 J = (-np.dot(Y.T, np.log(sigmoid(X.dot(theta)))) - \
   np.dot((1 - Y).T, np.log(1 - sigmoid(X.dot(theta))))) / m
 return J
 
def gradient(theta,X,Y):
 m,n=X.shape
 theta=theta.reshape((n,1))
 grad=np.dot(X.T,sigmoid(X.dot(theta))-Y)/m
 return grad.flatten()
 
if __name__=='__main__':
 data = LoadData('ex2data1csv.csv')
 X, Y = ReshapeData(data)
 X, initial_theta = InitData(X)
 result = op.minimize(fun=costFunction, x0=initial_theta, args=(X, Y), method='TNC', jac=gradient)
 print(result)

最后结果如下,符合MATLAB里面用fminunc优化的结果(fminunc:cost:0.203,theta:-25.161,0.206,0.201)

fun: array([0.2034977])
  jac: array([8.95038682e-09, 8.16149951e-08, 4.74505693e-07])
 message: 'Local minimum reached (|pg| ~= 0)'
 nfev: 36
  nit: 17
 status: 0
 success: True
  x: array([-25.16131858, 0.20623159, 0.20147149])

此外,由于知道cost在0.203左右,所以我用最笨的梯度下降试了一下,由于后面实在是太慢了,所以设置while J>0.21,循环了大概13W次。。可见,使用集成好的优化算法是多么重要。。。还有,在以前的理解中,如果一个学习速率不合适,J会一直发散,但是昨天的实验发现,有的速率开始会发散,后面还是会收敛。

以上这篇基于Python fminunc 的替代方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
在Django中创建动态视图的教程
Jul 15 Python
Python三级目录展示的实现方法
Sep 28 Python
python实现简单遗传算法
Mar 19 Python
python删除某个字符
Mar 19 Python
python实现海螺图片的方法示例
May 12 Python
python日志模块logbook使用方法
Sep 19 Python
Python 实现自动导入缺失的库
Oct 29 Python
Django框架之中间件MiddleWare的实现
Dec 30 Python
Python-numpy实现灰度图像的分块和合并方式
Jan 09 Python
简单了解python filter、map、reduce的区别
Jan 14 Python
python标准库os库的函数介绍
Feb 12 Python
python如何利用paramiko执行服务器命令
Nov 07 Python
浅谈SciPy中的optimize.minimize实现受限优化问题
Feb 29 #Python
使用python求解二次规划的问题
Feb 29 #Python
Python龙贝格法求积分实例
Feb 29 #Python
python计算导数并绘图的实例
Feb 29 #Python
细数nn.BCELoss与nn.CrossEntropyLoss的区别
Feb 29 #Python
Pytorch对Himmelblau函数的优化详解
Feb 29 #Python
Pytorch中的自动求梯度机制和Variable类实例
Feb 29 #Python
You might like
ajax实现无刷新分页(php)
2010/07/18 PHP
PHP的关于变量和日期处理的一些面试题目整理
2015/08/10 PHP
以实例全面讲解PHP中多进程编程的相关函数的使用
2015/08/18 PHP
jquery+ajax+C#实现无刷新操作数据库数据的简单实例
2014/02/08 Javascript
jQuery中attr()方法用法实例
2015/01/05 Javascript
JavaScript获得页面base标签中url的方法
2015/04/03 Javascript
学习JavaScript设计模式之观察者模式
2020/04/22 Javascript
EasyUI中在表单提交之前进行验证
2016/07/19 Javascript
js复制内容到剪贴板代码,js复制代码的简单实例
2016/10/27 Javascript
Angular2安装angular-cli
2017/05/21 Javascript
简单快速的实现js计算器功能
2017/08/17 Javascript
关于vue中的ajax请求和axios包问题
2018/04/19 Javascript
使用nodejs分离html文件里的js和css详解
2019/04/12 NodeJs
vue实现记事本功能
2019/06/26 Javascript
javascript实现动态时钟的启动和停止
2020/07/29 Javascript
vue data恢复初始化数据的实现方法
2019/10/31 Javascript
小程序选项卡以及swiper套用(跨页面)
2020/06/19 Javascript
[36:05]完美世界DOTA2联赛循环赛 Forest vs DM 第一场 11.06
2020/11/06 DOTA
Python 2.7.x 和 3.x 版本的重要区别小结
2014/11/28 Python
python中函数总结之装饰器闭包详解
2016/06/12 Python
深入理解Python3 内置函数大全
2017/11/23 Python
Python实现的圆形绘制(画圆)示例
2018/01/31 Python
Python 中Pickle库的使用详解
2018/02/24 Python
python微信公众号之关键词自动回复
2018/06/15 Python
pyqt 实现QlineEdit 输入密码显示成圆点的方法
2019/06/24 Python
Python使用微信接入图灵机器人过程解析
2019/11/04 Python
Python基于pillow库实现生成图片水印
2020/09/14 Python
整理HTML5中表单的常用属性及新属性
2016/02/19 HTML / CSS
亚洲独特体验旅游专家:eOasia
2018/08/15 全球购物
皇家阿尔伯特瓷器美国官网:Royal Albert美国
2020/02/16 全球购物
机电一体化专业应届本科生求职信
2013/09/27 职场文书
物理系毕业生自荐书
2014/06/13 职场文书
乡党政领导班子群众路线教育实践活动个人对照检查材料
2014/09/20 职场文书
逃课打麻将检讨书
2014/10/05 职场文书
信息合作协议书
2014/10/09 职场文书
社区公民道德宣传日活动总结
2015/03/23 职场文书