Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to understand scipy and numpy interpolation

If I have some measured data whose function I don't know (let's say it's either not important, or computationally difficult), such as

x2 = [0, 1, 10, 25, 30]
y2 = [5, 12, 50, 73, 23]

and I use numpy.interp to find the intermediate values, it gives me a linear interpolant between the points and I get a straight line:

xinterp = np.arange(31)
yinterp1 = np.interp(xinterp, x2, y2)
plt.scatter(xinterp, yinterp1)
plt.plot(x2, y2, color = 'red', marker = '.')

enter image description here

The example from the scipy.interpolate docs gives

x = np.linspace(0, 10, num=11, endpoint=True)
y = np.cos(-x**2/9.0)
f = interp1d(x, y)
f2 = interp1d(x, y, kind='cubic')
xnew = np.linspace(0, 10, num=41, endpoint=True)
plt.plot(x, y, 'o', xnew, f(xnew), '-', xnew, f2(xnew), '--')
plt.legend(['data', 'linear', 'cubic'], loc='best')
plt.show()

enter image description here

with different kinds of interpolation for a smoother curve. But what if I want the points in a smooth curve, rather than just the curve? Is there a function in NumPy or SciPy that can give the discrete points along the smoothed curve?

like image 918
Jim421616 Avatar asked Sep 13 '17 22:09

Jim421616


People also ask

What is interpolation in Scipy?

Interpolation is a technique of constructing data points between given data points. The scipy. interpolate is a module in Python SciPy consisting of classes, spline functions, and univariate and multivariate interpolation classes.

Why interpolation is used in Python?

Interpolation is a method for generating points between given points. For example: for points 1 and 2, we may interpolate and find points 1.33 and 1.66. Interpolation has many usage, in Machine Learning we often deal with missing data in a dataset, interpolation is often used to substitute those values.

What does Scipy interpolate interp1d return?

This class returns a function whose call method uses interpolation to find the value of new points. A 1-D array of monotonically increasing real values. A N-D array of real values.


1 Answers

You can generate the function points and reassign them to a variable similarly to when you generated them and plotted them:

y_lin = f(xnew)
y_cub = f2(xnew)

interp1d returns you a function that you can then use to generate the data which in turns can be reassigned to other variables and used any way you want. Both outputs plotted together:

plt.plot(x, y, 'o', xnew, f(xnew), xnew, y_lin, '-', xnew, f2(xnew), xnew, y_cub, '--')
plt.legend(['data', 'linear' ,'reassigned linear', 'cubic', 'reassigned cubic'], loc='best')
plt.show()
like image 99
atru Avatar answered Sep 23 '22 06:09

atru