用Python實(shí)現(xiàn)插值算法
數(shù)模比賽中,常常需要對(duì)數(shù)據(jù)進(jìn)行處理和分析,但有時(shí)候數(shù)據(jù)不多,就需要一些方法“模擬產(chǎn)生”一些靠譜的值來滿足需求,這就是插值的作用。本文不再具體介紹每個(gè)插值算法的內(nèi)在原理,將直接通過調(diào)包實(shí)現(xiàn)。
下面,先上三件套,看一下原始數(shù)據(jù)的大致情況:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_excel('data.xlsx')
拉格朗日插值算法
原始數(shù)據(jù)我們采用sin(x)的形式,看一下原始數(shù)據(jù)點(diǎn):
import scipy from scipy.interpolate import lagrange x = np.linspace(0,10,6) #0~10等差插入11個(gè)數(shù),需要預(yù)測(cè)的值 y = np.sin(x) x_new = np.linspace(0,10,200) #用于繪制圖形 y_new = np.sin(x_new) plt.plot(x,y,'ro') plt.plot(x_new,y_new,'b')

f1 = lagrange(x,y) plt.plot(x,y,'ro') plt.plot(x_new,y_new,'b') plt.plot(x_new,f1(x_new),'g')
看一下擬合效果:

分段線性插值
f4 = scipy.interpolate.interp1d(x,y,kind='linear') plt.plot(x,y,'ro') plt.plot(x_new,y_new,'b') plt.plot(x_new,f4(x_new),'g')

分段二次(三次)插值
f5 = scipy.interpolate.interp1d(x,y,kind='quadratic') #三次就是cubic plt.plot(x,y,'ro') plt.plot(x_new,y_new,'b') plt.plot(x_new,f5(x_new),'g')

牛頓插值法:暫未找到相應(yīng)的庫
分段三次埃爾米特插值
f5 = scipy.interpolate.interp1d(x,y,kind='quadratic') #三次就是cubic plt.plot(x,y,'ro') plt.plot(x_new,y_new,'b') plt.plot(x_new,f5(x_new),'g')

三次樣條插值
f3 = scipy.interpolate.CubicSpline(x,y) plt.plot(x,y,'ro') plt.plot(x_new,y_new,'b') plt.plot(x_new,f3(x_new),'g')

接下來,讓我們看看一個(gè)具體實(shí)例的比較:
y = np.array(data)[:,1] x = np.linspace(2009,2018,10) x_new = np.array([2019,2020,2021]) f2 = scipy.interpolate.PchipInterpolator(x,y) f3 = scipy.interpolate.CubicSpline(x,y) #coding:utf-8 plt.rcParams['font.sans-serif']=['SimHei'] #用來正常顯示中文標(biāo)簽 plt.rcParams['axes.unicode_minus']=False #用來正常顯示負(fù)號(hào) plt.plot(x,y,color='black',marker='o',label='樣本點(diǎn)') plt.plot(x_new,f2(x_new),'b-',marker='x',label='分段三次埃米爾特') plt.plot(x_new,f3(x_new),'r-',marker='x',label='三次樣條插值') plt.xticks(range(2009,2022,1)) #調(diào)整x軸間距 plt.legend() plt.show()

Tips:①最常用的就是埃爾米特三次插值、三次樣條插值
②拉格朗日插值雖然在訓(xùn)練集上表現(xiàn)良好,但是在測(cè)試集上著實(shí)難堪,尤其擬合高階函數(shù)時(shí),千萬不要輕易用此預(yù)測(cè)
到此這篇關(guān)于用Python實(shí)現(xiàn)插值算法的文章就介紹到這了,更多相關(guān)Python插值算法內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
利用Python進(jìn)行網(wǎng)絡(luò)爬蟲和數(shù)據(jù)抓取的代碼示例
在當(dāng)今數(shù)字化時(shí)代,數(shù)據(jù)是無處不在的,從市場(chǎng)趨勢(shì)到個(gè)人偏好,從社交媒體活動(dòng)到商業(yè)智能,數(shù)據(jù)扮演著關(guān)鍵的角色,Python提供了一套強(qiáng)大而靈活的工具,使得網(wǎng)絡(luò)爬蟲和數(shù)據(jù)抓取成為可能,本文將深入探討如何利用Python進(jìn)行網(wǎng)絡(luò)爬蟲和數(shù)據(jù)抓取,為您打開數(shù)據(jù)世界的大門2024-05-05
PyTorch實(shí)現(xiàn)FedProx聯(lián)邦學(xué)習(xí)算法
這篇文章主要為大家介紹了PyTorch實(shí)現(xiàn)FedProx的聯(lián)邦學(xué)習(xí)算法,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05
tensorflow對(duì)圖像進(jìn)行拼接的例子
今天小編就為大家分享一篇tensorflow對(duì)圖像進(jìn)行拼接的例子,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-02-02

