hellowolrd
hellowolrd

Reputation: 391

Griddata predict method

With the griddata in scipy used to perform interpolation (cubic splines and others), we have to put as parameters the data from which we interpolate, and at the same time, the new points on which we want to make a "prediction".

Is it possible to construct a "griddata object", that would have a method to predict a new point without reconstructing a new interpolation spline each time... ? (for example, like with regression tree, we first construct the tree, then we aplly the .predict(new_points) method).

Here is an example :

import pandas as pd
import numpy as np
import sklearn
import scipy.interpolate as itp

n = 100
x1 = np.linspace(-2, 4, n)

X1 = []
X2 = []

for x in x1:
    X1.append( [x for i in range(0, n)] )
    X2.append( np.linspace(9, 15, n) )

X1 = np.array(X1).flatten()
X2 = np.array(X2).flatten()

Y1 = exp( 2*X1 )
    Y2 = 3 * sqrt(X2)

#Data frames :
X = np.transpose( [X1, X2] )
X = pd.DataFrame(X, columns=["X1", "X2"])

Y = np.transpose( [Y1, Y2] )
Y = pd.DataFrame(Y, columns=["Y1", "Y2"])

X_new = np.transpose( [[-2], [9]] )

inter_cubic = itp.griddata(X, Y, X_new, method='cubic', fill_value=nan, rescale=False)

print(inter_cubic)

print(exp(2*(-2)), 3*sqrt(9))

Now inter_cubic is just an numpy array..

Is there a way of performing it, or can we use another "spline" constructor?

Upvotes: 3

Views: 611

Answers (1)

Warren Weckesser
Warren Weckesser

Reputation: 114791

If you look at the source code for griddata (scroll down past the docstring to see the actual code), you'll see that it is a wrapper for several other interpolation functions, most of which work the way you want. In your case, with 2-d data and cubic interpolation, griddata does this:

        ip = CloughTocher2DInterpolator(points, values, fill_value=fill_value,
                                        rescale=rescale)
        return ip(xi)

So instead of using griddata, you could use CloughTocher2DInterpolator. Specifically, using the names from your script, you would create the interpolator with

ip = itp.CloughTocher2DInterpolator(X, Y, fill_value=np.nan, rescale=False)

The object ip doesn't have a predict method; you just call it with the points at which you want to evaluate the interpolator. In your case, your would write

Y_new = ip(X_new)

Upvotes: 2

Related Questions