当我在下面的例子中使用Scipy minimize时,它找到了一个非最小的解决方案-有人能帮我修改一下这个来找到最小值吗?在
我有四个约束:1)guess数组的猜测值必须和为1,2)猜测值必须大于0,3)初始猜测数组中超过阈值的任何猜测值都必须设置为等于阈值并保持不变。
编辑:第四个约束-任何猜测都不能大于阈值。在
我上次没有使用约束。对于约束2,我使用了一个边界。对于约束3,在调用scipy的minimize方法之前,我在performminize方法中执行了该操作。在
from scipy.optimize import minimize
import numpy as np
from numpy import array
def objective(initialGuesses, threshold):
overThreshold = initialGuesses[np.where((threshold < initialGuesses[:]))]
underThreshold = initialGuesses[np.where((threshold >= initialGuesses[:]))]
overThreshold[:] = threshold
sumUnderThreshold = np.sum(underThreshold)
oppositeSumOverTreshold = 1 - np.sum(overThreshold)
transformedGuess = underThreshold / sumUnderThreshold * oppositeSumOverTreshold
thresholdedResults = np.concatenate((overThreshold, transformedGuess))
squaredError = np.square(thresholdedResults - initialGuesses) / initialGuesses
return np.sum(squaredError)
def performMinimizeSo(initialGuesses, threshold):
overThreshold = initialGuesses[np.where((threshold < initialGuesses[:]))]
overThreshold[:] = threshold
underThreshold = initialGuesses[np.where((threshold >= initialGuesses[:]))]
# Says one minus the sum of all variables minus the sum of weights over the threshold must be zero
cons = ({'type': 'eq', 'fun': lambda x: 1 - sum(x) - sum(overThreshold)})
minimum = minimize(objective, underThreshold, args=(threshold), method='SLSQP',
constraints=cons,
bounds=[(0, None) for i in range(len(underThreshold))],
)
allGuesses = np.append(overThreshold, minimum.x)
return allGuesses
def testCaseForSo():
initialGuesses = array([
[0.1],
[0.05],
[0.05],
[0.05],
[0.05],
[0.05],
[0.05],
[0.05],
[0.05],
[0.05],
[0.05],
[0.05],
[0.05],
[0.05],
[0.05],
[0.05],
[0.05],
[0.05],
[0.025],
[0.025]])
threshold = .09
output = (performMinimizeSo(initialGuesses, threshold))
print(output)
testCaseForSo()
excel发现,最小的答案是:
^{pr2}$Scipy minimize认为这是答案,虽然接近但不是正确的最小值:
^{3}$以下是运行后输出的属性压缩。最小化(正如您所见,scipy认为它找到了最小值,尽管我们知道它没有):
minimum.sucess == True
minimum.status == 0
minimum.message == 'Optimization terminated successfully'
目前没有回答
相关问题 更多 >
编程相关推荐