SciPy的最小化不是迭代

2024-09-28 17:05:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图最小化一个基本上如下所示的函数:

enter image description here

实际上它有两个自变量,但由于x1+x2=1,它们并不是真正独立的。你知道吗

现在是目标函数

def calculatePVar(w,covM):
    w = np.matrix(w)
    return (w*covM*w.T) [0,0]

wnere w是每个资产的权重列表,covM是由pandas的.cov()返回的协方差矩阵

在这里调用优化函数:

w0 = []
for sec in portList:
    w0.append(1/len(portList))

bnds = tuple((0,1)  for x in w0)
cons = ({'type': 'eq', 'fun': lambda x:  np.sum(x)-1.0})
res= minimize(calculatePVar, w0, args=nCov, method='SLSQP',constraints=cons, bounds=bnds)
weights = res.x

现在函数有一个明确的最小值,但minimize只会吐出初始值作为结果,它确实表示“优化已成功终止”。有什么建议吗?你知道吗

优化结果:

enter image description here

图片作为链接,因为我不符合要求!你知道吗


Tags: 函数in目标fornpresx1x2
1条回答
网友
1楼 · 发布于 2024-09-28 17:05:16

你的代码有一些混乱的变量,所以我只是清除了这些,简化了一些行,现在最小化工作正常。然而,现在的问题是:结果是否正确?它们有意义吗?这是你的判断:

import numpy as np 
from scipy.optimize import minimize

def f(w, cov_matrix):
    return (np.matrix(w) * cov_matrix * np.matrix(w).T)[0,0]

cov_matrix = np.array([[1, 2, 3],
                       [4, 5, 6],
                       [7, 8, 9]])
p    = [1, 2, 3]
w0   = [(1/len(p))  for e in p]
bnds = tuple((0,1)  for e in w0)
cons = ({'type': 'eq', 'fun': lambda w:  np.sum(w)-1.0})

res  = minimize(f, w0, 
                args        = cov_matrix, 
                method      = 'SLSQP',
                constraints = cons, 
                bounds      = bnds)
weights = res.x
print(res)
print(weights)

更新:

根据你的评论,在我看来-也许-你的函数有多个极小值,这就是scipy.optimize.minimize被困在那里的原因。我建议scipy.optimize.basinhopping作为一种替代方法,这将使用一个随机步骤来遍历函数的大多数极小值,而且它仍然很快。代码如下:

import numpy as np 
from scipy.optimize import basinhopping


class MyBounds(object):
     def __init__(self, xmax=[1,1], xmin=[0,0] ):
         self.xmax = np.array(xmax)
         self.xmin = np.array(xmin)

     def __call__(self, **kwargs):
         x = kwargs["x_new"]
         tmax = bool(np.all(x <= self.xmax))
         tmin = bool(np.all(x >= self.xmin))
         return tmax and tmin

def f(w):
    global cov_matrix
    return (np.matrix(w) * cov_matrix * np.matrix(w).T)[0,0]

cov_matrix = np.array([[0.000244181, 0.000198035],
                       [0.000198035, 0.000545958]])

p    = ['ABEV3', 'BBDC4']
w0   = [(1/len(p))  for e in p]
bnds = tuple((0,1)  for e in w0)
cons = ({'type': 'eq', 'fun': lambda w:  np.sum(w)-1.0})

bnds = MyBounds()
minimizer_kwargs = {"method":"SLSQP", "constraints": cons}
res  = basinhopping(f, w0, 
                    accept_test  = bnds)
weights = res.x
print(res)
print("weights: ", weights)

输出:

                        fun: 2.3907094432990195e-09
 lowest_optimization_result:       fun: 2.3907094432990195e-09
 hess_inv: array([[ 2699.43934183, -1184.79396719],
       [-1184.79396719,  1210.50404805]])
      jac: array([1.34548553e-06, 2.00122166e-06])
  message: 'Optimization terminated successfully.'
     nfev: 60
      nit: 6
     njev: 15
   status: 0
  success: True
        x: array([0.00179748, 0.00118076])
                    message: ['requested number of basinhopping iterations completed successfully']
      minimization_failures: 0
                       nfev: 6104
                        nit: 100
                       njev: 1526
                          x: array([0.00179748, 0.00118076])
weights:  [0.00179748 0.00118076]

相关问题 更多 >