{ "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 LabelBinarizer as skLabelBinarizer" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "class LabelBinarizer():\n", " def __init__(self, pos_label=1, neg_label=0):\n", " self.pos_label = pos_label\n", " self.neg_label = neg_label\n", "\n", " def fit(self, y):\n", " self.classes_ = np.unique(y)\n", " return self\n", "\n", " def transform(self, y):\n", " y_enc = np.full((y.shape[0], len(self.classes_)), self.neg_label)\n", " for i, c in enumerate(self.classes_):\n", " y_enc[y == c, i] = self.pos_label\n", " if len(self.classes_) == 2:\n", " y_enc = y_enc[:, 1].reshape(-1, 1)\n", " return y_enc" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "iris = load_iris()" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "# binary\n", "y = iris.target\n", "y = y[y != 2]\n", "le1 = LabelBinarizer().fit(y)\n", "le2 = skLabelBinarizer().fit(y)\n", "assert np.array_equal(le1.classes_, le2.classes_)\n", "yt1 = le1.transform(y)\n", "yt2 = le2.transform(y)\n", "assert yt1.shape == (len(y), 1)\n", "assert np.array_equal(yt1, yt2)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "# numeric multiclass\n", "y = iris.target\n", "le1 = LabelBinarizer().fit(y)\n", "le2 = skLabelBinarizer().fit(y)\n", "assert np.array_equal(le1.classes_, le2.classes_)\n", "yt1 = le1.transform(y)\n", "yt2 = le2.transform(y)\n", "assert np.array_equal(yt1, yt2)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "# string multiclass\n", "y = iris.target_names[iris.target]\n", "le1 = LabelBinarizer().fit(y)\n", "le2 = skLabelBinarizer().fit(y)\n", "assert np.array_equal(le1.classes_, le2.classes_)\n", "yt1 = le1.transform(y)\n", "yt2 = le2.transform(y)\n", "assert np.array_equal(yt1, yt2)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "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.6.8" } }, "nbformat": 4, "nbformat_minor": 2 }