利用python做数据拟合详情

 更新时间:2022年01月24日 12:58:49   作者:图様  
这篇文章主要介绍了利用python做数据拟合,下面文章围绕如何让利用python做数据拟合的相关资料展开详细内容,需要的朋友可以参考一下,希望对大家有所帮助

1、例子:拟合一种函数Func,此处为一个指数函数。

出处:

SciPy v1.1.0 Reference Guide

#Header
import numpy as np
import matplotlib.pyplot as plt
from 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 noise
xdata = 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_noise
plt.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.5
popt, 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))

#Labels
plt.title("Exponential Function Fitting")
plt.xlabel('x coordinate')
plt.ylabel('y coordinate')
plt.legend()
leg = plt.legend()  # remove the frame of Legend, personal choice
leg.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

#Header
import numpy as np
import matplotlib.pyplot as plt
from numpy import exp, linspace, random
from scipy.optimize import curve_fit

#Define the Gaussian function
def gaussian(x, amp, cen, wid):
 return amp * exp(-(x-cen)**2 / wid)

#Create the data to be fitted
x = 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 parameters
best_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 parameters
y1 = gaussian(x, *best_vals) #best_vals, '*'is used to read-out the values in the array
y2 = gaussian(x, *init_vals) #init_vals
plt.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()

#Labels
plt.title("Gaussian Function Fitting")
plt.xlabel('x coordinate')
plt.ylabel('y coordinate')
plt.legend()
leg = plt.legend()  # remove the frame of Legend, personal choice
leg.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

#Header
import numpy as np
import matplotlib.pyplot as plt
from numpy import exp, loadtxt, pi, sqrt
from lmfit import Model

#Import the data and define x, y and the function
data = 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))

#Fitting
gmodel = 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())

#Plot
plt.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()


#Labels
plt.title("Gaussian Function Fitting")
plt.xlabel('x coordinate')
plt.ylabel('y coordinate')
plt.legend()
leg = plt.legend()  # remove the frame of Legend, personal choice
leg.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

得到的JPG导出图如下:

到此这篇关于利用python做数据拟合详情的文章就介绍到这了,更多相关python做数据拟合内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Flask实现定制日志并输出到文件

    Flask实现定制日志并输出到文件

    这篇文章主要为大家学习介绍了Flask如何实现定制日志并输出到文件,文中的示例代码简介易懂,感兴趣的小伙伴快跟随小编一起学习一下吧
    2023-07-07
  • Python入门教程(四十)Python的NumPy数组创建

    Python入门教程(四十)Python的NumPy数组创建

    这篇文章主要介绍了Python入门教程(四十)Python的NumPy数组创建,NumPy 用于处理数组,NumPy 中的数组对象称为 ndarray,我们可以使用 array() 函数创建一个 NumPy ndarray 对象,需要的朋友可以参考下
    2023-05-05
  • Python matplotlib如何简单绘制不同类型的表格

    Python matplotlib如何简单绘制不同类型的表格

    通过Matplotlib,开发者可以仅需要几行代码,便可以生成绘图,直方图,功率谱,条形图,错误图,散点图等,下面这篇文章主要给大家介绍了关于Python matplotlib如何简单绘制不同类型表格的相关资料,需要的朋友可以参考下
    2022-07-07
  • 基于Python实现一键找出磁盘里所有猫照

    基于Python实现一键找出磁盘里所有猫照

    最近在整理我磁盘上的照片,发现不少猫照,突然觉得若能把这些猫照都挑出来,观察它们的成长轨迹也是一件不错的事情。一张一张的找实在是太费劲了,能不能自动化地找出来呢?本文将详细为大家讲讲,需要的可以参考一下
    2022-05-05
  • 浅析python 动态库m.so.1.0错误问题

    浅析python 动态库m.so.1.0错误问题

    这篇文章主要介绍了python 动态库m.so.1.0错误问题,文中给大家提到了python中使用动态库的方法,通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-05-05
  • Scrapy-Redis结合POST请求获取数据的方法示例

    Scrapy-Redis结合POST请求获取数据的方法示例

    这篇文章主要给大家介绍了关于Scrapy-Redis结合POST请求获取数据的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用Scrapy-Redis具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-05-05
  • python提取log文件内容并画出图表

    python提取log文件内容并画出图表

    这篇文章主要介绍了python提取log文件内容并画出图表,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-07-07
  • python实现时间序列自相关图(acf)、偏自相关图(pacf)教程

    python实现时间序列自相关图(acf)、偏自相关图(pacf)教程

    这篇文章主要介绍了python实现时间序列自相关图(acf)、偏自相关图(pacf)教程,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-06-06
  • Python使用OpenPyXL处理Excel表格

    Python使用OpenPyXL处理Excel表格

    这篇文章主要介绍了Python使用OpenPyXL处理Excel表格,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-07-07
  • Python基础学习之函数方法实例详解

    Python基础学习之函数方法实例详解

    这篇文章主要介绍了Python基础学习之函数方法,结合实例形式分析了Python函数方法的定义、参数、复用和继承相关操作技巧,需要的朋友可以参考下
    2019-06-06

最新评论