python - 在 python 中,如何平滑数据?

我使用的代码是:


import matplotlib.pyplot as plt
import numpy as np
from scipy import interpolate

data = np.genfromtxt("spline_data.dat", delimiter = 't')
x = 1000 / data[:, 0]
y = data[:, 1]
x_int = np.linspace(x[0], x[-1], 100)
tck = interpolate.splrep(x, y, k = 3, s = 1)
y_int = interpolate.splev(x_int, tck, der = 0)

fig = plt.figure(figsize = (5.15,5.15))
plt.subplot(111)
plt.plot(x, y, marker = 'o', linestyle='')
plt.plot(x_int, y_int, linestyle = '-', linewidth = 0.75, color='k')
plt.xlabel("X")
plt.ylabel("Y")
plt.show()

我尝试改变曲线和平滑条件的顺序,但是没有得到平滑的plot 。

对该数据进行平滑处理的方法?

时间:

使用较大的平滑参数,例如s=1000


tck = interpolate.splrep(x, y, k=3, s=1000)

可以尝试将np.linspace函数的最后一个参数更改为更小的数字np.linspace(x[0], x[-1], 10),例如,

演示代码:


import matplotlib.pyplot as plt
import numpy as np
from scipy import interpolate

data = np.random.rand(100,2)
tempx = list(data[:, 0])
tempy = list(data[:, 1])
x = np.array(sorted([point*10 + tempx.index(point) for point in tempx]))
y = np.array([point*10 + tempy.index(point) for point in tempy])
x_int = np.linspace(x[0], x[-1], 10)
tck = interpolate.splrep(x, y, k = 3, s = 1)
y_int = interpolate.splev(x_int, tck, der = 0)

fig = plt.figure(figsize = (5.15,5.15))
plt.subplot(111)
plt.plot(x, y, marker = 'o', linestyle='')
plt.plot(x_int, y_int, linestyle = '-', linewidth = 0.75, color='k')
plt.xlabel("X")
plt.ylabel("Y")
plt.show()

你也可以在pandas中使用rolling_mean平滑数据:


import pandas as pd

data = [...(your data here)...]

smoothendData = pd.rolling_mean(data,5)

滚动平均值的第二个参数是移动平均(滚动平均值)周期,Pandas :列的指数平滑功能

或者使用带通滤波器:fft带通滤波器http://docs.scipy.org/doc/scipy/reference/signal.html

假设在处理某些现象的噪音观测,高斯过程回归也是一个不错的选择,下面是如何应用它的简单例子:


import matplotlib.pyplot as plt
import numpy as np
from sklearn.gaussian_process import GaussianProcess

data = np.genfromtxt("spline_data.dat", delimiter='t')
x = 1000 / data[:, 0]
y = data[:, 1]
x_pred = np.linspace(x[0], x[-1], 100)

# <GP regression>
gp = GaussianProcess(theta0=1, thetaL=0.00001, thetaU=1000, nugget=0.000001)
gp.fit(np.atleast_2d(x).T, y)
y_pred = gp.predict(np.atleast_2d(x_pred).T)
# </GP regression>

fig = plt.figure(figsize=(5.15, 5.15))
plt.subplot(111)
plt.plot(x, y, marker='o', linestyle='')
plt.plot(x_pred, y_pred, linestyle='-', linewidth=0.75, color='k')
plt.xlabel("X")
plt.ylabel("Y")
plt.show()

...