{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "from sklearn.datasets import load_iris\n", "from sklearn.preprocessing import KBinsDiscretizer as skKBinsDiscretizer" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "class KBinsDiscretizer():\n", " def __init__(self, n_bins=5, strategy=\"quantile\"):\n", " self.n_bins = n_bins\n", " self.strategy = strategy\n", "\n", " def fit(self, X):\n", " self.n_bins_ = np.full(X.shape[1], self.n_bins)\n", " self.bin_edges_ = np.empty(X.shape[1], dtype=object)\n", " for i in range(X.shape[1]):\n", " if self.strategy == \"uniform\":\n", " self.bin_edges_[i] = np.linspace(X[:, i].min(), X[:, i].max(),\n", " self.n_bins_[i] + 1)\n", " elif self.strategy == \"quantile\":\n", " quantiles = np.linspace(0, 100, self.n_bins_[i] + 1)\n", " self.bin_edges_[i] = np.percentile(X[:, i], quantiles)\n", " return self\n", "\n", " def transform(self, X):\n", " Xt = np.empty_like(X)\n", " for i in range(X.shape[1]):\n", " # similar to scikit-learn solution\n", " Xt[:, i] = np.digitize(X[:, i] + np.finfo(float).eps, self.bin_edges_[i][1:])\n", " Xt = np.clip(Xt, 0, self.n_bins_ - 1)\n", " return Xt" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "X, _ = load_iris(return_X_y=True)\n", "trans1 = KBinsDiscretizer(n_bins=5).fit(X)\n", "trans2 = skKBinsDiscretizer(n_bins=5, encode=\"ordinal\").fit(X)\n", "for i in range(X.shape[1]):\n", " assert np.allclose(trans1.bin_edges_[i], trans2.bin_edges_[i])\n", "Xt1 = trans1.transform(X)\n", "Xt2 = trans2.transform(X)\n", "assert np.array_equal(Xt1, Xt2)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "X, _ = load_iris(return_X_y=True)\n", "trans1 = KBinsDiscretizer(n_bins=5, strategy=\"uniform\").fit(X)\n", "trans2 = skKBinsDiscretizer(n_bins=5, encode=\"ordinal\", strategy=\"uniform\").fit(X)\n", "for i in range(X.shape[1]):\n", " assert np.allclose(trans1.bin_edges_[i], trans2.bin_edges_[i])\n", "Xt1 = trans1.transform(X)\n", "Xt2 = trans2.transform(X)\n", "assert np.array_equal(Xt1, Xt2)" ] } ], "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 }