【发布时间】:2021-09-25 12:02:10
【问题描述】:
我制作了一个随机图,并尝试使用 SciPy curve_fit 将最佳曲线拟合到绘图中,但它失败了。
首先,我生成了一个随机指数衰减图,其中A, w, T2是使用numpy随机生成的:
def expDec(t, A, w, T2):
return A * np.cos(w * t) * (2.718**(-t / T2))
现在我让 SciPy 猜出最佳拟合曲线:
t = x['Input'].values
hr = x['Output'].values
c, cov = curve_fit(bpm, t, hr)
然后我绘制曲线
for i in range(n):
y[i] = bpm(x['Input'][i], c[0], c[1], c[2])
plt.plot(x['Input'], x['Output'])
plt.plot(x['Input'], y)
就是这样。以下是合身度数:
如果有人能帮忙,那就太好了。
MWE(也可通过交互方式获得 here)
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy.optimize import curve_fit
inputs = []
outputs = []
# THIS GIVES THE DOMAIN
dom = np.linspace(-5, 5, 100)
# FUNCTION & PARAMETERS (RANDOMLY SELECTED)
A = np.random.uniform(3, 6)
w = np.random.uniform(3, 6)
T2 = np.random.uniform(3, 6)
y = A * np.cos(w * dom) * (2.718**(-dom / T2))
# DEFINES EXPONENTIAL DECAY FUNCTION
def expDec(t, A, w, T2):
return A * np.cos(w * t) * (2.718**(-t / T2))
# SETS UP FIGURE FOR PLOTTING
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
# PLOTS THE FUNCTION
plt.plot(dom, y, 'r')
# SHOW THE PLOT
plt.show()
for i in range(-9, 10):
inputs.append(i)
outputs.append(expDec(i, A, w, T2))
# PUT IT DIRECTLY IN A PANDAS DATAFRAME
points = {'Input': inputs, 'Output': outputs}
x = pd.DataFrame(points, columns = ['Input', 'Output'])
# FUNCTION WHOSE PARAMETERS PROGRAM SHOULD BE GUESSING
def bpm(t, A, w, T2):
return A * np.cos(w * t) * (2.718**(-t / T2))
# INPUT & OUTPUTS
t = x['Input'].values
hr = x['Output'].values
# USE SCIPY CURVE FIT TO USE NONLINEAR LEAST SQUARES TO FIND BEST PARAMETERS. TRY 1000 TIMES BEFORE STOPPING.
constants = curve_fit(bpm, t, hr, maxfev=1000)
# GET CONSTANTS FROM CURVE_FIT
A_fit = constants[0][0]
w_fit = constants[0][1]
T2_fit = constants[0][2]
# CREATE ARRAY TO HOLD FITTED OUTPUT
fit = []
# APPEND OUTPUT TO FIT=[] ARRAY
for i in range(-9,10):
fit.append(bpm(i, A_fit, w_fit, T2_fit))
# PLOTS BEST PARAMETERS
plt.plot(x['Input'], x['Output'])
plt.plot(x['Input'], fit, "ro-")
【问题讨论】:
-
请提供minimal reproducible example,即缺少
t和hr的具体值。尽管如此,考虑到少数数据点,我觉得这很合适。另请注意,您需要更多数据点才能绘制平滑图。 -
请不要将您对网站规则的看法添加到问题中。
-
您的拟合需要更好的初步猜测
-
另外,你不需要循环:
y = expDec(x['Input'], *c) -
@MadPhysicist 你能澄清一下吗? 1)我没有使用初始猜测。我正在使用 SciPy 来拟合图表。 2)我不明白你说的那行代码是什么意思。
*c是什么?
标签: python scipy curve-fitting scipy-optimize