2016-04-26 26 views
1

我在圖中所示的階梯狀的方式,而我試圖插值與Python與MWE data,但我得到的錯誤:如何在Python中使用類似步驟的值插值和平滑數據?

enter image description here

錯誤

File "/usr/lib/python2.7/dist-packages/scipy/interpolate/polyint.py", line 54, in __call__ y = self._evaluate(x) File "/usr/lib/python2.7/dist-packages/scipy/interpolate/interpolate.py", line 448, in _evaluate out_of_bounds = self._check_bounds(x_new) File "/usr/lib/python2.7/dist-packages/scipy/interpolate/interpolate.py", line 478, in _check_bounds raise ValueError("A value in x_new is above the interpolation " ValueError: A value in x_new is above the interpolation range.

MWE

import numpy as np 
from scipy import optimize, interpolate 
from scipy.interpolate import interp1d 
import time 


with open('./pdf_data.dat', "r") as data: 
    while True: 
     line = data.readline() 
     if not line.startswith('#'): 
      break 
    data_header = [i for i in line.strip().split('\t') if i] 
    _data_ = np.genfromtxt(data, names = data_header, dtype = None, delimiter = '\t') 
_data_.dtype.names = [j.replace('_', ' ') for j in _data_.dtype.names] 


x = _data_['X'] 
y = _data_['Y'] 


interp_fn = interp1d(x, y) 
x, index = np.unique(x, return_index = True) 


pdf_interp = interp_fn(x) 

如何內插和平滑Python中的階躍式值?這樣我就可以得到一條平滑的曲線。

+0

它看起來像你沒有包括整個錯誤回溯 - 它只能追溯到'scipy/interpolate/polyint.py',並且不會顯示錯誤發生在* your code的哪裏。當你在你列出的代碼的末尾調用'interp_fn'時,還是在別的地方? –

+0

當你構建你的'interp1d'對象時,你可以傳入'bounds_error = False,fill_value =「extrapolate」',然後而不是抱怨超出範圍的值你會得到外推。這是否是一個好主意取決於它們實際上有多遠。 –

+0

似乎你的'np.unique'在這裏沒有效果 – gdlmx

回答

0

能重現你的錯誤只需:

from scipy.interpolate import interp1d 
f = interp1d([1,2,3,3,4],[1,2,3,4,5]) 
f([1,2,3,4]) # prints [1,2,3,5], note that the 3rd value is not as you may expect 
f([1,2,3,4,5]) 

的最後一個命令f([1,2,3,4,5])的錯誤消息:

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "C:\winPython\python-2.7.10.amd64\lib\site-packages\scipy\interpolate\polyint.py", line 79, in __call__ 
    y = self._evaluate(x) 
    File "C:\winPython\python-2.7.10.amd64\lib\site-packages\scipy\interpolate\interpolate.py", line 497, in _evaluate 
    out_of_bounds = self._check_bounds(x_new) 
    File "C:\winPython\python-2.7.10.amd64\lib\site-packages\scipy\interpolate\interpolate.py", line 527, in _check_bounds 
    raise ValueError("A value in x_new is above the interpolation " 
ValueError: A value in x_new is above the interpolation range. 

所以,請打印出你的腳本x值,看看它是否包含OUT-範圍值。

既然你在代碼中使用np.unique,看來你需要調用的interp_fn(equivalence_ratio)代替interp_fn(x)

x1, index = np.unique(x, return_index = True) 
y1 = [y[k] for k in index] 
interp_fn = interp1d(x1, y1) 
pdf_interp = interp_fn(x) 

此代碼工作正常以及與數據文件附加你。

+0

這可能會重現錯誤,但它是'interp1d'使用的一個壞例子 - 當你重複使用'x'值調用'interp1d'。即使該功能不會拒絕錯誤的輸入,它也會影響輸出,並可能導致不可預知的插值結果。 – gariepy

+0

我假設@nxkryptor的數據包含大量的重複值。這是這個問題的關鍵。 – gdlmx

+0

確實如此。 (我認爲主要是因爲過度激進的四捨五入 - 數據文件中的所有數字都只給出三位有效數字。) –