{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from sklearn.preprocessing import LabelEncoder\n", "import pandas as pd\n", "import numpy as np\n", "# generate x feature encoder\n", "encX = LabelEncoder()\n", "encX.fit(['看電視', '讀書', '音樂', '游泳'])\n", "# generate y feature encoder\n", "ency = LabelEncoder()\n", "ency.fit(['是', '否'])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(encX.classes_) # '游泳' '看電視' '讀書' '音樂'分別會轉成0,1,2,3\n", "print(ency.classes_) # 否、是分別會轉成0,1" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "data_Xy = {'興趣': ['看電視', '讀書', '音樂', '看電視'], '成功與否': ['是', '否', '否', '是']}\n", "df = pd.DataFrame(data=data_Xy, index=['小明', '小林', '小英', '小陳'])\n", "df = df[['興趣', '成功與否']]\n", "df" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df_encode = df.copy()\n", "df_encode['興趣'] = encX.transform(df_encode['興趣'])\n", "df_encode['成功與否'] = ency.transform(df_encode['成功與否'])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df_encode" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "prediction = np.array([1, 0, 0, 1])\n", "df['prediction'] = ency.inverse_transform(prediction) # 將預測完的結果做反轉換\n", "df" ] } ], "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 }