{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "from scipy.spatial.distance import cdist\n", "from sklearn.datasets import load_boston\n", "from sklearn.preprocessing import StandardScaler\n", "from sklearn.neighbors import KNeighborsRegressor as skKNeighborsRegressor" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Implementation 1\n", "- based on brute force\n", "- similar to scikit-learn algorithm='brute', weights='uniform'" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "class KNeighborsRegressor():\n", " def __init__(self, n_neighbors=5):\n", " self.n_neighbors = n_neighbors\n", "\n", " def fit(self, X, y):\n", " self._fit_X = X\n", " self._y = y\n", " return self\n", "\n", " def predict(self, X):\n", " dist_mat = cdist(X, self._fit_X)\n", " neigh_ind = np.argsort(dist_mat, axis=1)[:, :self.n_neighbors]\n", " return np.mean(self._y[neigh_ind], axis=1)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "X, y = load_boston(return_X_y=True)\n", "X = StandardScaler().fit_transform(X)\n", "clf1 = KNeighborsRegressor().fit(X, y)\n", "clf2 = skKNeighborsRegressor().fit(X, y)\n", "pred1 = clf1.predict(X)\n", "pred2 = clf2.predict(X)\n", "assert np.allclose(pred1, pred2)" ] } ], "metadata": { "kernelspec": { "display_name": "dev", "language": "python", "name": "dev" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.3" } }, "nbformat": 4, "nbformat_minor": 2 }