python - 如何平滑仅在某些部分具有大噪声的曲线?
问题描述
我想平滑如下所示的散点图(点非常密集),数据在这里。
曲线中间有很大的噪音,我想平滑曲线,y值也应该单调增加。
由于有很多这样的曲线,所以很难知道噪声在曲线中的位置。
我试过scipy.signal.savgol_filter
了,但没有用。
我使用的代码是:
from scipy.signal import savgol_filter
from scipy import interpolate
import numpy as np
import matplotlib.pyplot as plt
s = np.loadtxt('data.csv', delimiter=',')
x = s[:, 0]
y = s[:, 1]
yhat = savgol_filter(y, 551, 3)
plt.plot(x, y, 'r')
plt.plot(x, yhat, 'b')
plt.show()
非常感谢您的建议。谢谢!
- - - - - - - - - -更新 - - - - - - - - - - - - -
按照 Colin 的方法,我得到了我想要的结果。这是代码:
from scipy.signal import savgol_filter
from scipy import interpolate
import numpy as np
import matplotlib.pyplot as plt
s = np.loadtxt('data.csv', delimiter=',')
x = s[:, 0]
y = s[:, 1]
yhat = savgol_filter(y, 551, 3)
tolerance = 0.2
increased_span = 150
filter_size = 11
first_pass = medfilt(y,filter_size)
diff = (y-first_pass)**2
first = np.argmax(diff>tolerance) - increased_span
last = len(y) - np.argmax(diff[::-1]>tolerance) + increased_span
print (first, last)
#interpolate between increased span
yhat[first:last] = np.interp(x[first:last], [x[first], x[last]], [y[first], y[last]])
f = interpolate.interp1d(x, yhat, kind='slinear')
x_inter = np.linspace(x[0], x[-1], 1000)
y_inter = f(x_inter)
y_inter = savgol_filter(y_inter, 41, 3)
plt.plot(x, y, 'r')
plt.plot(x, yhat, 'b')
plt.show()
解决方案
如果我们首先隔离故障区域,有很多方法可以消除它。这是一个例子:
tolerance = 0.2
increased_span = 150
filter_size = 11
#find noise
first_pass = medfilt(y,filter_size)
diff = (yhat-first_pass)**2
first = np.argmax(diff>tolerance) - increased_span
last = len(y) - np.argmax(diff[::-1]>tolerance) + increased_span
#interpolate between increased span
yhat[first:last] = np.interp(x[first:last], [x[first], x[last]], [y[first], y[last]])
推荐阅读
- vuejs2 - 带有首字母的 Vue 独立品牌
- android - Android 视图绑定:从包含的 xml 布局访问 NavHostFragment 时
- c++ - 如何在 QGraphicsScene 中的像素图上正确订阅像素值(就像在 OpenCV 命名窗口中一样)?
- python - 识别数据框中的模式
- javascript - Nodejs上传图片req.file未定义
- php - 提高 WooCommerce 税收计算精度并保持显示的价格保留两位小数
- python - 这些 for 循环是否相同?
- android - 为什么使用 FragmentContainerView 时,设计选项卡不刷新?
- javascript - 有没有一种更简洁、更可重复的方式来编写这个 onclick 代码?
- python - 如何将 DateTimeField 与 timezone.now() 进行比较