我试图执行全球拟合与对称包,跟随符号文档。
import numpy as np
import symfit as sf
import matplotlib.pyplot as plt
%matplotlib inline # for ipynb
# Generate example data
t = np.arange(0.0, 600.1, 30)
k = 0.005
C1_0, C2_0 = 1.0, 2.0
C1 = C1_0 * np.exp(-k*t)
C2 = C2_0 * np.exp(-k*t)
# Construct model
x_1, x_2, y_1, y_2 = sf.variables('x_1, x_2, y_1, y_2')
kg = sf.Parameter(value=0.01, min=0.0, max=0.1)
a_1, a_2 = sf.parameters('a_1, a_2')
globalmodel = sf.Model({
y_1: a_1 * np.e**(- kg * x_1),
y_2: a_2 * np.e**(- kg * x_2),
})
# Do fit
globalfit = sf.Fit(globalmodel, x_1=t, x_2=t, y_1=C1, y_2=C2)
globalfit_result = globalfit.execute()
print(globalfit_result)
### EDITED START
while globalfit_result.r_squared < 0.99:
kg = sf.Parameter(value=globalfit_result.params['kg'])
a_1 = sf.Parameter(value=globalfit_result.params['a_1'])
a_2 = sf.Parameter(value=globalfit_result.params['a_2'])
globalmodel = sf.Model({
y_1: a_1 * np.e**(- kg * x_1),
y_2: a_2 * np.e**(- kg * x_2),
})
globalfit = sf.Fit(globalmodel, x_1=t, x_2=t, y_1=C1, y_2=C2)
globalfit_result = globalfit.execute()
### EDITED END
y_r = globalmodel(x_1=t, x_2=t, **globalfit_result.params)
# Plot fit
plt.plot(t,C1,'ro')
plt.plot(t,C2,'b+')
plt.plot(t,y_r[0],'r-')
plt.plot(t,y_r[1],'b-')
plt.show()在本例中,我希望"globalmodel“中的"kg”参数优化为0.005。而“公斤”的值约为9.6e-3,与初始值(10.0e-3)过近。我想我做了件蠢事,但我想不出来。
欢迎任何意见和建议!
编辑的
我增加了(一个非常丑陋)的同时循环,以获得最佳的配合。我不知道为什么要这样做,但它似乎奏效了。
发布于 2016-12-04 16:32:17
看来边界是造成问题的原因。我在我的测试中删除了它们,然后一切都很好。This is a known problem in symfit 0.3.3,a̶n̶d̶̶o̶n̶e̶̶I̶̶a̶l̶r̶e̶a̶d̶y̶̶f̶i̶x̶e̶d̶̶i̶n̶̶t̶h̶e̶̶̶̶m̶a̶s̶t̶e̶r̶̶̶̶1̶̶̶b̶r̶a̶n̶c̶h̶̶o̶n̶̶G̶i̶t̶h̶u̶b̶.̶̶̶̶I̶̶u̶p̶l̶o̶a̶d̶e̶d̶̶a̶̶n̶e̶w̶̶d̶e̶v̶̶v̶e̶r̶s̶i̶o̶n̶̶y̶o̶u̶̶c̶o̶u̶l̶d̶̶n̶o̶w̶̶i̶n̶s̶t̶a̶l̶l̶̶u̶s̶i̶n̶g̶̶̶p̶i̶p̶ ̶i̶n̶s̶t̶a̶l̶l̶ ̶s̶y̶m̶f̶i̶t̶=̶=̶0̶.̶3̶.̶3̶.̶d̶e̶v̶1̶5̶5̶ ̶-̶-̶u̶p̶g̶r̶a̶d̶e̶̶,̶̶u̶n̶t̶i̶l̶̶I̶̶o̶f̶f̶i̶c̶i̶a̶l̶l̶y̶̶r̶e̶l̶e̶a̶s̶e̶̶0̶.̶3̶.̶4̶̶(̶w̶h̶i̶c̶h̶̶w̶i̶l̶l̶̶b̶e̶̶i̶d̶e̶n̶t̶i̶c̶a̶l̶̶b̶u̶t̶̶w̶i̶t̶h̶̶e̶x̶t̶e̶n̶d̶e̶d̶̶d̶o̶c̶u̶m̶e̶n̶t̶a̶t̶i̶o̶n̶)̶,which has now been fixed in newer versions.
请注意,我将您的np.e更改为sf.exp,因为这是象征性的。我的工作代码如下,除了在0.3.3.dev155中提到和运行的更改之外,与您的代码相同。
import numpy as np
import symfit as sf
import matplotlib.pyplot as plt
# Generate example data
t = np.arange(0.0, 600.1, 30)
k = 0.005
C1_0, C2_0 = 1.0, 2.0
C1 = C1_0 * np.exp(-k*t)
C2 = C2_0 * np.exp(-k*t)
# Construct model
x_1, x_2, y_1, y_2 = sf.variables('x_1, x_2, y_1, y_2')
kg = sf.Parameter(value=0.01, min=0.0, max=0.1)
a_1, a_2 = sf.parameters('a_1, a_2')
globalmodel = sf.Model({
y_1: a_1 * sf.exp(- kg * x_1),
y_2: a_2 * sf.exp(- kg * x_2),
})
# Do fit
globalfit = sf.Fit(globalmodel, x_1=t, x_2=t, y_1=C1, y_2=C2)
globalfit_result = globalfit.execute()
print(globalfit_result)
y_r = globalmodel(x_1=t, x_2=t, **globalfit_result.params)
# Plot fit
plt.plot(t,C1,'ro')
plt.plot(t,C2,'b+')
plt.plot(t,y_r[0],'r-')
plt.plot(t,y_r[1],'b-')
plt.show()https://stackoverflow.com/questions/40958688
复制相似问题