用科学的方法解决因素最小化

时间:2019-06-16 19:58:36

标签: python scipy scipy-optimize scipy-optimize-minimize

我试图解决乘以向量“因子”之和的因数x。向量'Factor'的总和应类似于向量'Basic'的总和。 首先,我读了一个csv,看起来像下面的DataFrame:

enter image description here

谢谢您的帮助。

好吧,我也尝试了最小化和反弹。也许使用scipy.optimize会更好?

import pandas as pd
from scipy.optimize import minimize, optimize
import numpy as np

path='/scipytest.csv'

dffunc=pd.read_csv(path,  decimal=',', delimiter=';') 

BaseSum=np.sum(dffunc['Basic'])
FacSum=np.sum(dffunc['Factor'])

def f(x, FacSum):
    return BaseSum-FacSum*x


con = {'type': 'ineq',
       'fun': lambda BaseSum,FacSum: BaseSum-FacSum,
       'args': (FacSum,)}

x=0

result = minimize(f,(x,FacSum), args=(FacSum,), method='SLSQP', constraints=con)

print(result.x)
print(f(result.x))

提高ValueError(“目标函数必须返回标量”)

ValueError:目标函数必须返回标量

1 个答案:

答案 0 :(得分:1)

我认为您不一定需要scipy.optimize.minimize。由于您要最小化标量,因此可以使用scipy.optimize.minimize_scalardocs)。可以像下面这样完成:

from scipy.optimize import minimize_scalar
import numpy as np


# define vecs
basic_vec  = np.array([123, 342, 235, 123,  56, 345, 234, 123, 345,  54, 234]).reshape(11, 1)
factor_vec = np.array([234, 345, 453, 345, 456, 457,  23,  45,  56, 567,   5]).reshape(11, 1)
# define sums
BaseSum    = np.sum(basic_vec)
FacSum     = np.sum(factor_vec)
# define 
f      = lambda x, FacSum: np.abs(BaseSum - FacSum * x)
result = minimize_scalar(f, args   = (FacSum,), bounds = (0, FacSum), method = 'bounded')
# prints
print("x                    = ", result.x)
print("BaseSum - FacSum * x = ", f(result.x, FacSum))

输出:

x                    =  0.741461642947231
BaseSum - FacSum * x =  0.004465840431748802

此外,我什至不知道为什么当您只需做以下事情时,为什么甚至需要使用最小化:

x = BaseSum/FacSum