利用python做数据拟合详情
作者:图様 发布时间:2023-04-22 15:32:17
标签: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导出图如下:
来源:https://zhuanlan.zhihu.com/p/37869744


猜你喜欢
- 从windows操作系统本地读取csv文件报错data = pd.read_csv(path)Traceback (most recent
- 朴素贝叶斯算法简单高效,在处理分类问题上,是应该首先考虑的方法之一。通过本教程,你将学到朴素贝叶斯算法的原理和Python版本的逐步实现。更
- Python3,开一个线程,间隔1秒把一个递增的数字写入队列,再开一个线程,从队列中取出数字并打印到终端#! /usr/bin/env py
- PRD的作用之一在于,保留产品设计初衷,期望达到什么样的目的,起到事后验证的效果。产品初衷需要做到利益最大化,找最大的蛋糕,为最大目标人群服
- 下载地址:https://dev.mysql.com/downloads/mysql/5.7.html#downloads上传到服务器rz
- 出现问题: 1. 使用层制作的下拉菜单下正好有FLASH动画,菜单被动画遮挡. 2. 页面中的层浮动广告当经过FLASH动画时,浮动层从动画
- 昨天BOSS下了个命令让我用word宏的方式来快速生成sql,这样在我们建表的时候就不用在一条一条元数据的输入。从而提高效率节约成本:接到命
- 这篇文章主要介绍了python3.8 微信发送服务器监控报警消息代码实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考
- Python字符串和字典相关操作的实例详解字符串操作:字符串的 % 格式化操作:str = "Hello,%s.%s enough
- 1.在浏览器下载与浏览器相对于的驱动并放到python的安装根目录下驱动的两个下载地址:http://chromedriver.storag
- 前言因为项目中遇到了这个bug:Vue cil2中配置代理proxytable成功,却无效报错404,在后端和代理都配置无误的情况下,还是报
- 新安装的MySQL5.7,登录时提示密码错误,安装的时候并没有更改密码,后来通过免密码登录的方式更改密码,输入update mysql.us
- 这两天学习了Vue.js 感觉条件渲染和列表渲染知识点挺多的,而且很重要,所以,今天添加一点小笔记。条件渲染v-if在 < templ
- 本文实例讲述了Python实现FTP上传文件或文件夹实例。分享给大家供大家参考。具体如下:import sys import os impo
- 这两周组里面几位想学习python,于是我们就创建了一个这样的环境和氛围来给大家学习。昨天在群里,贴了一个需求,就是统计squid访问日志中
- 参考Go的CSP并发模型实现:M, P, GGo语言是为并发而生的语言,Go语言是为数不多的在语言层面实现并发的语言。并发(concurre
- 小编把之前整理的关于mysql 5.7.9 免安装版配置方法分享给大家,供大家参考,具体内容如下1. 解压MySQL压缩包将下载的MySQL
- 前几天在一本书上看到一篇可以利用字典破解zip文件密码的文章,觉得比较有意思于是研究了一番,在这里分享一下原理主要是利用python里自带的
- 工作中我们经常要两段代码的区别,或者需要查看接口返回的字段与预期是否一致,如何快速定位出两者的差异?除了一些对比的工具比如Beyond Co
- 一、问题实现对文本的分句,大致来说主要是以中文的句号、感叹、问号等符号进行分句。难点在于直接分句可能会造成人物说话的语句也被分开!二、步骤分