所以我有磁滞回线。我想使用erf函数使其适合我的数据。
我的循环的一部分在下面的图表中以黑色显示。
我正在尝试使用scipy.optimize.curve_fit
和scipy.special.erf
函数通过以下代码拟合数据:
import scipy.special
import scipy.optimize
def erfunc(x,a,b):
return mFL*scipy.special.erf((x-a)/(b*np.sqrt(2)))
params,extras = scipy.optimize.curve_fit(erfunc,x_data,y_data)
x_erf = list(range(-3000,3000,1))
y_erf = erfunc(x_erf,params[0],params[1])
mFL
是常数,a
控制erf曲线的位置和b
曲线的斜率。 (据我所知)但是,当我绘制获得的x_erf和y_erf数据时(蓝色)。我得到以下拟合,至少可以这样说:
有没有办法让我合适呢?
编辑:
链接到数据文件:https://www.dropbox.com/s/o0uoieg3jkliun7/xydata.csv?dl=0
参数[0] = 1.83289895,参数1 = 0.27837306
最佳答案
我怀疑这里很适合需要两件事。首先,我相信您需要在mFL
函数中添加erfunc
,其次,如Glostas所建议的,您需要为拟合参数指定一些初始猜测。我创建了一些人工数据,试图复制您的数据。左边的图在给curve_fit
一些初始参数之前,右边的图在之后。
这是复制以上曲线的代码
import numpy as np
from scipy.special import erf
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
def erfunc(x, mFL, a, b):
return mFL*erf((x-a)/(b*np.sqrt(2)))
x_data = np.linspace(-3000, 3000, 100)
mFL, a, b = 0.0003, 500, 100
y_data = erfunc(x_data, mFL, a, b)
y_noise = np.random.rand(y_data.size) / 1e4
y_noisy_data = y_data + y_noise
params, extras = curve_fit(erfunc, x_data, y_noisy_data)
# supply initial guesses to curve_fit through p0 arg
superior_params, extras = curve_fit(erfunc, x_data, y_noisy_data,
p0=[0.001, 100, 100])
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
ax1.plot(x_data, erfunc(x_data, *params))
ax1.plot(x_data, y_noisy_data, 'k')
ax1.set_title('Before Guesses')
ax2.plot(x_data, erfunc(x_data, *superior_params))
ax2.plot(x_data, y_noisy_data, 'k')
ax2.set_title('After Guesses')