【发布时间】:2020-08-30 14:36:32
【问题描述】:
我在 python 中的优化逻辑有问题。我有创建优化功能。逻辑是我需要更改 2 个参数,它们是 monthly_cci 和 rho。 monthly_cci 是包含 40 个值的随机 numpy 数组,rho 是一个必须为正的单个值(也是随机的)。
我需要这两个参数来适应公式来找到fitted_upper。我循环了 40 个循环以获得 40 个 fitted_upper 组合为一个名为 monthly_fitted 的数组。然后我用另一个公式转换monthly_fitted 得到fitted_matrix。我将fitted_matrix定义错误函数,即error_matrix。
我需要通过更改monthly_cci 和rho 来尽可能降低error_matrix 的方差。我试图编写如下代码,但它不起作用。对这个案例有什么建议吗?
谢谢!
from scipy.optimize import minimize
def cci(monthly_cci, rho):
monthly_cci = np.random.randn(40)
rho = np.random.rand(1)
monthly_fitted = []
for i in range(0, len(monthly_cci)):
fitted_upper = (upper_array - (np.sqrt(rho) * monthly_cci[i])) / np.sqrt(1 - rho)
monthly_fitted.append(fitted_upper)
monthly_fitted = np.vstack(monthly_fitted)
#Fitted matrix
m_0 = 1 - norm.cdf(monthly_fitted[0:, 1])
m_1 = norm.cdf(monthly_fitted[0:, 1]) - norm.cdf(monthly_fitted[0:, 2])
m_2 = norm.cdf(monthly_fitted[0:, 2]) - norm.cdf(monthly_fitted[0:, 3])
m_3 = norm.cdf(monthly_fitted[0:, 3]) - norm.cdf(monthly_fitted[0:, 4])
m_4 = norm.cdf(monthly_fitted[0:, 4])
fitted_matrix = np.stack((m_0, m_1, m_2, m_3, m_4), axis = 1)
fitted_matrix = fitted_matrix.reshape(cci['Monthkey'].max(), -1)
error_matrix = n_array * ((monthly_array - fitted_matrix) ** 2) / (fitted_matrix * (1 - fitted_matrix))
return np.var(error_matrix)
res = minimize(cci, x0 = [monthly_cci, rho], method='Nelder-Mead')
我收到错误消息
ValueError: setting an array element with a sequence.
【问题讨论】:
-
@norok2 我该怎么做,因为每个数组都需要另一个公式来转换
-
如果您能够提供 MWE,我们可能会提供更多帮助:*.com/help/minimal-reproducible-example
标签: python python-3.x optimization scipy solver