Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to smoothen data in Python?

I am trying to smoothen a scatter plot shown below using SciPy's B-spline representation of 1-D curve. The data is available here.

enter image description here

The code I used is:

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()

I tried changing the order of the spline and the smoothing condition, but I am not getting a smooth plot.

B-spline interpolation should be able to smoothen the data but what is wrong? Any alternate method to smoothen this data?

like image 579
Tom Kurushingal Avatar asked Jul 31 '26 22:07

Tom Kurushingal


2 Answers

Use a larger smoothing parameter. For example, s=1000:

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

This produces:

interpolation

like image 98
jme Avatar answered Aug 03 '26 12:08

jme


Assuming we are dealing with noisy observations of some phenomena, Gaussian Process Regression might also be a good choice. Knowledge about the variance of the noise can be included into the parameters (nugget) and other parameters can be found using Maximum Likelihood estimation. Here's a simple example of how it could be applied:

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()

which will give:

enter image description here

like image 23
Andrzej Pronobis Avatar answered Aug 03 '26 13:08

Andrzej Pronobis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!