scipy-0.18.1的“scipy.optimize.minimize”中是否有错误?

时间:2016-12-13 12:23:16

标签: python numpy optimization scipy

我正在尝试使用scipy.optimize.minimize中特别使用的dogleg方法来解决某个函数。为了更好地理解它,我正在调整帮助页面底部的示例并使用狗腿洞法:

from scipy.optimize import minimize

def fun(x):
    return (x[0] - 1)**2 + (x[1] - 2.5)**2

# solver
res = minimize(fun, (2, 0), method='dogleg', jac=False) # or jac=None, it doesn't matter

print(res)

我收到错误ValueError: Jacobian is required for dogleg minimization.

这类似于较旧的问题:"Jacobian is required for Newton-CG method" when doing a approximation to a Jacobian not being used when jac=False?似乎无法解决。

所以我的问题是:这个minimize中确实存在错误,或者我没有正确使用它?

1 个答案:

答案 0 :(得分:2)

您必须传递雅可比函数才能使用@IBOutlet var scrollView: UIScrollView! @IBOutlet var contentView: UIView! var textFieldActive:UITextField! override func viewDidLoad() { super.viewDidLoad() //Keyboard notification NotificationCenter.default.addObserver(self,selector: #selector(keyboardWasShown),name:NSNotification.Name.UIKeyboardDidShow, object: nil) NotificationCenter.default.addObserver(self,selector: #selector(keyboardWillHide),name:NSNotification.Name.UIKeyboardWillHide, object: nil) // Do any additional setup after loading the view. } func textFieldDidBeginEditing(_ textField: UITextField){ textFieldActive = textField } // MARK: - Keyboard notification Method func keyboardWasShown(notification: NSNotification) { let userInfo = notification.userInfo let keyboardSize = (userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue let contentInset = UIEdgeInsetsMake(0.0, 0.0, (keyboardSize?.height)!+100, 0.0) self.scrollViewGroupMakeTakers.contentInset = contentInset self.scrollViewGroupMakeTakers.scrollIndicatorInsets = contentInset // Step 3: Scroll the target text field into view. var aRect: CGRect = self.contentViewMakeTakers.frame; aRect.size.height -= (keyboardSize?.height)!+100 if (!aRect.contains(textFieldActive!.frame.origin)) { let scrollPoint: CGPoint = CGPoint(x: 0.0, y: textFieldActive!.frame.origin.y - (keyboardSize!.height-150)); self.scrollViewGroupMakeTakers.setContentOffset(scrollPoint, animated: true) } } func keyboardWillHide(notification: NSNotification) { let contentInsets : UIEdgeInsets = UIEdgeInsets.zero scrollViewGroupMakeTakers.contentInset = contentInsets; scrollViewGroupMakeTakers.scrollIndicatorInsets = contentInsets; } 方法,因为它是基于梯度的优化方法。如果您查看scipy.optimize.minimizedogleg参数,则说明

  

jac bool或callable,optional
  雅可比(梯度)的目标函数。仅适用于CG,BFGS,Newton-CG,L-BFGS-B,TNC,SLSQP,dogleg,trust-ncg。如果jac是布尔值并且为jac,则假定True将返回梯度以及目标函数。如果fun,将以数字方式估算渐变。 False也可以是一个可调用的,返回目标的梯度。在这种情况下,它必须接受与jac相同的参数。

然后,如果你俯视页面底部的注释:

  

方法狗腿洞使用狗腿信任区域算法进行无约束最小化。 此算法需要渐变和Hessian ;此外,Hessian必须是肯定的。

一些基于梯度的方法不需要显式雅可比(和/或Hessian),因为它们将使用差分方法来近似它们。但是fun 需要您明确传递此类函数。