最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

基于Python fminunc 的替代方法

 更新時間:2020年02月29日 15:17:08   作者:csdn_inside  
今天小編就為大家分享一篇基于Python fminunc 的替代方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

最近閑著沒事,想把coursera上斯坦福ML課程里面的練習,用Python來實現(xiàn)一下,一是加深ML的基礎,二是熟悉一下numpy,matplotlib,scipy這些庫。

在EX2中,優(yōu)化theta使用了matlab里面的fminunc函數(shù),不知道Python里面如何實現(xiàn)。搜索之后,發(fā)現(xiàn)stackflow上有人提到用scipy庫里面的minimize函數(shù)來替代。我嘗試直接調用我的costfunction和grad,程序報錯,提示(3,)和(100,1)dim維度不等,gradient vector不對之類的,試了N多次后,終于發(fā)現(xiàn)問題何在。。

首先來看看使用np.info(minimize)查看函數(shù)的介紹,傳入的參數(shù)有:

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關鍵詞參數(shù)里面的函數(shù),需要把優(yōu)化的theta放在第一個位置,X,y,放到后面。并且,theta在傳入的時候一定要是一個一維shape(n,)的數(shù)組,不然會出錯。

然后jac是梯度,這里的有兩個地方要注意,第一個是傳入的theta依然要是一個一維shape(n,),第二個是返回的梯度也要是一個一維shape(n,)的數(shù)組。

總之,關鍵在于傳入的theta一定要是一個1D shape(n,)的,不然就不行。我之前為了方便已經(jīng)把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優(yōu)化的結果(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,循環(huán)了大概13W次。??梢姡褂眉珊玫膬?yōu)化算法是多么重要。。。還有,在以前的理解中,如果一個學習速率不合適,J會一直發(fā)散,但是昨天的實驗發(fā)現(xiàn),有的速率開始會發(fā)散,后面還是會收斂。

以上這篇基于Python fminunc 的替代方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

  • selenium+python自動化測試之多窗口切換

    selenium+python自動化測試之多窗口切換

    這篇文章主要介紹了selenium+python自動化測試之多窗口切換,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2019-01-01
  • Python qrcode 生成一個二維碼的實例詳解

    Python qrcode 生成一個二維碼的實例詳解

    在本篇文章里小編給大家整理的是關于Python qrcode 生成一個二維碼的實例內容,需要的朋友們可以學習參考下。
    2020-02-02
  • 編寫Python小程序來統(tǒng)計測試腳本的關鍵字

    編寫Python小程序來統(tǒng)計測試腳本的關鍵字

    這篇文章主要介紹了編寫Python小程序來統(tǒng)計測試腳本的關鍵字的方法,文中的實例不僅可以統(tǒng)計關鍵字數(shù)量,還可以按主關鍵字來歸類,需要的朋友可以參考下
    2016-03-03
  • 解決Pyinstaller打包軟件失敗的一個坑

    解決Pyinstaller打包軟件失敗的一個坑

    這篇文章主要介紹了解決Pyinstaller打包軟件失敗的一個坑,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-03-03
  • Python字符串逆序的實現(xiàn)方法【一題多解】

    Python字符串逆序的實現(xiàn)方法【一題多解】

    今天小編就為大家分享一篇關于Python字符串逆序的實現(xiàn)方法【一題多解】,小編覺得內容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2019-02-02
  • Python字符串str超詳細詳解(適合新手!)

    Python字符串str超詳細詳解(適合新手!)

    str函數(shù)是Python的內置函數(shù),它將參數(shù)轉換成字符串類型,即人適合閱讀的形式,下面這篇文章主要給大家介紹了關于Python字符串str超詳細詳解的相關資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下
    2022-11-11
  • python利用socket實現(xiàn)客戶端和服務端之間進行通信

    python利用socket實現(xiàn)客戶端和服務端之間進行通信

    這篇文章主要介紹了python實現(xiàn)客戶端和服務端之間進行通信,文章通過python利用socket展開詳情介紹,具有一定的參考價值,需要的小伙伴可以參考一下
    2022-05-05
  • Python提升循環(huán)速度的高效方法小姐

    Python提升循環(huán)速度的高效方法小姐

    Python編程中,循環(huán)是一種常見的操作,但是如果處理大規(guī)模數(shù)據(jù)或者需要頻繁執(zhí)行的循環(huán),往往會導致程序運行速度變慢,下面我們就來看看有什么辦法可以提升循環(huán)速度吧
    2024-03-03
  • Python JWT 介紹和使用詳解

    Python JWT 介紹和使用詳解

    這篇文章主要介紹了Python JWT 介紹和使用詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2021-05-05
  • python虛擬機之描述器實現(xiàn)原理與源碼分析

    python虛擬機之描述器實現(xiàn)原理與源碼分析

    在本篇文章當中主要給大家介紹描述器背后的實現(xiàn)原理,通過分析?cpython對應的源代碼了解與描述器相關的字節(jié)碼的指令,我們就可以真正了解到描述器背后的原理,需要的朋友可以參考下
    2023-05-05

最新評論

壶关县| 永康市| 乡宁县| 东丽区| 博湖县| 连城县| 奇台县| 吉水县| 深州市| 祁阳县| 宜兰市| 香港| 定远县| 康保县| 闽侯县| 哈巴河县| 兰州市| 上饶市| 喀喇| 辰溪县| 广安市| 天镇县| 苏尼特左旗| 银川市| 瑞安市| 贵定县| 和田市| 且末县| 神木县| 宁晋县| 化德县| 高雄县| 海城市| 娄烦县| 高雄市| 巨鹿县| 柞水县| 德江县| 合水县| 专栏| 黄大仙区|