{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from sklearn import preprocessing\n", "import numpy as np" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a = np.array([[10, 2.7, 3.6, 5], [-100, 5, -2, 10], [120, 20, 40, 50]],\n", " dtype=np.float64)\n", "print(a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def normalize(x, axis, method, minmax_range=(0, 1)):\n", " if method == 'z-score':\n", " scale_a = preprocessing.scale(x, axis=axis)\n", " elif method == 'minmax':\n", " scale_a = preprocessing.minmax_scale(\n", " x, axis=axis,\n", " feature_range=minmax_range) # default feature range 0~1\n", " return scale_a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Z-Score" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# 改變axis,看看結果如何變化\n", "axis = 0\n", "scale_a = normalize(a, axis, method='z-score')\n", "print(scale_a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(scale_a.std(axis=axis))\n", "print(scale_a.mean(axis=axis))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Maxmin Scale" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# 改變axis,看看結果如何變化\n", "axis = 0\n", "# 改變minmax_range看看結果如何變化\n", "scale_a = normalize(a, axis, method='minmax', minmax_range=(0, 1))\n", "print(scale_a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(scale_a.max(axis=axis))\n", "print(scale_a.min(axis=axis))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.10.2" }, "toc": { "base_numbering": 1, "nav_menu": {}, "number_sections": true, "sideBar": true, "skip_h1_title": false, "title_cell": "Table of Contents", "title_sidebar": "Contents", "toc_cell": false, "toc_position": {}, "toc_section_display": true, "toc_window_display": false } }, "nbformat": 4, "nbformat_minor": 4 }