{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# 下載 myfun.py\n", "!wget \"https://raw.githubusercontent.com/TA-aiacademy/course_3.0/ML/02_ML/part3/Chapter3/myfun.py\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import pandas as pd\n", "\n", "from sklearn.datasets import make_blobs\n", "from sklearn.neighbors import KNeighborsClassifier\n", "from myfun import plot_decision_regions\n", "\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "\n", "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 調整K觀察結果" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# make 3-class dataset for classification\n", "centers = [[0, 0], [3.5, 0]]\n", "X, y = make_blobs(n_samples=100, centers=centers, random_state=40)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "color = \"rb\"\n", "color = [color[y[i]] for i in range(len(y))]\n", "plt.scatter(X[:, 0], X[:, 1], c=color)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def knn_example(plot_dict, X, y, k):\n", " # create model\n", " model = KNeighborsClassifier(n_neighbors=k)\n", "\n", " # training\n", " model.fit(X, y)\n", "\n", " # Plot the decision boundary. For that, we will assign a color to each\n", " if k in plot_dict:\n", " plt.subplot(plot_dict[k])\n", " plt.tight_layout()\n", " plot_decision_regions(X, y, model)\n", " plt.title('Plot for K: %d' % k)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plt.figure(figsize=(8.5, 6))\n", "\n", "# 調整 K\n", "plot_dict = {1: 231, 2: 232, 3: 233, 4: 234, 5: 235, 6: 236}\n", "for i in plot_dict:\n", " knn_example(plot_dict, X, y, i)" ] }, { "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 }