{ "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 Normalizer as skNormalizer" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "class Normalizer():\n", " def __init__(self, norm='l2'):\n", " self.norm = norm\n", "\n", " def fit(self, X):\n", " return self\n", "\n", " def transform(self, X):\n", " if norm == 'l1':\n", " norms = np.sum(np.abs(X), axis=1)\n", " elif norm == 'l2':\n", " norms = np.sqrt(np.sum(np.square(X), axis=1))\n", " elif norm == 'max':\n", " norms = np.max(X, axis=1)\n", " return X / norms[:, np.newaxis]" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "X, _ = load_iris(return_X_y=True)\n", "for norm in ['l1', 'l2', 'max']:\n", " sc1 = Normalizer(norm=norm).fit(X)\n", " sc2 = skNormalizer(norm=norm).fit(X)\n", " Xt1 = sc1.transform(X)\n", " Xt2 = sc2.transform(X)\n", " assert np.allclose(Xt1, Xt2)" ] } ], "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.7.3" } }, "nbformat": 4, "nbformat_minor": 2 }