用scipy曲线拟合多个数据集,找到常用参数



我正试图将多个数据集拟合到同一方程中,并在它们之间找到拟合参数的值。有两个自变量,我想我已经处理过了。我最终得到了一个可以像预期的那样适用于单个数据集的东西,但不能适用于多个数据集。代码本身是有效的,但拟合看起来像一个弓形(末端连接的直线和曲线(,而不仅仅是曲线。我希望每个数据集有单独的曲线,参数有共享值。我知道我需要以某种方式分解数据,也许是通过堆叠数据并用索引调整函数,但我被我发现的例子弄糊涂了,不知道如何在这里执行它们。以下是代码:

#import things
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
##set-up data##
#Have x-data as numpy array
xfrac = [1., 0.85,0.725,0.6,0.5,0.4,0.]
x = np.concatenate((xfrac,xfrac))

#Write function to generate and populate arrays using ideal values
#data sets (I have pasted the values instead of posting the code used to calculate them)
mix_850 = [1.701    3.642865 4.6762   5.0739   5.5177   5.9923   6.9408]
mix_1000 = [1.651185 3.53359  4.4854   4.8978   5.32525  5.7388   6.792]
dat = np.concatenate((mix_850,mix_1000))
#Temperature values
c=np.repeat(850.,7.)
d=np.repeat(1000.,7.)
Temp = np.concatenate((c,d))
#Define function
def f(Z, a1, b1, a2, b2):
x1,T= Z
x2= 1.-x1
excess = a1+b1+(a2+b2*T)*(x1-(1.-x1)*(x1*(1.-x1)))
ideal = ((x1*25.939)+((1.0-x1)*314.02))/(((x1*25.939)/1.701-0.3321e-3*T)+(((1.0-x1)*314.02)/7.784-0.9920e-3*T))
mix = excess + ideal
return mix
#Fitting
popt,_ = curve_fit(f,(x,Temp),dat)
fit_a1 = popt[0]
fit_b1 = popt[1]
fit_a2 = popt[2]
fit_b2 = popt[3]

xfrac定义为np.array:

xfrac = np.array([1., 0.85, 0.725, 0.6, 0.5, 0.4, 0.])

在绘图中使用xfrac而不是x

# plotting
mix1 = f((xfrac, c), *popt)
mix2 = f((xfrac, d), *popt)
# temperature 1
plt.plot(xfrac, mix1, label=c[0], c='blue')
plt.plot(xfrac, mix_850, linestyle='', c='blue',
marker='o', label='Data {}'.format(c[0]))
# temperature 2    
plt.plot(xfrac, mix2, label=d[0], c='red')
plt.plot(xfrac, mix_1000, linestyle='', c='red',
marker='o', label='Data {}'.format(d[0]))
plt.xlabel('xfrac')
plt.ylabel('mix')
plt.legend()

相关内容

  • 没有找到相关文章