用python实现matlab smooth中的moving average、lowess、loess、sgolay、rlowess、rloess平滑方法具体代码
时间: 2023-06-02 11:05:21 浏览: 328
以下是使用Python实现MATLAB中的平滑方法的代码示例:
1. Moving Average
```python
import numpy as np
def moving_average(arr, k):
"""
Computes the moving average of an array `arr` with window size `k`.
"""
weights = np.repeat(1.0, k) / k
return np.convolve(arr, weights, 'valid')
```
2. Lowess
```python
from statsmodels.nonparametric.smoothers_lowess import lowess
def lowess_smooth(arr, frac=0.25):
"""
Applies lowess smoothing to an array `arr` with smoothing parameter `frac`.
"""
return lowess(arr, np.arange(len(arr)), frac=frac, is_sorted=True)[:, 1]
```
3. Loess
```python
from statsmodels.nonparametric.smoothers_lowess import lowess
def loess_smooth(arr, frac=0.25, degree=2):
"""
Applies loess smoothing to an array `arr` with smoothing parameter `frac`
and polynomial degree `degree`.
"""
return lowess(arr, np.arange(len(arr)), frac=frac, is_sorted=True, delta=0.01, return_sorted=False, frac_policy='symmetric', it=0, delta_policy='weighted', robust=True, return_std=False, conf_int=False, degree=degree)[:, 1]
```
4. Savitzky-Golay
```python
from scipy.signal import savgol_filter
def savgol_smooth(arr, window_length=11, polyorder=2):
"""
Applies Savitzky-Golay filtering to an array `arr` with window length `window_length`
and polynomial order `polyorder`.
"""
return savgol_filter(arr, window_length=window_length, polyorder=polyorder, mode='nearest')
```
5. Robust Lowess
```python
from statsmodels.robust.robust_linear_model import RLM
from statsmodels.robust.robust_linear_model import HuberT
def rlowess_smooth(arr, frac=0.25):
"""
Applies robust lowess smoothing to an array `arr` with smoothing parameter `frac`.
"""
x = np.arange(len(arr))
y = arr
rlm_model = RLM(y, x, M=HuberT())
rlm_results = rlm_model.fit()
res = rlm_results.resid
loess_model = lowess(res, x, frac=frac, is_sorted=True)
return arr - loess_model[:, 1]
```
6. Robust Loess
```python
from statsmodels.robust.robust_linear_model import RLM
from statsmodels.robust.robust_linear_model import HuberT
from statsmodels.nonparametric.smoothers_lowess import lowess
def rloess_smooth(arr, frac=0.25, degree=2):
"""
Applies robust loess smoothing to an array `arr` with smoothing parameter `frac`
and polynomial degree `degree`.
"""
x = np.arange(len(arr))
y = arr
rlm_model = RLM(y, x, M=HuberT())
rlm_results = rlm_model.fit()
res = rlm_results.resid
loess_model = lowess(res, x, frac=frac, delta=0.01, return_sorted=False, frac_policy='symmetric', it=0, delta_policy='weighted', robust=True, return_std=False, conf_int=False, degree=degree)
return arr - loess_model[:, 1]
```
以上是Python实现MATLAB平滑方法的代码示例,希望对你有所帮助。
阅读全文