人妖在线一区,国产日韩欧美一区二区综合在线,国产啪精品视频网站免费,欧美内射深插日本少妇

新聞動態(tài)

利用python做數(shù)據(jù)擬合詳情

發(fā)布日期:2021-12-10 08:11 | 文章來源:站長之家

1、例子:擬合一種函數(shù)Func,此處為一個指數(shù)函數(shù)。

出處:

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中運(yùn)行。得到的JPG導(dǎo)出圖如下:

2. 例子:擬合一個Gaussian函數(shù)

出處: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中運(yùn)行。得到的JPG導(dǎo)出圖如下:

3. 用一個lmfit的包來實(shí)現(xiàn)2中的Gaussian函數(shù)擬合

需要下載lmfit這個包,下載地址:

https://pypi.org/project/lmfit/#files

下載下來的文件是.tar.gz格式,在MacOS及Linux命令行中解壓,指令:

將其中的lmfit文件夾復(fù)制到當(dāng)前project目錄下。

上述例子2中生成了data.dat,用來作為接下來的方法中的原始數(shù)據(jù)。

出處:

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導(dǎo)出圖如下:

到此這篇關(guān)于利用python做數(shù)據(jù)擬合詳情的文章就介紹到這了,更多相關(guān)python做數(shù)據(jù)擬合內(nèi)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!

版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。

相關(guān)文章

實(shí)時開通

自選配置、實(shí)時開通

免備案

全球線路精選!

全天候客戶服務(wù)

7x24全年不間斷在線

專屬顧問服務(wù)

1對1客戶咨詢顧問

在線
客服

在線客服:7*24小時在線

客服
熱線

400-630-3752
7*24小時客服服務(wù)熱線

關(guān)注
微信

關(guān)注官方微信
頂部