1

我尝试解决乘以向量“因子”之和的因子 x。向量“因子”的总和应该是向量“基本”的总和。首先,我阅读了一个类似于以下 DataFrame 的 csv:

在此处输入图像描述

提前感谢您的帮助。

好吧,我也尝试过最小化和反弹。也许使用 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))

raise ValueError("目标函数必须返回一个标量")

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

4

1 回答 1

2

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

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
于 2019-06-16T20:46:06.157 回答