verde.KNeighbors#
- class verde.KNeighbors(k=1, reduction=<function mean>)[source]#
Nearest neighbor interpolation.
This gridder assumes Cartesian coordinates.
Interpolation based on the values of the k nearest neighbors of each interpolated point. The number of neighbors k can be controlled and mostly influences the spatial smoothness of the interpolated values.
The data values of the k nearest neighbors are combined into a single value by a reduction function, which defaults to the mean. This can also be configured.
Note
If installed, package
pykdtreewill be used for the nearest neighbors look-up instead ofscipy.spatial.cKDTreefor better performance.- Parameters:
- k
int The number of neighbors to use for each interpolated point. Default is 1.
- reduction
function Function used to combine the values of the k neighbors into a single value. Can be any function that takes a 1D numpy array as input and outputs a single value. Default is
numpy.mean.
- k
- Attributes:
- tree_K-D
tree An instance of the K-D tree data structure for the data points that is used to query for nearest neighbors.
- data_1D
array A copy of the input data as a 1D array. Used to look up values for interpolation/prediction.
- region_
tuple The boundaries (
[W, E, S, N]) of the data used to fit the interpolator. Used as the default region for thegrid`method.
- tree_K-D
Methods
filter(coordinates, data[, weights])Filter the data through the gridder and produce residuals.
fit(coordinates, data[, weights])Fit the interpolator to the given data.
Get metadata routing of this object.
get_params([deep])Get parameters for this estimator.
grid([region, shape, spacing, dims, ...])Interpolate the data onto a regular grid.
predict(coordinates)Interpolate data on the given set of points.
profile(point1, point2, size[, dims, ...])Interpolate data along a profile between two points.
scatter([region, size, random_state, dims, ...])Interpolate values onto a random scatter of points.
score(coordinates, data[, weights])Score the gridder predictions against the given data.
set_fit_request(*[, coordinates, data, weights])Configure whether metadata should be requested to be passed to the
fitmethod.set_params(**params)Set the parameters of this estimator.
set_predict_request(*[, coordinates])Configure whether metadata should be requested to be passed to the
predictmethod.set_score_request(*[, coordinates, data, ...])Configure whether metadata should be requested to be passed to the
scoremethod.
Attributes#
- KNeighbors.data_names_defaults = [('scalars',), ('east_component', 'north_component'), ('east_component', 'north_component', 'vertical_component')]#
- KNeighbors.dims = ('northing', 'easting')#
- KNeighbors.extra_coords_name = 'extra_coord'#
Methods#
- KNeighbors.filter(coordinates, data, weights=None)#
Filter the data through the gridder and produce residuals.
Calls
fiton the data, evaluates the residuals (data - predicted data), and returns the coordinates, residuals, and weights.Not very useful by itself but this interface makes gridders compatible with other processing operations and is used by
verde.Chainto join them together (for example, so you can fit a spline on the residuals of a trend).- Parameters:
- coordinates
tupleofarrays Arrays with the coordinates of each data point. Should be in the following order: (easting, northing, vertical, …). For the specific definition of coordinate systems and what these names mean, see the class docstring.
- data
arrayortupleofarrays The data values of each data point. If the data has more than one component, data must be a tuple of arrays (one for each component).
- weights
Noneorarrayortupleofarrays If not None, then the weights assigned to each data point. If more than one data component is provided, you must provide a weights array for each data component (if not None).
- coordinates
- Returns:
coordinates,residuals,weightsThe coordinates and weights are same as the input. Residuals are the input data minus the predicted data.
- KNeighbors.fit(coordinates, data, weights=None)[source]#
Fit the interpolator to the given data.
The data region is captured and used as default for the
gridmethod.- Parameters:
- coordinates
tupleofarrays Arrays with the coordinates of each data point. Should be in the following order: (easting, northing, vertical, …). Only easting and northing will be used, all subsequent coordinates will be ignored.
- data
array The data values that will be interpolated.
- weights
Noneorarray Data weights are not supported by this interpolator and will be ignored. Only present for compatibility with other gridders.
- coordinates
- Returns:
selfReturns this gridder instance for chaining operations.
- KNeighbors.get_metadata_routing()#
Get metadata routing of this object.
Please check User Guide on how the routing mechanism works.
- Returns:
- routing
MetadataRequest A
MetadataRequestencapsulating routing information.
- routing
- KNeighbors.get_params(deep=True)#
Get parameters for this estimator.
- KNeighbors.grid(region=None, shape=None, spacing=None, dims=None, data_names=None, projection=None, coordinates=None, **kwargs)#
Interpolate the data onto a regular grid.
The grid can be specified by two methods:
Pass the actual coordinates of the grid points, as generated by
verde.grid_coordinatesor from an existingxarray.Datasetgrid.Let the method define a new grid by either passing the number of points in each dimension (the shape) or by the grid node spacing. If the interpolator collected the input data region, then it will be used if
region=None. Otherwise, you must specify the grid region. Seeverde.grid_coordinatesfor details. Other arguments forverde.grid_coordinatescan be passed as extra keyword arguments (kwargs) to this method.
Use the dims and data_names arguments to set custom names for the dimensions and the data field(s) in the output
xarray.Dataset. Default names will be provided if none are given.- Parameters:
- region
list= [W,E,S,N] The west, east, south, and north boundaries of a given region. Use only if
coordinatesis None.- shape
tuple= (n_north,n_east)orNone The number of points in the South-North and West-East directions, respectively. Use only if
coordinatesis None.- spacing
tuple= (s_north,s_east)orNone The grid spacing in the South-North and West-East directions, respectively. Use only if
coordinatesis None.- dims
listorNone The names of the northing and easting data dimensions, respectively, in the output grid. Default is determined from the
dimsattribute of the class. Must be defined in the following order: northing dimension, easting dimension. NOTE: This is an exception to the “easting” then “northing” pattern but is required for compatibility with xarray.- data_names
str,listorNone The name(s) of the data variables in the output grid. Defaults to
'scalars'for scalar data,['east_component', 'north_component']for 2D vector data, and['east_component', 'north_component', 'vertical_component']for 3D vector data.- projection
callableorNone If not None, then should be a callable object
projection(easting, northing) -> (proj_easting, proj_northing)that takes in easting and northing coordinate arrays and returns projected northing and easting coordinate arrays. This function will be used to project the generated grid coordinates before passing them intopredict. For example, you can use this to generate a geographic grid from a Cartesian gridder.- coordinates
tupleofarrays Tuple of arrays containing the coordinates of the grid in the following order: (easting, northing, vertical, …). The easting and northing arrays could be 1d or 2d arrays, if they are 2d they must be part of a meshgrid. If coordinates are passed,
region,shape, andspacingare ignored.
- region
- Returns:
- grid
xarray.Dataset The interpolated grid. Metadata about the interpolator is written to the
attrsattribute.
- grid
See also
verde.grid_coordinatesGenerate the coordinate values for the grid.
- KNeighbors.predict(coordinates)[source]#
Interpolate data on the given set of points.
Requires a fitted gridder (see
fit).- Parameters:
- coordinates
tupleofarrays Arrays with the coordinates of each data point. Should be in the following order: (easting, northing, vertical, …). Only easting and northing will be used, all subsequent coordinates will be ignored.
- coordinates
- Returns:
- data
array The data values interpolated on the given points.
- data
- KNeighbors.profile(point1, point2, size, dims=None, data_names=None, projection=None, **kwargs)#
Interpolate data along a profile between two points.
Generates the profile along a straight line assuming Cartesian distances. Point coordinates are generated by
verde.profile_coordinates. Other arguments for this function can be passed as extra keyword arguments (kwargs) to this method.Use the dims and data_names arguments to set custom names for the dimensions and the data field(s) in the output
pandas.DataFrame. Default names are provided.Includes the calculated Cartesian distance from point1 for each data point in the profile.
To specify point1 and point2 in a coordinate system that would require projection to Cartesian (geographic longitude and latitude, for example), use the
projectionargument. With this option, the input points will be projected using the given projection function prior to computations. The generated Cartesian profile coordinates will be projected back to the original coordinate system. Note that the profile points are evenly spaced in projected coordinates, not the original system (e.g., geographic).Warning
The profile calculation method with a projection has changed in Verde 1.4.0. Previous versions generated coordinates (assuming they were Cartesian) and projected them afterwards. This led to “distances” being incorrectly handled and returned in unprojected coordinates. For example, if
projectionis from geographic to Mercator, the distances would be “angles” (incorrectly calculated as if they were Cartesian). After 1.4.0, point1 and point2 are projected prior to generating coordinates for the profile, guaranteeing that distances are properly handled in a Cartesian system. With this change, the profile points are now evenly spaced in projected coordinates and the distances are returned in projected coordinates as well.- Parameters:
- point1
tuple The easting and northing coordinates, respectively, of the first point.
- point2
tuple The easting and northing coordinates, respectively, of the second point.
- size
int The number of points to generate.
- dims
listorNone The names of the northing and easting data dimensions, respectively, in the output dataframe. Default is determined from the
dimsattribute of the class. Must be defined in the following order: northing dimension, easting dimension. NOTE: This is an exception to the “easting” then “northing” pattern but is required for compatibility with xarray.- data_names
str,listorNone The name(s) of the data variables in the output dataframe. Defaults to
'scalars'for scalar data,['east_component', 'north_component']for 2D vector data, and['east_component', 'north_component', 'vertical_component']for 3D vector data.- projection
callableorNone If not None, then should be a callable object
projection(easting, northing, inverse=False) -> (proj_easting, proj_northing)that takes in easting and northing coordinate arrays and returns projected northing and easting coordinate arrays. Should also take an optional keyword argumentinverse(default to False) that if True will calculate the inverse transform instead. This function will be used to project the profile end points before generating coordinates and passing them intopredict. It will also be used to undo the projection of the coordinates before returning the results.
- point1
- Returns:
- table
pandas.DataFrame The interpolated values along the profile.
- table
- KNeighbors.scatter(region=None, size=300, random_state=0, dims=None, data_names=None, projection=None, **kwargs)#
Interpolate values onto a random scatter of points.
Point coordinates are generated by
verde.scatter_points. Other arguments for this function can be passed as extra keyword arguments (kwargs) to this method.If the interpolator collected the input data region, then it will be used if
region=None. Otherwise, you must specify the grid region.Use the dims and data_names arguments to set custom names for the dimensions and the data field(s) in the output
pandas.DataFrame. Default names are provided.Warning
The
scattermethod is deprecated and will be removed in Verde 2.0.0. Useverde.scatter_pointsand thepredictmethod instead.- Parameters:
- region
list= [W,E,S,N] The west, east, south, and north boundaries of a given region.
- size
int The number of points to generate.
- random_state
numpy.random.RandomStateoranintseed A random number generator used to define the state of the random permutations. Use a fixed seed to make sure computations are reproducible. Use
Noneto choose a seed automatically (resulting in different numbers with each run).- dims
listorNone The names of the northing and easting data dimensions, respectively, in the output dataframe. Default is determined from the
dimsattribute of the class. Must be defined in the following order: northing dimension, easting dimension. NOTE: This is an exception to the “easting” then “northing” pattern but is required for compatibility with xarray.- data_names
str,listorNone The name(s) of the data variables in the output dataframe. Defaults to
'scalars'for scalar data,['east_component', 'north_component']for 2D vector data, and['east_component', 'north_component', 'vertical_component']for 3D vector data.- projection
callableorNone If not None, then should be a callable object
projection(easting, northing) -> (proj_easting, proj_northing)that takes in easting and northing coordinate arrays and returns projected northing and easting coordinate arrays. This function will be used to project the generated scatter coordinates before passing them intopredict. For example, you can use this to generate a geographic scatter from a Cartesian gridder.
- region
- Returns:
- table
pandas.DataFrame The interpolated values on a random set of points.
- table
- KNeighbors.score(coordinates, data, weights=None)#
Score the gridder predictions against the given data.
Calculates the R^2 coefficient of determination of between the predicted values and the given data values. A maximum score of 1 means a perfect fit. The score can be negative.
Warning
The default scoring will change from R² to negative root mean squared error (RMSE) in Verde 2.0.0. This may change model selection results slightly. The negative version will be used to maintain the behaviour of larger scores being better, which is more compatible with current model selection code.
If the data has more than 1 component, the scores of each component will be averaged.
- Parameters:
- coordinates
tupleofarrays Arrays with the coordinates of each data point. Should be in the following order: (easting, northing, vertical, …). For the specific definition of coordinate systems and what these names mean, see the class docstring.
- data
arrayortupleofarrays The data values of each data point. If the data has more than one component, data must be a tuple of arrays (one for each component).
- weights
Noneorarrayortupleofarrays If not None, then the weights assigned to each data point. If more than one data component is provided, you must provide a weights array for each data component (if not None).
- coordinates
- Returns:
- score
float The R^2 score
- score
- KNeighbors.set_fit_request(*, coordinates: bool | None | str = '$UNCHANGED$', data: bool | None | str = '$UNCHANGED$', weights: bool | None | str = '$UNCHANGED$') KNeighbors#
Configure whether metadata should be requested to be passed to the
fitmethod.Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with
enable_metadata_routing=True(seesklearn.set_config). Please check the User Guide on how the routing mechanism works.The options for each parameter are:
True: metadata is requested, and passed tofitif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it tofit.None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (
sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.New in version 1.3.
- Parameters:
- coordinates
str,True,False,orNone, default=sklearn.utils.metadata_routing.UNCHANGED Metadata routing for
coordinatesparameter infit.- data
str,True,False,orNone, default=sklearn.utils.metadata_routing.UNCHANGED Metadata routing for
dataparameter infit.- weights
str,True,False,orNone, default=sklearn.utils.metadata_routing.UNCHANGED Metadata routing for
weightsparameter infit.
- coordinates
- Returns:
- self
object The updated object.
- self
- KNeighbors.set_params(**params)#
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as
Pipeline). The latter have parameters of the form<component>__<parameter>so that it’s possible to update each component of a nested object.- Parameters:
- **params
dict Estimator parameters.
- **params
- Returns:
- self
estimatorinstance Estimator instance.
- self
- KNeighbors.set_predict_request(*, coordinates: bool | None | str = '$UNCHANGED$') KNeighbors#
Configure whether metadata should be requested to be passed to the
predictmethod.Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with
enable_metadata_routing=True(seesklearn.set_config). Please check the User Guide on how the routing mechanism works.The options for each parameter are:
True: metadata is requested, and passed topredictif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it topredict.None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (
sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.New in version 1.3.
- KNeighbors.set_score_request(*, coordinates: bool | None | str = '$UNCHANGED$', data: bool | None | str = '$UNCHANGED$', weights: bool | None | str = '$UNCHANGED$') KNeighbors#
Configure whether metadata should be requested to be passed to the
scoremethod.Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with
enable_metadata_routing=True(seesklearn.set_config). Please check the User Guide on how the routing mechanism works.The options for each parameter are:
True: metadata is requested, and passed toscoreif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it toscore.None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (
sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.New in version 1.3.
- Parameters:
- coordinates
str,True,False,orNone, default=sklearn.utils.metadata_routing.UNCHANGED Metadata routing for
coordinatesparameter inscore.- data
str,True,False,orNone, default=sklearn.utils.metadata_routing.UNCHANGED Metadata routing for
dataparameter inscore.- weights
str,True,False,orNone, default=sklearn.utils.metadata_routing.UNCHANGED Metadata routing for
weightsparameter inscore.
- coordinates
- Returns:
- self
object The updated object.
- self