基于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 相关文章推荐
Python使用scrapy抓取网站sitemap信息的方法
Apr 08 Python
详细解析Python中__init__()方法的高级应用
May 11 Python
python 根据正则表达式提取指定的内容实例详解
Dec 04 Python
Python分布式进程中你会遇到的问题解析
May 28 Python
Python实现将字符串的首字母变为大写,其余都变为小写的方法
Jun 11 Python
python将字符串转换成json的方法小结
Jul 09 Python
django做form表单的数据验证过程详解
Jul 26 Python
python+selenium select下拉选择框定位处理方法
Aug 24 Python
python实现实时视频流播放代码实例
Jan 11 Python
tensorflow中tf.slice和tf.gather切片函数的使用
Jan 19 Python
python Socket网络编程实现C/S模式和P2P
Jun 22 Python
Django如何创作一个简单的最小程序
May 12 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
教你IIS6的PHP最佳配置方法
2006/09/05 PHP
用在PHP里的JS打印函数
2006/10/09 PHP
PHP中通过ADO调用Access数据库的方法测试不通过
2006/12/31 PHP
php+mysql实现数据库随机重排实例
2014/10/17 PHP
php自定义加密与解密程序实例
2014/12/31 PHP
CentOS下与Apache连接的PHP多版本共存方案实现详解
2015/12/19 PHP
php格式文件打开的四种方法
2018/02/24 PHP
基于ThinkPHP删除目录及目录文件函数
2020/10/28 PHP
js兼容的placeholder属性详解
2013/08/18 Javascript
对比分析AngularJS中的$http.post与jQuery.post的区别
2015/02/27 Javascript
利用Javascript实现BMI计算器
2016/08/16 Javascript
基于JavaScript实现前端文件的断点续传
2016/10/17 Javascript
从零学习node.js之express入门(六)
2017/02/25 Javascript
微信小程序 input表单与redio及下拉列表的使用实例
2017/09/20 Javascript
微信小程序使用input组件实现密码框功能【附源码下载】
2017/12/11 Javascript
Angular学习笔记之集成三方UI框架、控件的示例
2018/03/23 Javascript
解决Vue2.0中使用less给元素添加背景图片出现的问题
2018/09/03 Javascript
[48:41]VP vs VG Supermajor小组赛 B组胜者组决赛 BO3 第二场 6.2
2018/06/03 DOTA
[45:59]EG vs OG 2018国际邀请赛小组赛BO2 第二场 8.17
2018/08/18 DOTA
Python yield使用方法示例
2013/12/04 Python
python 实现分页显示从es中获取的数据方法
2018/12/26 Python
10招!看骨灰级Pythoner玩转Python的方法
2019/04/15 Python
python使用Paramiko模块实现远程文件拷贝
2019/04/30 Python
python输出电脑上所有的串口名的方法
2019/07/02 Python
Python虚拟环境的原理及使用详解
2019/07/02 Python
解决Python import docx出错DLL load failed的问题
2020/02/13 Python
利用Python实现Excel的文件间的数据匹配功能
2020/06/16 Python
HTML5中在title标题标签里设置小图标的方法
2020/06/23 HTML / CSS
草莓网英国官网:Strawberrynet UK
2017/02/12 全球购物
婚礼主持词开场白
2014/03/13 职场文书
百年校庆节目主持词
2014/03/27 职场文书
科级干部群众路线教育实践活动个人对照检查材料
2014/09/19 职场文书
2014年结对帮扶工作总结
2014/12/17 职场文书
捐助感谢信
2015/01/22 职场文书
对学校的意见和建议
2015/06/04 职场文书
MySQL如何使备份得数据保持一致
2022/05/02 MySQL