python - Python - 更复杂函数的曲线拟合
解决方案
这是您可能会发现有用的一种方法。这使用lmfit
(http://lmfit.github.io/lmfit-py/),它提供了一种高级的曲线拟合方法:
import numpy as np
import matplotlib.pyplot as plt
from lmfit import Model
def decay_cosine(t, amp, beta, omega, phi):
"""model data as decaying cosine wave"""
return amp * np.exp(-beta*t)* np.cos(omega*t + phi)
# create fake data to be fitted
t = np.linspace(0, 5, 101)
y = decay_cosine(t, 1.4, 0.9, 7.2, 0.23) + np.random.normal(size=len(t), scale=0.05)
# build model from decay_cosine
mod = Model(decay_cosine)
# create parameters, giving initial values
params = mod.make_params(amp=2.0, beta=0.5, omega=5, phi=0)
# you can place bounds on parameters:
params['phi'].max = np.pi/2
params['phi'].min = -np.pi/2
params['amp'].min = 0
# fit data to model
result = mod.fit(y, params, t=t)
# print out fit results
print(result.fit_report())
# plot data with best fit
plt.plot(t, y, 'bo', label='data')
plt.plot(t, result.best_fit, 'r')
plt.show()
这将打印出这样的报告:
[[Model]]
Model(decay_cosine)
[[Fit Statistics]]
# fitting method = leastsq
# function evals = 46
# data points = 101
# variables = 4
chi-square = 0.25540159
reduced chi-square = 0.00263301
Akaike info crit = -595.983903
Bayesian info crit = -585.523421
[[Variables]]
amp: 1.38812335 +/- 0.03034640 (2.19%) (init = 2)
beta: 0.90760648 +/- 0.02820705 (3.11%) (init = 0.5)
omega: 7.16579292 +/- 0.02891827 (0.40%) (init = 5)
phi: 0.26249321 +/- 0.02225816 (8.48%) (init = 0)
[[Correlations]] (unreported correlations are < 0.100)
C(omega, phi) = -0.713
C(amp, beta) = 0.695
C(amp, phi) = 0.253
C(amp, omega) = -0.183
C(beta, phi) = 0.178
C(beta, omega) = -0.128
并产生这样的情节:
推荐阅读
- javascript - 如何避免找不到模块
- javascript - 如何使用 JSON Query 将数组转换为字符串
- video - 想通过视频的下载链接在我的网站中嵌入视频
- swagger - Fastify swagger doc 在默认标签下的 swagger doc 中生成一个 OPTIONS API
- angular - 刷新令牌附加后令牌拦截不起作用
- python - 如何在另一个文件中使用全局变量
- php - Laravel 5.8:如何在多对多关系中显示数据透视表的列信息
- python - 如何使用 Python 更新 Elastic Search 并理解架构?
- python - 使用beautifulsoup 库的网页抓取代码没有得到预期的结果
- json - 如果方法 validateOpco 返回 null 地图对象,我的 Rest Controller 类必须显示 Resource Not Found Exception