如何在Python中优化或最小化多个数组的函数?

问题描述 投票:0回答:1

我有多个数组,希望将其与下面给出的形式的指数函数匹配:

我在MWE中有五个数组,y1,y2,y3 ...,y5。现在,我想找到A,E,m和n的最优值,以使残差最小化。

下面给出的MWE对每个数组y1或y2或y3单独执行此操作;给我(A1,E1,m1,n1),(A2,E2,m2,n2),...(A5,E5,m5,n5)。如何对所有数组进行优化,以使对于A,E,m和n的特定值(即,A,E,m和n的相同值)给我带来的误差最小?]

MWE

from __future__ import division
import numpy as np
from scipy import optimize
import matplotlib.pyplot as plt
def f(params, y):
    A, E, m, n, = params
    residuals = y - (A * np.exp(E*x/1000) * (40 ** m) * (0.50 ** n))
    objective = (residuals**2).sum()
    return objective

x = np.array([1.170, 1.194, 1.223, 1.255, 1.282, 1.325, 1.358, 1.389, 1.435, 1.471])
y_1 = np.array([16.96, 18.45, 20.58, 21.62, 27.22, 33.98, 41.32, 55.64, 72.66, 95.68])
y_2 = np.array([22.74, 25.69, 34.54, 35.77, 40.88, 45.53, 60.12, 72.65, 91.54, 102.58])
y_3 = np.array([26.11, 21.99, 26.88, 31.63, 41.06, 45.47, 59.04, 60.11, 79.79, 97.79])
y_4 = np.array([33.73, 36.01, 35.12, 35.94, 47.02, 56.55, 63.94, 66.78, 96.06, 116.07])
y_5 = np.array([30.87, 33.09, 32.51, 41.72, 42.75, 54.52, 63.02, 78.15, 89.02, 102.54])

result = optimize.minimize(f, [45, 2000, -1.0, -0.5], y_1)
A1, E1, m1, n1 = result.x
y_predicted_1 = (A1 * np.exp(E1*x/1000) * (40 ** m1) * (0.50 ** n1))

result = optimize.minimize(f, [45, 2000, -1.0, -0.5], y_2)
A2, E2, m2, n2 = result.x
y_predicted_2 = (A2 * np.exp(E2*x/1000) * (40 ** m2) * (0.50 ** n2))

result = optimize.minimize(f, [45, 2000, -1.0, -0.5], y_3)
A3, E3, m3, n3 = result.x
y_predicted_3 = (A3 * np.exp(E3*x/1000) * (40 ** m3) * (0.50 ** n3))

result = optimize.minimize(f, [45, 2000, -1.0, -0.5], y_4)
A4, E4, m4, n4 = result.x
y_predicted_4 = (A4 * np.exp(E4*x/1000) * (40 ** m4) * (0.50 ** n4))

result = optimize.minimize(f, [45, 2000, -1.0, -0.5], y_5)
A5, E5, m5, n5 = result.x
y_predicted_5 = (A5 * np.exp(E5*x/1000) * (40 ** m5) * (0.50 ** n5))
python numpy optimization data-fitting scipy-optimize
1个回答
0
投票

您实际上快到了。只需使用多个数据作为参数(之所以起作用是因为您设计f的方式):

result = optimize.minimize(f, [45, 2000, -1., -.5], [y_1, y_2, y_3, y_4, y_5])
A_, E_, m_, n_ = result.x
y_predicted_all = (A_ * np.exp(E_*x/1000) * (40 ** m_) * (0.50 ** n_))

然后您将得到这些残差:

Residuals (overall): 
1: 1361.14349
2: 107.87036
3: 165.67150
4: 713.73400
5: 358.97836

Residuals (individual): 
1: 53.10579
2: 72.27874
3: 76.72340
4: 206.37223
5: 60.04984

比预期的稍差一些。然后其中一些非常漂亮,例如y_1,但是其他一些可能还不错。

enter image description hereenter image description here

© www.soinside.com 2019 - 2024. All rights reserved.