[英]Minimize function with Scipy minimize
嘗試使用Scipy最小化獲得Std_Diff目標函數最小的d值(整數)。
我的代碼:
def Std_Diff(d):
return std(diff(df['BN'].values,d));
from scipy.optimize import minimize
b=(3,)
res = minimize(Std_Diff,(1,), method='SLSQP', bounds = b)
The **df['BN'].values** are
Out[72]:
array([ 2, 2, 2, 2, 3, 2, 7, 5, 7, 11, 8, 2, 11, 7, 15, 8, 7,
12, 21, 19, 32, 35, 40, 35, 21, 19, 25, 20, 40, 80, 99], dtype=int64)
錯誤是
IndexError:數組的索引太多了
如果我不使用bounds
:
res = minimize(Std_Diff,(1,), method='SLSQP')
我收到另一個錯誤:
> in _minimize_slsqp(func, x0, args, jac, bounds, constraints, maxiter,
> ftol, iprint, disp, eps, callback, **unknown_options)
> 368 fx = float(np.asarray(func(x)))
> 369 except:
> --> 370 raise ValueError("Objective function must return a scalar")
> 371 # Compute the constraints
> 372 if cons['eq']: ValueError: Objective function must return a scalar.
(我一開始就磕磕絆絆,但我會離開這里,這樣你就可以得到一些如何調試的想法。)
你用以下方法調用minimize
:
Std_Diff,(1,)
這是初始值是標量(或1個數字)。 minimize
從中獲取線索並將搜索變量設置為相同。 這就是d
把它傳遞給你的函數, Std_Diff
。 但它也期望該函數也返回單個值。 換句話說,最小化標量值的標量函數。
所以std(diff(df['BN'].values,1))
應該返回一個標量。 顯然它沒有。
好的,用假想的values
進行測試
In [115]: bf
Out[115]:
array([ 2, 2, 2, 2, 3, 2, 7, 5, 7, 11, 8, 2, 11, 7, 15, 8, 7,
12, 21, 19, 32, 35, 40, 35, 21, 19, 25, 20, 40, 80, 99], dtype=int64)
In [116]: np.std(np.diff(bf,1))
Out[116]: 9.9219733700285424
所以我的第一個猜測錯了。
仔細查看錯誤堆棧,我發現錯誤發生在您的函數中,而不是之后。 使用d
看起來像是一個問題。
/usr/local/lib/python3.5/dist-packages/numpy/lib/function_base.py in diff(a, n, axis)
1913 raise ValueError(
-> 1914 "order must be non-negative but got " + repr(n))
1915 a = asanyarray(a)
ValueError: order must be non-negative but got array([-64259548.28233695])
在無界的情況下,搜索變量可以為負(非常如此),在np.diff
引發錯誤。
(您顯示的錯誤來自During handling of the above exception, another exception occurred:
。這不是主要錯誤,而是次要錯誤。)
指定邊界時的問題是規范不完整。 它需要每個變量的(最小,最大)元組。 這樣可行:
In [147]: minimize(Std_Diff,1, method='SLSQP', bounds=((3,None),))
...
Out[147]:
fun: 9.921973370028542
jac: array([ 64259549.28233695])
message: 'Positive directional derivative for linesearch'
nfev: 3
nit: 5
njev: 1
status: 8
success: False
x: array([ 1.])
變量的界限(僅適用於L-BFGS-B,TNC和SLSQP)。
(min, max)
對x
每個元素的對,定義該參數的邊界。 當在該方向上沒有約束時,使用None作為min
或max
之一。
查看錯誤行:
--> 341 bnderr = bnds[:, 0] > bnds[:, 1]
它希望bnds
是一個2列的2列數組。 例如:
In [153]: np.array(((3,10),))
Out[153]: array([[ 3, 10]])
In [154]: np.array((3,))
Out[154]: array([3])
我還修改了函數,以更清楚地了解其值如何變化
def Std_Diff(d):
print(d)
r = np.std(np.diff(bf,d))
print(r)
return r
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.