{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "source": [
        "コードA.1■dict型"
      ],
      "metadata": {
        "id": "30T9T0LScweW"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# dict型データの初期化\n",
        "fruits_dict = {'apple': 110, 'orange': 80, 'banana': 30,\n",
        "               'peach': 200}"
      ],
      "metadata": {
        "id": "wbkfSF05cZ08"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# dict型データの読み出し\n",
        "print(fruits_dict['orange']) # 80"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "k1lpd2XEd-xt",
        "outputId": "8d0c03b8-08ce-4f94-b756-f334b11caea1"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "80\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# dict型データのvalueの更新\n",
        "fruits_dict['orange'] = 75\n",
        "print(fruits_dict['orange']) # 75"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "iBz0GZKrd_H6",
        "outputId": "d2aebe11-00c5-4711-f8f4-f2861d605338"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "75\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# dict型データのkey,valueペアを削除\n",
        "del fruits_dict['apple']\n",
        "print(fruits_dict) # {'orange': 75, 'banana': 30, 'peach': 200}"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "IA_2URcfd_V9",
        "outputId": "4dd84db0-08d0-48d8-d9fa-e895061c126d"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "{'orange': 75, 'banana': 30, 'peach': 200}\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# dict型データのkey,valueペアを追加\n",
        "fruits_dict['melon'] = 600\n",
        "print(fruits_dict)\n",
        "# {'orange': 75, 'banana': 30, 'peach': 200, 'melon': 600}"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "OfYtvAvxd_qH",
        "outputId": "14e2ab95-cd84-4c4b-8982-8d4bc92a2aa5"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "{'orange': 75, 'banana': 30, 'peach': 200, 'melon': 600}\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "コードA.2■1次元配列"
      ],
      "metadata": {
        "id": "eEAqhyNBdMpg"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import numpy as np\n",
        "# ベクトルa,bを定義\n",
        "a = np.array([4, 5])\n",
        "b = np.array([2, 3])"
      ],
      "metadata": {
        "id": "07C0LpQCdR9r"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# ベクトルの和\n",
        "print(a + b)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "hLOJ_tmCePRN",
        "outputId": "c62ec9ec-ae0f-460f-dd94-f2d6eee4f4db"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "[6 8]\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# 成分ごとの積を成分とするベクトルを出力\n",
        "print(a * b)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "c_Ig6XcLePiN",
        "outputId": "896de596-844c-4380-a164-79f74133b30e"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "[ 8 15]\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# 内積\n",
        "print(np.dot(a, b))"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "fF-toWyXePyn",
        "outputId": "14b504e0-0517-4b66-e84d-1b1d2a22024c"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "23\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "コードA.3■2次元配列"
      ],
      "metadata": {
        "id": "f1Hk3sDldk-m"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import numpy as np\n",
        "# 2次元の配列を定義\n",
        "C = np.array([[0, 1, 2], [3, 4, 5]])\n",
        "print(C)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "_RYlyddRdokb",
        "outputId": "72fb87eb-8651-4684-eef1-9cfd82460b1d"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "[[0 1 2]\n",
            " [3 4 5]]\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# 0番目，1番目の要素を表示\n",
        "print(C[0]) # [0 1 2]\n",
        "print(C[1]) # [3 4 5]"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "KI9y9nhDeZjV",
        "outputId": "8907ddf7-f0e0-463a-80cd-a6e644a4735a"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "[0 1 2]\n",
            "[3 4 5]\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# 1番目の要素の2番目の成分を表示\n",
        "print(C[1, 2]) # 5"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "1rTcNGGHeZR1",
        "outputId": "376dd4e6-67c2-466a-c1f3-e6e685e45445"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "5\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# 1列目の全行を表示(:は全てを意味する)\n",
        "print(C[:, 1]) # [1 4]"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "yigosCrneZJi",
        "outputId": "a27cbd01-c2eb-4b09-8f69-8d136f48061d"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "[1 4]\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# 行列の形状を表示\n",
        "print(C.shape) # (2, 3)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "ND4AgFy-eYqs",
        "outputId": "0a2ca6fe-5787-4bb5-84b2-a92a6f09929e"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "(2, 3)\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# 成分のデータ型を表示\n",
        "print(C.dtype) # int64"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "HNRWQtjReXkS",
        "outputId": "377adf13-2a15-4910-c846-65ca9a172795"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "int64\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "コードA.4■行列の積"
      ],
      "metadata": {
        "id": "lk4huITjejmV"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import numpy as np\n",
        "# 配列で2×3行列と3×2行列を表現\n",
        "C = np.array([[0, 1, 2], [3, 4, 5]])\n",
        "D = np.array([[0, 1], [2, 3],[4, 5]])"
      ],
      "metadata": {
        "id": "JPjMJfoNei9j"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# 積の計算\n",
        "E = np.dot(C, D)\n",
        "F = np.dot(D, C)\n",
        "print(E)\n",
        "# [[10 13]\n",
        "#  [28 40]]"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "IYvR1-aJe1Z3",
        "outputId": "6ec838e5-8bbf-4e5b-dd61-cd0f45c50acf"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "[[10 13]\n",
            " [28 40]]\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "print(F)\n",
        "# [[ 3  4  5]\n",
        "#  [ 9 14 19]\n",
        "#  [15 24 33]]"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "22CJi4mme1Lr",
        "outputId": "520b6037-5504-40f0-e8b1-77d4bc0ee2df"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "[[ 3  4  5]\n",
            " [ 9 14 19]\n",
            " [15 24 33]]\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "コードA.5■等差数列"
      ],
      "metadata": {
        "id": "j_YqRQInfZwf"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import numpy as np\n",
        "# 等差数列の生成\n",
        "G = np.arange(1, 10, 2)\n",
        "print(G) # [1 3 5 7 9]"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "QxNAIKevfeLb",
        "outputId": "8be5a591-5601-413c-9b88-8a7117bc8d5c"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "[1 3 5 7 9]\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# 等差数列の生成（初項，間隔を省略）\n",
        "H = np.arange(10)\n",
        "print(H) # [0 1 2 3 4 5 6 7 8 9]"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "yYOp8ssxfkFk",
        "outputId": "0da1fa1f-a180-420e-a429-366b6b454ea6"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "[0 1 2 3 4 5 6 7 8 9]\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# 等差数列の生成（間隔を省略）\n",
        "I = np.arange(5, 10)\n",
        "print(I) # [5 6 7 8 9]"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "2d2r-BECfj8C",
        "outputId": "9f0216d5-65fd-45f2-e797-9feb9486582b"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "[5 6 7 8 9]\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "コードA.6■乱数"
      ],
      "metadata": {
        "id": "gkJNdAJhfzwk"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import numpy as np\n",
        "import matplotlib.pyplot as plt\n",
        "# シードを指定すると毎回同じ乱数を生成する\n",
        "np.random.seed(42)\n",
        "# 0以上1未満の乱数を4個生成し配列を生成\n",
        "J = np.random.rand(4)\n",
        "print(J)"
      ],
      "metadata": {
        "id": "453tLRGcf3LC",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "ee31c206-df79-49b6-e170-548e7c8be484"
      },
      "execution_count": 1,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "[0.37454012 0.95071431 0.73199394 0.59865848]\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# 0以上1未満の乱数を1000000個生成しヒストグラムを表示\n",
        "K = np.random.rand(1000000)# 300分割してヒストグラムを生成\n",
        "plt.hist(K, bins=300)\n",
        "plt.show()"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 265
        },
        "id": "0Lk2BQvT_hcs",
        "outputId": "753cab99-2a10-4daf-fd0c-e6e1b80d9b43"
      },
      "execution_count": 2,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<Figure size 432x288 with 1 Axes>"
            ],
            "image/png": "[encoded data, 7320 characters]\n"
          },
          "metadata": {
            "needs_background": "light"
          }
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# 標準正規分布の乱数を1000000個生成しヒストグラムを表示\n",
        "L = np.random.randn(1000000)\n",
        "# 300分割してヒストグラムを生成\n",
        "plt.hist(L, bins=300)\n",
        "plt.show()"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 265
        },
        "id": "t2ypzFu6_hID",
        "outputId": "7e28ab72-b739-4415-e313-3be507839f13"
      },
      "execution_count": 3,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<Figure size 432x288 with 1 Axes>"
            ],
            "image/png": "[encoded data, 6640 characters]\n"
          },
          "metadata": {
            "needs_background": "light"
          }
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# 0以上1未満の乱数で2×300の配列を生成\n",
        "M = np.random.rand(2, 300)# 0以上1未満の乱数を座標として散布図作成\n",
        "X = M[0]\n",
        "Y = M[1]\n",
        "plt.scatter(X, Y)\n",
        "plt.show()"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 265
        },
        "id": "EkwTrisF_hB5",
        "outputId": "6a90e036-d10a-4582-c57d-2761c4302c52"
      },
      "execution_count": 4,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<Figure size 432x288 with 1 Axes>"
            ],
            "image/png": "[encoded data, 16520 characters]\n"
          },
          "metadata": {
            "needs_background": "light"
          }
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# 標準正規分布乱数を座標として散布図作成\n",
        "N = np.random.randn(2, 300)\n",
        "X = N[0]\n",
        "Y = N[1]\n",
        "plt.scatter(X, Y)\n",
        "plt.show()"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 265
        },
        "id": "ZKnPpjsU_fYC",
        "outputId": "5a282e9e-5dfe-407d-e97b-2ecab07ad0f8"
      },
      "execution_count": 5,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<Figure size 432x288 with 1 Axes>"
            ],
            "image/png": "[encoded data, 14928 characters]\n"
          },
          "metadata": {
            "needs_background": "light"
          }
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "コードA.7■pd.DataFrame"
      ],
      "metadata": {
        "id": "WJ_Tsps4AIwt"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import pandas as pd\n",
        "# dict型データ（valueはリスト）をDataFrameに読み込ませる\n",
        "df_pref = pd.DataFrame({'pref': ['Yamanashi','Kanagawa','Aichi'],\n",
        "                        'city':['Kofu','Yokohama','Nagoya'],\n",
        "                        'item':[18, 21, 8]})\n",
        "# DataFrameの先頭5行までを表示（ここでは3行すべてを表示）\n",
        "print(df_pref.head())\n",
        "#         pref      city  item\n",
        "# 0  Yamanashi      Kofu    18\n",
        "# 1   Kanagawa  Yokohama    21\n",
        "# 2      Aichi    Nagoya     8"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "LOsIY6bMAPV0",
        "outputId": "8fc45260-e2ec-40ce-9d1d-e7de4601b6dd"
      },
      "execution_count": 7,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "        pref      city  item\n",
            "0  Yamanashi      Kofu    18\n",
            "1   Kanagawa  Yokohama    21\n",
            "2      Aichi    Nagoya     8\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "コードA.8■DataFrameの表示"
      ],
      "metadata": {
        "id": "yYLVmJSzA6FW"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import pandas as pd\n",
        "# csvファイルをDataFrameに読み込ませる\n",
        "df_iris = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv')\n",
        "# DataFrameの先頭5行までを表示\n",
        "print(df_iris.head())\n",
        "#    sepal_length  sepal_width  petal_length  petal_width species\n",
        "# 0           5.1          3.5           1.4          0.2  setosa\n",
        "# 1           4.9          3.0           1.4          0.2  setosa\n",
        "# 2           4.7          3.2           1.3          0.2  setosa\n",
        "# 3           4.6          3.1           1.5          0.2  setosa\n",
        "# 4           5.0          3.6           1.4          0.2  setosa"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "FOWVce0GA5Tr",
        "outputId": "bbdc4a32-1fdf-43ad-f2f3-1f40781b9e7d"
      },
      "execution_count": 13,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "   sepal_length  sepal_width  petal_length  petal_width species\n",
            "0           5.1          3.5           1.4          0.2  setosa\n",
            "1           4.9          3.0           1.4          0.2  setosa\n",
            "2           4.7          3.2           1.3          0.2  setosa\n",
            "3           4.6          3.1           1.5          0.2  setosa\n",
            "4           5.0          3.6           1.4          0.2  setosa\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# index（項番）のstart，end，step\n",
        "print(df_iris.index)\n",
        "# RangeIndex(start=0, stop=150, step=1)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "K0MJS2LcCPhm",
        "outputId": "8cf51c33-4249-41dc-a80b-a8da69b6589c"
      },
      "execution_count": 14,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "RangeIndex(start=0, stop=150, step=1)\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# column（列名）の一覧\n",
        "print(df_iris.columns)\n",
        "# Index(['sepal length', 'sepal width', 'petal length', 'petal width',\n",
        "#        'species'],\n",
        "#       dtype='object')"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "5fQqXZjsCPRQ",
        "outputId": "cbb76762-4696-4c0a-9452-74831b76e9e9"
      },
      "execution_count": 15,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Index(['sepal_length', 'sepal_width', 'petal_length', 'petal_width',\n",
            "       'species'],\n",
            "      dtype='object')\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# iloc で特定のindex の行・列のデータだけ抽出\n",
        "print(df_iris.iloc[:,[0,2]])\n",
        "#      sepal_length  petal_length\n",
        "# 0             5.1           1.4\n",
        "# 1             4.9           1.4\n",
        "# 2             4.7           1.3\n",
        "# 3             4.6           1.5\n",
        "# 4             5.0           1.4\n",
        "# ..            ...           ...\n",
        "# 145           6.7           5.2\n",
        "# 146           6.3           5.0\n",
        "# 147           6.5           5.2\n",
        "# 148           6.2           5.4\n",
        "# 149           5.9           5.1\n",
        "#\n",
        "# [150 rows x 2 columns]"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "Fhgou3EuCOSO",
        "outputId": "1f334753-7315-428c-bf1d-1fdd1591f0e2"
      },
      "execution_count": 18,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "     sepal_length  petal_length\n",
            "0             5.1           1.4\n",
            "1             4.9           1.4\n",
            "2             4.7           1.3\n",
            "3             4.6           1.5\n",
            "4             5.0           1.4\n",
            "..            ...           ...\n",
            "145           6.7           5.2\n",
            "146           6.3           5.0\n",
            "147           6.5           5.2\n",
            "148           6.2           5.4\n",
            "149           5.9           5.1\n",
            "\n",
            "[150 rows x 2 columns]\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "コードA.9■DataFrameからの描画"
      ],
      "metadata": {
        "id": "JDJa6sMVEFM2"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import pandas as pd\n",
        "import matplotlib.pyplot as plt\n",
        "# 描画領域を作成\n",
        "plt.figure()\n",
        "# csvファイルをDataFrameに読み込ませる\n",
        "df_iris = pd.read_csv(\n",
        "'https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv'\n",
        ")\n",
        "# x,y座標の列を指定しsetosa個体を四角形でプロット\n",
        "ax1 = df_iris.loc[df_iris['species'] == 'setosa'].plot(kind='scatter',x='petal_length',y='sepal_length',marker='s')\n",
        "# x,y座標の列を指定しversicolor個体を三角形でプロット\n",
        "df_iris.loc[df_iris['species'] == 'versicolor'].plot(kind='scatter',x='petal_length',y='sepal_length',marker='^',\n",
        "ax = ax1)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 315
        },
        "id": "bddF7emcD4hI",
        "outputId": "666aef3c-6059-4a0f-b691-577d155ebbd8"
      },
      "execution_count": 34,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<matplotlib.axes._subplots.AxesSubplot at 0x7f2ac814f150>"
            ]
          },
          "metadata": {},
          "execution_count": 34
        },
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<Figure size 432x288 with 0 Axes>"
            ]
          },
          "metadata": {}
        },
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<Figure size 432x288 with 1 Axes>"
            ],
            "image/png": "[encoded data, 9196 characters]\n"
          },
          "metadata": {
            "needs_background": "light"
          }
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "コードA.10■SymPyでベクトルを扱う"
      ],
      "metadata": {
        "id": "8dKNj1lBHNmv"
      }
    },
    {
      "cell_type": "code",
      "execution_count": 35,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 78
        },
        "id": "8_lP1NJLdggJ",
        "outputId": "87eb7836-f9c1-499f-ac84-127622548163"
      },
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "Matrix([\n",
              "[a1],\n",
              "[a2],\n",
              "[a3]])"
            ],
            "text/latex": "$\\displaystyle \\left[\\begin{matrix}a_{1}\\\\a_{2}\\\\a_{3}\\end{matrix}\\right]$"
          },
          "metadata": {}
        }
      ],
      "source": [
        "import sympy as sym\n",
        "import numpy as np\n",
        "a1, a2, a3 = sym.symbols('a1 a2 a3', real=True)\n",
        "a = sym.Matrix([a1, a2, a3])\n",
        "b = sym.Matrix([1, 2, 3])\n",
        "display(a)"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "display(b)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 78
        },
        "id": "EgwxIUaLHfYt",
        "outputId": "21d1a35e-c9d0-473a-b29d-a8805d0a573e"
      },
      "execution_count": 36,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "Matrix([\n",
              "[1],\n",
              "[2],\n",
              "[3]])"
            ],
            "text/latex": "$\\displaystyle \\left[\\begin{matrix}1\\\\2\\\\3\\end{matrix}\\right]$"
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "display(a + b)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 78
        },
        "id": "rd8EL9lrHfSn",
        "outputId": "e58b482e-7030-459f-97e8-4b55708e3ab0"
      },
      "execution_count": 37,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "Matrix([\n",
              "[a1 + 1],\n",
              "[a2 + 2],\n",
              "[a3 + 3]])"
            ],
            "text/latex": "$\\displaystyle \\left[\\begin{matrix}a_{1} + 1\\\\a_{2} + 2\\\\a_{3} + 3\\end{matrix}\\right]$"
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "display(a - b)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 78
        },
        "id": "C6n9NX9dHfLJ",
        "outputId": "ebac7c85-5387-4a6d-b642-fd69265a6efe"
      },
      "execution_count": 38,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "Matrix([\n",
              "[a1 - 1],\n",
              "[a2 - 2],\n",
              "[a3 - 3]])"
            ],
            "text/latex": "$\\displaystyle \\left[\\begin{matrix}a_{1} - 1\\\\a_{2} - 2\\\\a_{3} - 3\\end{matrix}\\right]$"
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "display(a.norm()) #ベクトルaの大きさ"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 48
        },
        "id": "prUIr3IVHe-K",
        "outputId": "1e15dc51-0539-40cd-fd22-29ff1d4be970"
      },
      "execution_count": 39,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "sqrt(a1**2 + a2**2 + a3**2)"
            ],
            "text/latex": "$\\displaystyle \\sqrt{a_{1}^{2} + a_{2}^{2} + a_{3}^{2}}$"
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "display(b.norm()) #ベクトルbの大きさ"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 39
        },
        "id": "UDFIFnqpHeu2",
        "outputId": "ac3ce0ae-391e-4506-c771-c53ceec202a0"
      },
      "execution_count": 40,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "sqrt(14)"
            ],
            "text/latex": "$\\displaystyle \\sqrt{14}$"
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "display((a-b).norm()) #ベクトルa,b間の距離"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 48
        },
        "id": "do4fzZ91ePkS",
        "outputId": "07179bda-e572-4c0f-9f80-32d62d486253"
      },
      "execution_count": 41,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "sqrt((a1 - 1)**2 + (a2 - 2)**2 + (a3 - 3)**2)"
            ],
            "text/latex": "$\\displaystyle \\sqrt{\\left(a_{1} - 1\\right)^{2} + \\left(a_{2} - 2\\right)^{2} + \\left(a_{3} - 3\\right)^{2}}$"
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "display(a.dot(b))  #ベクトルa,bの内積"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 39
        },
        "id": "oRocr4uVepKa",
        "outputId": "51ca9d19-7c7d-43a3-e7ab-05cb0650c443"
      },
      "execution_count": 42,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "a1 + 2*a2 + 3*a3"
            ],
            "text/latex": "$\\displaystyle a_{1} + 2 a_{2} + 3 a_{3}$"
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "display(sym.sqrt(b.dot(b)))  #ベクトルbの大きさ"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 39
        },
        "id": "7kOA-wLTeXK4",
        "outputId": "20ca5719-8646-4caa-f43f-0444efd7ac86"
      },
      "execution_count": 43,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "sqrt(14)"
            ],
            "text/latex": "$\\displaystyle \\sqrt{14}$"
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "print(np.sqrt(float(b.dot(b))))  #ベクトルbの大きさ"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "Wy_pIXXyf4SD",
        "outputId": "1c046d4e-c2fe-4c53-adad-a93559865fd7"
      },
      "execution_count": 44,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "3.7416573867739413\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "コードA.11■行列の積（第2章の例2.3）"
      ],
      "metadata": {
        "id": "ZYOEUUPUH8v0"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import sympy as sym\n",
        "from IPython.display import Math, display\n",
        "# 変数を定義\n",
        "(x, y, p, q) = sym.symbols(\"x y p q\")\n",
        "# 行列を定義\n",
        "A = sym.Matrix([\n",
        "    [2, 1],\n",
        "    [3, 4]\n",
        "])\n",
        "display((Math(f\"A={sym.latex(A)}\")))"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 58
        },
        "id": "zfp6FtIngxBl",
        "outputId": "a815bb60-d9d0-46be-e03b-749a76f4caca"
      },
      "execution_count": 45,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<IPython.core.display.Math object>"
            ],
            "text/latex": "$\\displaystyle A=\\left[\\begin{matrix}2 & 1\\\\3 & 4\\end{matrix}\\right]$"
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "B = sym.Matrix([\n",
        "    [-2, 1],\n",
        "    [3, -4],\n",
        "])\n",
        "display((Math(f\"B={sym.latex(B)}\")))"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 58
        },
        "id": "bf-LQtojIN3m",
        "outputId": "1c4f5e4c-5150-4501-899d-94d745f6e7ba"
      },
      "execution_count": 46,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<IPython.core.display.Math object>"
            ],
            "text/latex": "$\\displaystyle B=\\left[\\begin{matrix}-2 & 1\\\\3 & -4\\end{matrix}\\right]$"
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "C = sym.Matrix([\n",
        "    [5, x],\n",
        "    [5*x, 3],\n",
        "    [4, 0]\n",
        "])\n",
        "display((Math(f\"C={sym.latex(C)}\")))"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 78
        },
        "id": "3pG1KQUsINlV",
        "outputId": "2c17d013-652f-44f6-e75b-fbc024662a31"
      },
      "execution_count": 47,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<IPython.core.display.Math object>"
            ],
            "text/latex": "$\\displaystyle C=\\left[\\begin{matrix}5 & x\\\\5 x & 3\\\\4 & 0\\end{matrix}\\right]$"
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "#行列どうしの掛け算\n",
        "AB = A * B\n",
        "display((Math(f\"AB={sym.latex(AB)}\")))"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 58
        },
        "id": "54j6QJX2INb8",
        "outputId": "f269afb8-f3d9-4462-c4dd-8fa4d0a239d9"
      },
      "execution_count": 48,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<IPython.core.display.Math object>"
            ],
            "text/latex": "$\\displaystyle AB=\\left[\\begin{matrix}-1 & -2\\\\6 & -13\\end{matrix}\\right]$"
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "CA = C * A\n",
        "display((Math(f\"CA={sym.latex(CA)}\")))"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 78
        },
        "id": "9H4AmIKnINKJ",
        "outputId": "6ee7e3fd-72b3-427d-e41a-5e14b03b766c"
      },
      "execution_count": 49,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<IPython.core.display.Math object>"
            ],
            "text/latex": "$\\displaystyle CA=\\left[\\begin{matrix}3 x + 10 & 4 x + 5\\\\10 x + 9 & 5 x + 12\\\\8 & 4\\end{matrix}\\right]$"
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "CAB = C * A * B\n",
        "display((Math(f\"CAB={sym.latex(CAB)}\")))"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 78
        },
        "id": "lz3eO2EnIL2O",
        "outputId": "d878fbbd-0880-41c7-8463-7c59e4cbd865"
      },
      "execution_count": 50,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<IPython.core.display.Math object>"
            ],
            "text/latex": "$\\displaystyle CAB=\\left[\\begin{matrix}6 x - 5 & - 13 x - 10\\\\18 - 5 x & - 10 x - 39\\\\-4 & -8\\end{matrix}\\right]$"
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "コードA.12■指数関数，対数関数のグラフ"
      ],
      "metadata": {
        "id": "BDWfeK40Ih1w"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import sympy as sym\n",
        "x = sym.symbols('x')\n",
        "f = sym.exp(x)\n",
        "g = sym.log(x)\n",
        "p1 = sym.plot(f, xlim=(-2.2,2.2), ylim=(0,8.5), \n",
        "              ylabel = \"f(x)=exp(x)\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 297
        },
        "id": "3tzmxYpniEzA",
        "outputId": "ba664a6f-633a-49ac-baea-89ab889a6820"
      },
      "execution_count": 51,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<Figure size 432x288 with 1 Axes>"
            ],
            "image/png": "[encoded data, 14472 characters]\n"
          },
          "metadata": {
            "needs_background": "light"
          }
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "p2 = sym.plot(g, xlim=(-1.0, 4.0), ylim=(-2,2),\n",
        "              ylabel = \"g(x)=log(x)\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 297
        },
        "id": "p2UPAqY7Iygq",
        "outputId": "42a93cf3-9d90-4968-ebc1-08e2b2f6402f"
      },
      "execution_count": 54,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<Figure size 432x288 with 1 Axes>"
            ],
            "image/png": "[encoded data, 14760 characters]\n"
          },
          "metadata": {
            "needs_background": "light"
          }
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "コードA.13■x^nの微分"
      ],
      "metadata": {
        "id": "gxRK7-EzIyNQ"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import sympy as sym\n",
        "x, n = sym.symbols('x n')   # 変数の定義\n",
        "f1 = x**n   # 関数の定義\n",
        "display(f1, f1.diff(x), sym.simplify(f1.diff(x)))"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 94
        },
        "id": "68MkDomVi0xZ",
        "outputId": "d52effa3-8f04-4035-b66f-92b9cc26ac94"
      },
      "execution_count": 55,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "x**n"
            ],
            "text/latex": "$\\displaystyle x^{n}$"
          },
          "metadata": {}
        },
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "n*x**n/x"
            ],
            "text/latex": "$\\displaystyle \\frac{n x^{n}}{x}$"
          },
          "metadata": {}
        },
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "n*x**(n - 1)"
            ],
            "text/latex": "$\\displaystyle n x^{n - 1}$"
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "コードA.14■3次曲線の接線を図示"
      ],
      "metadata": {
        "id": "dF6xEs6UJRCH"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import sympy as sym\n",
        "import matplotlib.pyplot as plt\n",
        "plt.rcParams['figure.figsize'] = 10, 12\n",
        "plt.rcParams[\"font.size\"] = 18\n",
        "x0 = -0.5\n",
        "x = sym.symbols('x')   # 変数の定義\n",
        "f1 = x**3 - 3 * x**2 + 1    # 関数の定義\n",
        "y0 = f1.subs(x, x0)\n",
        "df1 = f1.diff(x)\n",
        "display(df1)\n",
        "df1x0 = df1.subs(x, x0)\n",
        "p1 = sym.plot(f1, xlim=(-4, 4), ylim=(-4, 4),\n",
        "              ylabel='f1(x)', legend=True,\n",
        "              line_color=\"blue\", show=False)  # グラフ描画\n",
        "f2 = df1x0 * (x - x0) + y0\n",
        "p2 = sym.plot(f2, xlim=(-4, 4), ylim=(-4, 4),\n",
        "              ylabel='f1(x)', legend=True,\n",
        "              line_color=\"red\", show=False)  # グラフ描画)\n",
        "p1.extend(p2)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 39
        },
        "id": "6-1cSWGzjIxS",
        "outputId": "ecac8f25-ce8a-4afe-8e53-b24509a4a3b8"
      },
      "execution_count": 56,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "3*x**2 - 6*x"
            ],
            "text/latex": "$\\displaystyle 3 x^{2} - 6 x$"
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "p1.show()"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 856
        },
        "id": "VqYPZ_byjNL9",
        "outputId": "b5205100-2f09-4ca3-d819-25d7715bb100"
      },
      "execution_count": 57,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<Figure size 720x864 with 1 Axes>"
            ],
            "image/png": "[encoded data, 46456 characters]\n"
          },
          "metadata": {
            "needs_background": "light"
          }
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "コードA.15■合成関数の微分"
      ],
      "metadata": {
        "id": "SSVq4Xm4JiNC"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import sympy as sym\n",
        "x, n = sym.symbols('x n')   # 変数の定義\n",
        "f1 = 2 * x + 3  # 関数の定義\n",
        "f2 = 1 / f1**2  # 合成関数の定義\n",
        "display(f2)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 58
        },
        "id": "UtkxesC3jRQl",
        "outputId": "565c8675-fbce-48e0-89e6-ec1757d64f62"
      },
      "execution_count": 61,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "(2*x + 3)**(-2)"
            ],
            "text/latex": "$\\displaystyle \\frac{1}{\\left(2 x + 3\\right)^{2}}$"
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "display(sym.simplify(f2.diff(x)))"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 58
        },
        "id": "OBTY8G-wJm6m",
        "outputId": "78c86a68-e936-4315-d538-65f3de06139f"
      },
      "execution_count": 62,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "-4/(2*x + 3)**3"
            ],
            "text/latex": "$\\displaystyle - \\frac{4}{\\left(2 x + 3\\right)^{3}}$"
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "コードA.16■グラフ作成の基本形"
      ],
      "metadata": {
        "id": "0HxytyksJt_l"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import numpy as np\n",
        "import matplotlib.pyplot as plt\n",
        "# グラフ化する関数の定義\n",
        "x = np.arange(0, 2.05, 0.05)\n",
        "y = 1 - (x - 1)**2\n",
        "# グラフをプロット\n",
        "plt.plot(x, y)\n",
        "# グラフを表示\n",
        "plt.show()"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 708
        },
        "id": "6mEoNKpBjSl5",
        "outputId": "7dc0fce4-3dfb-493a-fda3-7a08b4552059"
      },
      "execution_count": 63,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<Figure size 720x864 with 1 Axes>"
            ],
            "image/png": "[encoded data, 35836 characters]\n"
          },
          "metadata": {
            "needs_background": "light"
          }
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "コードA.17■pyplotを活用してグラフ作成"
      ],
      "metadata": {
        "id": "u8w7zUFtJ5E_"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import numpy as np\n",
        "import matplotlib.pyplot as plt\n",
        "# 図示する三つの関数を定義\n",
        "x = np.arange(0, 2.05, 0.05)\n",
        "y1 = 1 - (x - 1)**2\n",
        "y2 = 0.25 * x**2\n",
        "y3 = 0.5 * np.sin(2 * np.pi * x / 2) + 0.5\n",
        "# 描画領域を作成\n",
        "plt.figure(figsize=(18,16))\n",
        "# グラフ上に書く文字のフォントサイズ設定\n",
        "plt.rcParams[\"font.size\"] = 24\n",
        "# グラフの属性を細かく定義\n",
        "def graphconfig():\n",
        "  # 凡例を表示する位置を左上にする\n",
        "  plt.legend(loc='upper left', bbox_to_anchor=(1, 1))\n",
        "  # 補助目盛を表示する\n",
        "  plt.minorticks_on()\n",
        "  # x座標の目盛りを定義\n",
        "  plt.xticks(np.arange(0, 2.05, 0.5))\n",
        "  plt.yticks(np.arange(0, 1.05, 0.5))\n",
        "  # 座標軸の名前を設定\n",
        "  plt.xlabel(r'$x$')\n",
        "  plt.ylabel(r'$y$')\n",
        "  # 主目盛のグリッド線の形状，色を設定\n",
        "  plt.grid(which='major', linestyle='-', color='k')\n",
        "  # 補助目盛のグリッド線の形状，色を設定\n",
        "  plt.grid(which='minor', linestyle='dotted', color='k')\n",
        "# 2行1列の1行目に描画領域設定\n",
        "plt.subplot(211)\n",
        "# 関数y1,y2のグラフをプロット\n",
        "plt.plot(x, y1, label= r'$y_1=(x-1)^2$', color='g')\n",
        "plt.plot(x, y2, label= r'$y_2=\\frac{1}{4}x^2$', color='r')\n",
        "# グラフ属性を設定する関数を呼び出す\n",
        "graphconfig()\n",
        "# 2行1列の2行目に描画領域設定\n",
        "plt.subplot(211)\n",
        "# 関数y2,y3のグラフをプロット\n",
        "plt.subplot(212)\n",
        "plt.plot(x, y2, label= r'$y_2=\\frac{1}{4}x^2$', color='r')\n",
        "plt.plot(x, y3, label= r'$y_3=\\frac{1}{2}sin\\frac{2\\pi x}{2}+\\frac{1}{2}$', color='b')\n",
        "# グラフ属性を設定する関数を呼び出す\n",
        "graphconfig()\n",
        "# レイアウトの余白を少なめに設定\n",
        "plt.tight_layout()\n",
        "# グラフを表示\n",
        "plt.show()"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "id": "X4OCGBx9jX9J",
        "outputId": "f450e33c-bb2a-49a2-c587-fad8313ce268"
      },
      "execution_count": 64,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stderr",
          "text": [
            "/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:36: MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance.  In a future version, a new instance will always be created and returned.  Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance.\n"
          ]
        },
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<Figure size 1296x1152 with 2 Axes>"
            ],
            "image/png": "[encoded data, 170956 characters]\n"
          },
          "metadata": {
            "needs_background": "light"
          }
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "コードA.18■分類モデルの作成"
      ],
      "metadata": {
        "id": "G_O9QeExKkAt"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "from sklearn import svm\n",
        "from sklearn.datasets import load_iris\n",
        "# データを読み込む\n",
        "iris = load_iris()\n",
        "# 機械学習モデルを設定\n",
        "clf = svm.SVC()\n",
        "# dataからtargetを予測する学習をさせる\n",
        "clf.fit(iris.data, iris.target)\n",
        "# 分類できるかどうか確認する\n",
        "test_data = [[5.4, 3.9, 1.7, 0.4], [5.8, 2.6, 4. , 1.2], [6.7, 3.3, 5.7, 2.5]]\n",
        "print(clf.predict(test_data)) # [0 1 2]"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "WvmZae9WjgEo",
        "outputId": "0ea77866-4fb5-4d54-fb9e-5347716d6d80"
      },
      "execution_count": 65,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "[0 1 2]\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "コードA.19■分類モデルの評価"
      ],
      "metadata": {
        "id": "dRjKxuUHKum_"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "from sklearn import svm\n",
        "from sklearn.model_selection import train_test_split\n",
        "from sklearn.metrics import confusion_matrix\n",
        "from sklearn.metrics import classification_report\n",
        "import seaborn as sns\n",
        "import matplotlib.pyplot as plt\n",
        "import pandas as pd\n",
        "# データを読み込む\n",
        "df = sns.load_dataset('iris')\n",
        "df = df.query('species != \"setosa\"')\n",
        "# 欠損値を除去\n",
        "df = df.copy().dropna()\n",
        "# 特徴量データ\n",
        "x1label = \"sepal_length\"\n",
        "x2label = \"petal_length\"\n",
        "# ラベルデータ\n",
        "y1label = \"species\"\n",
        "# 特徴量データ，ラベルデータをリストに入れる\n",
        "X_iris = df[[x1label, x2label]].values\n",
        "y_iris = df[y1label].values\n",
        "# トレーニング用データとテスト用データに分割\n",
        "X_train, X_test, y_train, y_test = train_test_split(X_iris, y_iris,\n",
        "       test_size=0.3, random_state=42, stratify=y_iris)\n",
        "# 機械学習モデルを設定\n",
        "clf = svm.SVC(kernel='rbf', gamma =0.0001, C=1000)\n",
        "# X_trainからy_trainを予測する学習をさせる\n",
        "clf.fit(X_train, y_train)\n",
        "# テスト用データで分類できるかどうか確認する\n",
        "y_test_pred = clf.predict(X_test)\n",
        "# 予測値\n",
        "print(y_test_pred)\n",
        "# 正解\n",
        "print(y_test)\n",
        "# 混同行列を作成\n",
        "cm = confusion_matrix(y_test, y_test_pred)\n",
        "# 混同行列をヒートマップに変換\n",
        "sns.heatmap(cm, annot=True, cmap='Blues')\n",
        "# 軸にラベル設定\n",
        "plt.yticks(rotation=0)\n",
        "plt.xlabel(\"Predicted\", fontsize=13, rotation=0)\n",
        "plt.ylabel(\"Actual\", fontsize=13)\n",
        "# 混同行列のヒートマップを表示\n",
        "plt.show()\n",
        "# テスト用データの分類結果一覧\n",
        "print(classification_report(y_test, y_test_pred))"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "id": "dzhzcgbXjjc9",
        "outputId": "e4b2bbed-6252-4a58-a4c8-34203e0fbb41"
      },
      "execution_count": 73,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "['versicolor' 'versicolor' 'virginica' 'versicolor' 'versicolor'\n",
            " 'virginica' 'virginica' 'virginica' 'virginica' 'versicolor' 'virginica'\n",
            " 'virginica' 'versicolor' 'versicolor' 'virginica' 'virginica'\n",
            " 'versicolor' 'versicolor' 'virginica' 'versicolor' 'versicolor'\n",
            " 'versicolor' 'virginica' 'virginica' 'versicolor' 'versicolor'\n",
            " 'versicolor' 'virginica' 'virginica' 'versicolor']\n",
            "['versicolor' 'versicolor' 'virginica' 'versicolor' 'versicolor'\n",
            " 'virginica' 'virginica' 'virginica' 'virginica' 'versicolor' 'virginica'\n",
            " 'virginica' 'versicolor' 'versicolor' 'virginica' 'virginica'\n",
            " 'versicolor' 'versicolor' 'virginica' 'versicolor' 'versicolor'\n",
            " 'versicolor' 'virginica' 'virginica' 'versicolor' 'versicolor'\n",
            " 'virginica' 'virginica' 'virginica' 'versicolor']\n"
          ]
        },
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<Figure size 720x864 with 2 Axes>"
            ],
            "image/png": "[encoded data, 16660 characters]\n"
          },
          "metadata": {
            "needs_background": "light"
          }
        },
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "              precision    recall  f1-score   support\n",
            "\n",
            "  versicolor       0.94      1.00      0.97        15\n",
            "   virginica       1.00      0.93      0.97        15\n",
            "\n",
            "    accuracy                           0.97        30\n",
            "   macro avg       0.97      0.97      0.97        30\n",
            "weighted avg       0.97      0.97      0.97        30\n",
            "\n"
          ]
        }
      ]
    }
  ]
}