ml_knn
ml_knn(
x,
y,
newdata,
k,
regression=True,
what='prediction',
seed=None,
realizations=1000,
alpha=0.1,
)k-nearest-neighbors regression or classification.
Mirrors the C# KNearestNeighbors class: predicts from the k training rows closest to each new observation – an inverse-squared-distance weighted average of their responses for regression, or their most common response for classification.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| x | array_like | Training predictors, one row per observation. | required |
| y | array_like | The training response, one value per row of x. |
required |
| newdata | array_like | Predictors to predict for, with the same number of columns as x. |
required |
| k | int | The number of neighbors. | required |
| regression | bool | True for a weighted average; False for the modal class. |
True |
| what | ('prediction', 'neighbors', 'bootstrap', 'intervals') | Which result to return: the prediction (the default), the indices of each new observation’s neighbors, a prediction from one bootstrap resample of the training data, or bootstrapped prediction intervals. | "prediction" |
| seed | int | PRNG seed, used by "bootstrap" and "intervals"; None uses the clock. |
None |
| realizations | int | The number of bootstrap resamples for "intervals". |
1000 |
| alpha | float | The interval level for "intervals": 0.1 gives a 90% interval. |
0.1 |
Returns
| Name | Type | Description |
|---|---|---|
| numpy.ndarray | For "prediction" and "bootstrap", a 1-D array. For "neighbors", a 2-D array of 0-BASED training-row indices with one row per row of newdata and k columns. For "intervals", a 2-D array with four columns in the order lower, median, upper, mean – note "intervals" always reports percentiles, even for a classifier, because upstream has no classification branch there. |
Examples
>>> from corehydropy import ml_knn
>>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> y = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> float(ml_knn(x, y, newdata=[4.5], k=2)[0])
45.0