Numpy。在一个方程中找到所需的值,使误差最小化。

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

题目不清楚,希望在这里能更好的解释。

我有以下两个数组。epsp 具有相同的维度。

ep = [0.00000000e+00, 4.29973987e-05, 1.77977219e-04, 3.08940223e-04, 4.44883670e-04, 5.84806153e-04, 7.28705999e-04, 8.77580573e-04, 1.03342551e-03, 1.19623754e-03, 1.36301748e-03, 1.53675860e-03, 1.72145026e-03. 1.91608833e-03]

sp = [336.17311024, 366.02001118, 427.4927458,  471.53403676, 503.53359236, 527.23879184, 544.98822976, 558.34153011, 568.29913137, 575.9109472, 581.00400657, 584.97104685, 587.14272582, 587.92832846]

我需要得到一个数组 sw 按以下公式计算。

sw = (np.amax(sp)/(ei**(ei+c))) * ((ep+ei)**(ei+c))

其中 c 的最大值。ep 阵列和 ei 必须是最小化以下其他方程之和的值(在对sp和sw的每个值进行迭代后)。

f = (sp - sw)**2

有什么办法吗?

谢谢!

python numpy least-squares equation-solving scipy-optimize-minimize
1个回答
0
投票

不如这样吧?你已经描述了你的错误函数,所以可以使用 scipy.optimize.minimize 以减少它。

from scipy.optimize import minimize
import numpy as np
from matplotlib import pyplot as plt

ep = np.array([0.0000000e+00, 4.29973987e-05, 1.77977219e-04, 3.08940223e-04, 4.44883670e-04, 5.84806153e-04, 7.28705999e-04, 8.77580573e-04, 1.03342551e-03, 1.19623754e-03, 1.36301748e-03, 1.53675860e-03, 1.72145026e-03, 1.91608833e-03])

sp = np.array([336.17311024, 366.02001118, 427.4927458, 471.53403676, 503.53359236, 527.23879184, 544.98822976, 558.34153011, 568.29913137, 575.9109472, 581.00400657, 584.97104685, 587.14272582, 587.92832846])

def err(ei, c):
    sw = (sp/ei**(ei+c))*((ep+ei)**(ei+c))

    return np.sum((sp-sw)**2)

# do minimization
c = max(ep)
guess = [1.2]
res = minimize(err, guess, args=(c,), method='Nelder-Mead')
# get miniization result
ei, = res.x

# plot results
fig, ax = plt.subplots(ncols=2)
ax[0].plot(sp)
ax[0].plot((sp/ei**(ei+c))*((ep+ei)**(ei+c)))
ax[0].set_title('Function evaluation')

ax[1].plot((sp/ei**(ei+c))*((ep+ei)**(ei+c)) - sp, label='Minimized')
ei, = guess
ax[1].plot((sp/ei**(ei+c))*((ep+ei)**(ei+c)) - sp, label='Initial Guess')
ax[1].set_title('Difference')
ax[1].legend()

minimized fn

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