{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from scipy.stats import mode\n",
    "from scipy.spatial.distance import cdist\n",
    "from sklearn.datasets import load_breast_cancer\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "from sklearn.neighbors import KNeighborsClassifier as skKNeighborsClassifier"
   ]
  },
  {
   "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 KNeighborsClassifier():\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.classes_, self._y = np.unique(y, return_inverse=True)\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 self.classes_[mode(self._y[neigh_ind], axis=1)[0].ravel()]\n",
    "\n",
    "    def predict_proba(self, X):\n",
    "        dist_mat = cdist(X, self._fit_X)\n",
    "        neigh_ind = np.argsort(dist_mat, axis=1)[:, :self.n_neighbors]\n",
    "        proba = np.zeros((X.shape[0], len(self.classes_)))\n",
    "        pred_labels = self._y[neigh_ind]\n",
    "        for idx in pred_labels.T:\n",
    "            proba[np.arange(X.shape[0]), idx] += 1\n",
    "        proba /= np.sum(proba, axis=1)[:, np.newaxis]\n",
    "        return proba"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "X, y = load_breast_cancer(return_X_y=True)\n",
    "X = StandardScaler().fit_transform(X)\n",
    "clf1 = KNeighborsClassifier().fit(X, y)\n",
    "clf2 = skKNeighborsClassifier().fit(X, y)\n",
    "prob1 = clf1.predict_proba(X)\n",
    "prob2 = clf2.predict_proba(X)\n",
    "assert np.allclose(prob1, prob2)\n",
    "pred1 = clf1.predict(X)\n",
    "pred2 = clf2.predict(X)\n",
    "assert np.array_equal(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
}