如何利用python做数据拟合
发表于:2026-11-01 作者:千家信息网编辑
千家信息网最后更新 2026年11月01日,这篇文章将为大家详细讲解有关如何利用python做数据拟合,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。1、例子:拟合一种函数Func,此处为一个指数函数。出处:S
千家信息网最后更新 2026年11月01日如何利用python做数据拟合
这篇文章将为大家详细讲解有关如何利用python做数据拟合,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
1、例子:拟合一种函数Func,此处为一个指数函数。
出处:
SciPy v1.1.0 Reference Guide
#Headerimport numpy as npimport matplotlib.pyplot as pltfrom scipy.optimize import curve_fit#Define a function(here a exponential function is used)def func(x, a, b, c): return a * np.exp(-b * x) + c#Create the data to be fit with some noisexdata = np.linspace(0, 4, 50)y = func(xdata, 2.5, 1.3, 0.5)np.random.seed(1729)y_noise = 0.2 * np.random.normal(size=xdata.size)ydata = y + y_noiseplt.plot(xdata, ydata, 'bo', label='data')#Fit for the parameters a, b, c of the function func:popt, pcov = curve_fit(func, xdata, ydata)popt #output: array([ 2.55423706, 1.35190947, 0.47450618])plt.plot(xdata, func(xdata, *popt), 'r-', label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))#In the case of parameters a,b,c need be constrainted#Constrain the optimization to the region of #0 <= a <= 3, 0 <= b <= 1 and 0 <= c <= 0.5popt, pcov = curve_fit(func, xdata, ydata, bounds=(0, [3., 1., 0.5]))popt #output: array([ 2.43708906, 1. , 0.35015434])plt.plot(xdata, func(xdata, *popt), 'g--', label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))#Labelsplt.title("Exponential Function Fitting")plt.xlabel('x coordinate')plt.ylabel('y coordinate')plt.legend()leg = plt.legend() # remove the frame of Legend, personal choiceleg.get_frame().set_linewidth(0.0) # remove the frame of Legend, personal choice#leg.get_frame().set_edgecolor('b') # change the color of Legend frame#plt.show()#Export figure#plt.savefig('fit1.eps', format='eps', dpi=1000)plt.savefig('fit1.pdf', format='pdf', dpi=1000, figsize=(8, 6), facecolor='w', edgecolor='k')plt.savefig('fit1.jpg', format='jpg', dpi=1000, figsize=(8, 6), facecolor='w', edgecolor='k')上面一段代码可以直接在spyder中运行。得到的JPG导出图如下:

2. 例子:拟合一个Gaussian函数
出处:LMFIT: Non-Linear Least-Squares Minimization and Curve-Fitting for Python
#Headerimport numpy as npimport matplotlib.pyplot as pltfrom numpy import exp, linspace, randomfrom scipy.optimize import curve_fit#Define the Gaussian functiondef gaussian(x, amp, cen, wid): return amp * exp(-(x-cen)**2 / wid)#Create the data to be fittedx = linspace(-10, 10, 101)y = gaussian(x, 2.33, 0.21, 1.51) + random.normal(0, 0.2, len(x))np.savetxt ('data.dat',[x,y]) #[x,y] is is saved as a matrix of 2 lines#Set the initial(init) values of parameters need to optimize(best)init_vals = [1, 0, 1] # for [amp, cen, wid]#Define the optimized values of parametersbest_vals, covar = curve_fit(gaussian, x, y, p0=init_vals)print(best_vals) # output: array [2.27317256 0.20682276 1.64512305]#Plot the curve with initial parameters and optimized parametersy1 = gaussian(x, *best_vals) #best_vals, '*'is used to read-out the values in the arrayy2 = gaussian(x, *init_vals) #init_valsplt.plot(x, y, 'bo',label='raw data')plt.plot(x, y1, 'r-',label='best_vals')plt.plot(x, y2, 'k--',label='init_vals')#plt.show()#Labelsplt.title("Gaussian Function Fitting")plt.xlabel('x coordinate')plt.ylabel('y coordinate')plt.legend()leg = plt.legend() # remove the frame of Legend, personal choiceleg.get_frame().set_linewidth(0.0) # remove the frame of Legend, personal choice#leg.get_frame().set_edgecolor('b') # change the color of Legend frame#plt.show()#Export figure#plt.savefig('fit2.eps', format='eps', dpi=1000)plt.savefig('fit2.pdf', format='pdf', dpi=1000, figsize=(8, 6), facecolor='w', edgecolor='k')plt.savefig('fit2.jpg', format='jpg', dpi=1000, figsize=(8, 6), facecolor='w', edgecolor='k')上面一段代码可以直接在spyder中运行。得到的JPG导出图如下:

3. 用一个lmfit的包来实现2中的Gaussian函数拟合
需要下载lmfit这个包,下载地址:
https://pypi.org/project/lmfit/#files
下载下来的文件是.tar.gz格式,在MacOS及Linux命令行中解压,指令:
将其中的lmfit文件夹复制到当前project目录下。
上述例子2中生成了data.dat,用来作为接下来的方法中的原始数据。
出处:
Modeling Data and Curve Fitting
#Headerimport numpy as npimport matplotlib.pyplot as pltfrom numpy import exp, loadtxt, pi, sqrtfrom lmfit import Model#Import the data and define x, y and the functiondata = loadtxt('data.dat')x = data[0, :]y = data[1, :]def gaussian1(x, amp, cen, wid): return (amp / (sqrt(2*pi) * wid)) * exp(-(x-cen)**2 / (2*wid**2))#Fittinggmodel = Model(gaussian1)result = gmodel.fit(y, x=x, amp=5, cen=5, wid=1) #Fit from initial values (5,5,1)print(result.fit_report())#Plotplt.plot(x, y, 'bo',label='raw data')plt.plot(x, result.init_fit, 'k--',label='init_fit')plt.plot(x, result.best_fit, 'r-',label='best_fit')#plt.show()#Labelsplt.title("Gaussian Function Fitting")plt.xlabel('x coordinate')plt.ylabel('y coordinate')plt.legend()leg = plt.legend() # remove the frame of Legend, personal choiceleg.get_frame().set_linewidth(0.0) # remove the frame of Legend, personal choice#leg.get_frame().set_edgecolor('b') # change the color of Legend frame#plt.show()#Export figure#plt.savefig('fit3.eps', format='eps', dpi=1000)plt.savefig('fit3.pdf', format='pdf', dpi=1000, figsize=(8, 6), facecolor='w', edgecolor='k')plt.savefig('fit3.jpg', format='jpg', dpi=1000, figsize=(8, 6), facecolor='w', edgecolor='k')上面这一段代码需要按指示下载lmfit包,并且读取例子2中生成的data.dat。
关于"如何利用python做数据拟合"这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。
例子
函数
数据
代码
出处
篇文章
文件
更多
中生
运行
不错
原始
实用
指数函数
接下来
内容
合一
命令
地址
指令
数据库的安全要保护哪些东西
数据库安全各自的含义是什么
生产安全数据库录入
数据库的安全性及管理
数据库安全策略包含哪些
海淀数据库安全审计系统
建立农村房屋安全信息数据库
易用的数据库客户端支持安全管理
连接数据库失败ssl安全错误
数据库的锁怎样保障安全
互联网科技海报
互联网金融监管科技数据
科技和互联网公司
科技企业和互联网企业
北京互联网科技有限公司
金融科技与互联网金融
广州紫鲸互联网科技
互联网科技类展会
中盈科技互联网信息有限公司
科技与互联网哪个更好
互联网金融中的现代科技
佛山市翊博互联网络科技有限公司
西安小鹰速贷互联网科技有限公司
华中科技大学互联网的牛人
北京市互联网新科技
互联网科技数字货币
图游互联网科技
上海同邻互联网科技有限公司规模
保山浩联互联网科技有限公司
互联网的黑科技实验室
耶加雪菲
互联网科技公司排名
科技互联网项目
盈实互联网科技
唐信互联网科技
碳银互联网科技
菲比寻常互联网科技
深圳期待互联网科技
青海科技产业互联网发展
中天科技中国工业互联网