如何在python中拟合指数曲线

2024-10-03 09:19:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图用scipy.optimize中的curve_fit来拟合四条曲线。 我对一个线性函数做了一些拟合:y=x*m+b(参见代码def function(x,m,b))。 结果如下所示: enter image description here

现在我正在尝试将一些指数函数拟合到我的光谱中(见下图:黄色、紫色、红色和橙色线)。 我的问题是,有没有一种方法可以像黑色曲线一样拟合指数函数?这个函数是什么样的

enter image description here

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit

df = pd.read_csv("sample.csv", index_col="new")
#df = df.drop(columns = ["Standard"])
#print(df)

#(275, 283, 310, 325, 515, 528, 550, 560)
#275-283
df_1 = df[df.index<=283]
df_1 = df_1[df_1.index>=275]

#310-325
df_2 = df[df.index >= 310]
df_2 = df_2[df_2.index <= 325]

#515-528
df_3 = df[df.index >= 525]
df_3 = df_3[df_3.index <= 528]

#550-560
df_4 = df[df.index >= 550]
df_4 = df_4[df_4.index <= 560]


plt.plot(df.index, df["Mittel"])
plt.grid()
plt.show()

def function(x,a, m, b):
    return m*x+b
    #return m**x+b*a

xRegion1 = np.array(df_1.index)
yRegion1 = np.array(df_1["Mittel"])

xRegion2 = np.array(df_2.index)
yRegion2 = np.array(df_2["Mittel"])

xRegion3 = np.array(df_3.index)
yRegion3 = np.array(df_3["Mittel"])

xRegion4 = np.array(df_4.index)
yRegion4 = np.array(df_4["Mittel"])

popt1, pcov1 = curve_fit(function, xRegion1, yRegion1)
popt2, pcov2 = curve_fit(function, xRegion2, yRegion2)
popt3, pcov3 = curve_fit(function, xRegion3, yRegion3)
popt4, pcov4 = curve_fit(function, xRegion4, yRegion4)

xData1 = np.arange(270,580,1)
xData2 = np.arange(270,580,1)
xData3 = np.arange(270,580,1)
xData4 = np.arange(270,580,1)

#300-315
#520-535

plt.plot(df.index, df["Mittel"],
    xData1, function(xData1, *popt1),
    xData2, function(xData2, *popt2),
    xData3, function(xData3, *popt3),
    xData4, function(xData4, *popt4),
         )
plt.grid()
plt.show()

数据:https://www.dropbox.com/s/lgy3t97vujimx4z/sample.csv?dl=0


Tags: csvimportdfindexasnpfunctionplt
1条回答
网友
1楼 · 发布于 2024-10-03 09:19:43

你可能想用这些术语做线性回归

def function(x, a, b, c, e):
    return a * e^(b*x-c) + e

在这个函数中,a垂直缩放函数,e垂直移动函数。b水平缩放,c水平移动

相关问题 更多 >