|
117 | 117 |
|
118 | 118 | titanic = fetch_openml('titanic', version=1, as_frame=True)
|
119 | 119 | print(titanic.data.head()[['pclass', 'embarked']])
|
| 120 | + |
| 121 | +############################################################################ |
| 122 | +# Precomputed sparse nearest neighbors graph |
| 123 | +# ------------------------------------------ |
| 124 | +# Most estimators based on nearest neighbors graphs now accept precomputed |
| 125 | +# sparse graphs as input, to reuse the same graph for multiple estimator fits. |
| 126 | +# To use this feature in a pipeline, one can use the `memory` parameter, along |
| 127 | +# with one of the two new transformers, |
| 128 | +# :class:`~sklearn.neighbors.KNeighborsTransformer` and |
| 129 | +# :class:`~sklearn.neighbors.RadiusNeighborsTransformer`. The precomputation |
| 130 | +# can also be performed by custom estimators to use alternative |
| 131 | +# implementations, such as approximate nearest neighbors methods. |
| 132 | +# See more details in the :ref:`User Guide <neighbors_transformer>`. |
| 133 | + |
| 134 | +from sklearn.neighbors import KNeighborsTransformer |
| 135 | +from sklearn.manifold import Isomap |
| 136 | +from sklearn.pipeline import make_pipeline |
| 137 | + |
| 138 | +estimator = make_pipeline( |
| 139 | + KNeighborsTransformer(n_neighbors=10, mode='distance'), |
| 140 | + Isomap(n_neighbors=10, metric='precomputed'), |
| 141 | + memory='.') |
| 142 | +estimator.fit(X) |
| 143 | + |
| 144 | +# We can decrease the number of neighbors and the graph will not be recomputed. |
| 145 | +estimator.set_params(isomap__n_neighbors=5) |
| 146 | +estimator.fit(X) |
0 commit comments