{ "cells": [ { "cell_type": "code", "execution_count": 5, "id": "82651119-3e61-4bac-a2fc-a547887668a6", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1.5.0\n" ] } ], "source": [ "# 사이킷런 버전 확인\n", "import sklearn\n", "\n", "print(sklearn.__version__)" ] }, { "cell_type": "code", "execution_count": 6, "id": "dba9c6cc-d39a-45ee-84b1-5ea70b06a692", "metadata": {}, "outputs": [], "source": [ "# sklearn.datasets: 사이킷런에서 자체 제공하는 데이터 세트 생성 모듈\n", "from sklearn.datasets import load_iris\n", "# sklearn.tree: 트리 기반 ML 알고리즘을 구현한 클래스의 모임\n", "from sklearn.tree import DecisionTreeClassifier\n", "# sklearn.model_selection: 데이터 분리(학습, 검증, 평가) 또는 최적의 하이퍼 파라미터로 평가하기 위한 모듈 모임\n", "from sklearn.model_selection import train_test_split" ] }, { "cell_type": "code", "execution_count": 7, "id": "96be2226-3c99-44df-8f68-e5d8e6b891ce", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "iris target 값: [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n", " 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n", " 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2\n", " 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2\n", " 2 2]\n", "iris target 명: ['setosa' 'versicolor' 'virginica']\n" ] }, { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
sepal length (cm)sepal width (cm)petal length (cm)petal width (cm)label
05.13.51.40.20
14.93.01.40.20
24.73.21.30.20
\n", "
" ], "text/plain": [ " sepal length (cm) sepal width (cm) petal length (cm) petal width (cm) \\\n", "0 5.1 3.5 1.4 0.2 \n", "1 4.9 3.0 1.4 0.2 \n", "2 4.7 3.2 1.3 0.2 \n", "\n", " label \n", "0 0 \n", "1 0 \n", "2 0 " ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 붓꽃 데이터 세트 DF 생성\n", "import pandas as pd\n", "\n", "# 붓꽃 데이터 세트 로딩\n", "iris = load_iris()\n", "\n", "# iris.data 는 Iris 데이터 세트에서 피처만으로 된 데이터를 numpy로 가지고 있음\n", "iris_data = iris.data\n", "\n", "# iris.target 은 붓꽃 데이터 세트에서 레이블 데이터를 numpy로 가지고 있음\n", "iris_label = iris.target\n", "print('iris target 값:', iris_label)\n", "print('iris target 명:', iris.target_names)\n", "\n", "# 붓꽃 데이터 세트를 자세히 보기 위해 DF 으로 변환\n", "iris_df = pd.DataFrame(data=iris_data, columns=iris.feature_names)\n", "iris_df['label'] = iris.target\n", "iris_df.head(3)" ] }, { "cell_type": "code", "execution_count": 8, "id": "ee68a4d6-17c5-4be9-bcfa-0a81ed812cf0", "metadata": {}, "outputs": [], "source": [ "# 데이터 분리(학습 데이터, 테스트 데이터)\n", "X_train, X_test, y_train, y_test = train_test_split(iris_data, iris_label,\n", " test_size=0.2, random_state=11) #테스트 데이터 20%, 학습데이터 80%" ] }, { "cell_type": "code", "execution_count": 9, "id": "94e22de5-8f23-4bd7-ba94-3437d893eb8e", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
DecisionTreeClassifier(random_state=11)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
" ], "text/plain": [ "DecisionTreeClassifier(random_state=11)" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 의사결정트리 (학습과 예측 수행)\n", "# DecisionTreeClassifier 객체 생성\n", "df_clf = DecisionTreeClassifier(random_state=11) #동일한 학습/예측 결과를 출력하기 위한 용도\n", "\n", "# 학습 수행\n", "df_clf.fit(X_train, y_train)" ] }, { "cell_type": "code", "execution_count": 10, "id": "b57a3ba2-eb62-4f7c-8fbf-647fd7ca1e28", "metadata": {}, "outputs": [], "source": [ "# 학습 완료된 DecisionTreeClassifier 객체에서 테스트 데이터 세트로 예측 수행\n", "pred = df_clf.predict(X_test)" ] }, { "cell_type": "code", "execution_count": 12, "id": "6d5b28a6-ab1c-4731-92d0-e656ea5b5fa4", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "예측 정확도: 0.933333\n" ] } ], "source": [ "# 정확도 측정\n", "from sklearn.metrics import accuracy_score\n", "print('예측 정확도: {0:4f}'.format(accuracy_score(y_test, pred)))" ] }, { "cell_type": "code", "execution_count": 13, "id": "624dbd20-94c2-4e5a-a218-660c917ff473", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "# 붓꽃 데이터 세트 생성\n", "from sklearn.datasets import load_iris\n", "\n", "iris_data = load_iris()\n", "print(type(iris_data))" ] }, { "cell_type": "code", "execution_count": 14, "id": "080789c2-3720-4ef3-8cee-c352fc0d88b2", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "붓꽃 데이터 세트의 키들: dict_keys(['data', 'target', 'frame', 'target_names', 'DESCR', 'feature_names', 'filename', 'data_module'])\n" ] } ], "source": [ "# load_iris( ) 데이터 세트의 key 값 확인\n", "keys = iris_data.keys()\n", "print('붓꽃 데이터 세트의 키들:', keys)" ] }, { "cell_type": "code", "execution_count": 15, "id": "07cde142-4f9f-41cb-b6a9-0bafb75ae9ec", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", " feature_names의 type: \n", "\n", " feature_names의 shape: 4\n", "['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']\n", "\n", " target_names의 type: \n", "\n", " target_names의 shape: 3\n", "['setosa' 'versicolor' 'virginica']\n", "\n", " data 의 type: \n", "\n", " data 의 shape: 150\n", "[[5.1 3.5 1.4 0.2]\n", " [4.9 3. 1.4 0.2]\n", " [4.7 3.2 1.3 0.2]\n", " [4.6 3.1 1.5 0.2]\n", " [5. 3.6 1.4 0.2]\n", " [5.4 3.9 1.7 0.4]\n", " [4.6 3.4 1.4 0.3]\n", " [5. 3.4 1.5 0.2]\n", " [4.4 2.9 1.4 0.2]\n", " [4.9 3.1 1.5 0.1]\n", " [5.4 3.7 1.5 0.2]\n", " [4.8 3.4 1.6 0.2]\n", " [4.8 3. 1.4 0.1]\n", " [4.3 3. 1.1 0.1]\n", " [5.8 4. 1.2 0.2]\n", " [5.7 4.4 1.5 0.4]\n", " [5.4 3.9 1.3 0.4]\n", " [5.1 3.5 1.4 0.3]\n", " [5.7 3.8 1.7 0.3]\n", " [5.1 3.8 1.5 0.3]\n", " [5.4 3.4 1.7 0.2]\n", " [5.1 3.7 1.5 0.4]\n", " [4.6 3.6 1. 0.2]\n", " [5.1 3.3 1.7 0.5]\n", " [4.8 3.4 1.9 0.2]\n", " [5. 3. 1.6 0.2]\n", " [5. 3.4 1.6 0.4]\n", " [5.2 3.5 1.5 0.2]\n", " [5.2 3.4 1.4 0.2]\n", " [4.7 3.2 1.6 0.2]\n", " [4.8 3.1 1.6 0.2]\n", " [5.4 3.4 1.5 0.4]\n", " [5.2 4.1 1.5 0.1]\n", " [5.5 4.2 1.4 0.2]\n", " [4.9 3.1 1.5 0.2]\n", " [5. 3.2 1.2 0.2]\n", " [5.5 3.5 1.3 0.2]\n", " [4.9 3.6 1.4 0.1]\n", " [4.4 3. 1.3 0.2]\n", " [5.1 3.4 1.5 0.2]\n", " [5. 3.5 1.3 0.3]\n", " [4.5 2.3 1.3 0.3]\n", " [4.4 3.2 1.3 0.2]\n", " [5. 3.5 1.6 0.6]\n", " [5.1 3.8 1.9 0.4]\n", " [4.8 3. 1.4 0.3]\n", " [5.1 3.8 1.6 0.2]\n", " [4.6 3.2 1.4 0.2]\n", " [5.3 3.7 1.5 0.2]\n", " [5. 3.3 1.4 0.2]\n", " [7. 3.2 4.7 1.4]\n", " [6.4 3.2 4.5 1.5]\n", " [6.9 3.1 4.9 1.5]\n", " [5.5 2.3 4. 1.3]\n", " [6.5 2.8 4.6 1.5]\n", " [5.7 2.8 4.5 1.3]\n", " [6.3 3.3 4.7 1.6]\n", " [4.9 2.4 3.3 1. ]\n", " [6.6 2.9 4.6 1.3]\n", " [5.2 2.7 3.9 1.4]\n", " [5. 2. 3.5 1. ]\n", " [5.9 3. 4.2 1.5]\n", " [6. 2.2 4. 1. ]\n", " [6.1 2.9 4.7 1.4]\n", " [5.6 2.9 3.6 1.3]\n", " [6.7 3.1 4.4 1.4]\n", " [5.6 3. 4.5 1.5]\n", " [5.8 2.7 4.1 1. ]\n", " [6.2 2.2 4.5 1.5]\n", " [5.6 2.5 3.9 1.1]\n", " [5.9 3.2 4.8 1.8]\n", " [6.1 2.8 4. 1.3]\n", " [6.3 2.5 4.9 1.5]\n", " [6.1 2.8 4.7 1.2]\n", " [6.4 2.9 4.3 1.3]\n", " [6.6 3. 4.4 1.4]\n", " [6.8 2.8 4.8 1.4]\n", " [6.7 3. 5. 1.7]\n", " [6. 2.9 4.5 1.5]\n", " [5.7 2.6 3.5 1. ]\n", " [5.5 2.4 3.8 1.1]\n", " [5.5 2.4 3.7 1. ]\n", " [5.8 2.7 3.9 1.2]\n", " [6. 2.7 5.1 1.6]\n", " [5.4 3. 4.5 1.5]\n", " [6. 3.4 4.5 1.6]\n", " [6.7 3.1 4.7 1.5]\n", " [6.3 2.3 4.4 1.3]\n", " [5.6 3. 4.1 1.3]\n", " [5.5 2.5 4. 1.3]\n", " [5.5 2.6 4.4 1.2]\n", " [6.1 3. 4.6 1.4]\n", " [5.8 2.6 4. 1.2]\n", " [5. 2.3 3.3 1. ]\n", " [5.6 2.7 4.2 1.3]\n", " [5.7 3. 4.2 1.2]\n", " [5.7 2.9 4.2 1.3]\n", " [6.2 2.9 4.3 1.3]\n", " [5.1 2.5 3. 1.1]\n", " [5.7 2.8 4.1 1.3]\n", " [6.3 3.3 6. 2.5]\n", " [5.8 2.7 5.1 1.9]\n", " [7.1 3. 5.9 2.1]\n", " [6.3 2.9 5.6 1.8]\n", " [6.5 3. 5.8 2.2]\n", " [7.6 3. 6.6 2.1]\n", " [4.9 2.5 4.5 1.7]\n", " [7.3 2.9 6.3 1.8]\n", " [6.7 2.5 5.8 1.8]\n", " [7.2 3.6 6.1 2.5]\n", " [6.5 3.2 5.1 2. ]\n", " [6.4 2.7 5.3 1.9]\n", " [6.8 3. 5.5 2.1]\n", " [5.7 2.5 5. 2. ]\n", " [5.8 2.8 5.1 2.4]\n", " [6.4 3.2 5.3 2.3]\n", " [6.5 3. 5.5 1.8]\n", " [7.7 3.8 6.7 2.2]\n", " [7.7 2.6 6.9 2.3]\n", " [6. 2.2 5. 1.5]\n", " [6.9 3.2 5.7 2.3]\n", " [5.6 2.8 4.9 2. ]\n", " [7.7 2.8 6.7 2. ]\n", " [6.3 2.7 4.9 1.8]\n", " [6.7 3.3 5.7 2.1]\n", " [7.2 3.2 6. 1.8]\n", " [6.2 2.8 4.8 1.8]\n", " [6.1 3. 4.9 1.8]\n", " [6.4 2.8 5.6 2.1]\n", " [7.2 3. 5.8 1.6]\n", " [7.4 2.8 6.1 1.9]\n", " [7.9 3.8 6.4 2. ]\n", " [6.4 2.8 5.6 2.2]\n", " [6.3 2.8 5.1 1.5]\n", " [6.1 2.6 5.6 1.4]\n", " [7.7 3. 6.1 2.3]\n", " [6.3 3.4 5.6 2.4]\n", " [6.4 3.1 5.5 1.8]\n", " [6. 3. 4.8 1.8]\n", " [6.9 3.1 5.4 2.1]\n", " [6.7 3.1 5.6 2.4]\n", " [6.9 3.1 5.1 2.3]\n", " [5.8 2.7 5.1 1.9]\n", " [6.8 3.2 5.9 2.3]\n", " [6.7 3.3 5.7 2.5]\n", " [6.7 3. 5.2 2.3]\n", " [6.3 2.5 5. 1.9]\n", " [6.5 3. 5.2 2. ]\n", " [6.2 3.4 5.4 2.3]\n", " [5.9 3. 5.1 1.8]]\n", "\n", " target 의 type: \n", "\n", " target 의 shape: 150\n", "[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n", " 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n", " 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2\n", " 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2\n", " 2 2]\n" ] } ], "source": [ "print('\\n feature_names의 type:', type(iris_data.feature_names))\n", "print('\\n feature_names의 shape:', len(iris_data.feature_names))\n", "print(iris_data.feature_names)\n", "\n", "print('\\n target_names의 type:', type(iris_data.target_names))\n", "print('\\n target_names의 shape:', len(iris_data.target_names))\n", "print(iris_data.target_names)\n", "\n", "print('\\n data 의 type:', type(iris_data.data))\n", "print('\\n data 의 shape:', len(iris_data.data))\n", "print(iris_data.data)\n", "\n", "print('\\n target 의 type:', type(iris_data.target))\n", "print('\\n target 의 shape:', len(iris_data.target))\n", "print(iris_data.target)" ] }, { "cell_type": "code", "execution_count": 5, "id": "b36192f0-d4af-46e7-bf3f-420282ea8da4", "metadata": {}, "outputs": [], "source": [ "# Model_selection 모듈\n", "# 데이터 분할 (train_test_split)\n", "from sklearn.tree import DecisionTreeClassifier\n", "from sklearn.metrics import accuracy_score\n", "from sklearn.datasets import load_iris\n", "from sklearn.model_selection import train_test_split\n", "\n", "dt_clf = DecisionTreeClassifier()\n", "iris_data = load_iris()\n", "\n", "X_train, X_test, y_train, y_test = train_test_split(iris_data.data, iris_data.target, \\\n", " test_size=0.3, random_state=121)" ] }, { "cell_type": "code", "execution_count": 8, "id": "0dd3ba85-cc71-4bb9-b9e8-127dbcdc0e3d", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "예측 정확도: 0.9556\n" ] } ], "source": [ "# 의사결정트리 분류기 학습 및 예측 정확도 측정\n", "dt_clf.fit(X_train, y_train)\n", "pred = dt_clf.predict(X_test)\n", "print('예측 정확도: {0:.4f}'.format(accuracy_score(y_test, pred)))" ] }, { "cell_type": "code", "execution_count": 9, "id": "c0229a97-82f0-4e8f-8182-e6da7469fa53", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "예측 정확도: 1.0\n" ] } ], "source": [ "# 테스트 데이터 없이 학습 데이터 세트로만 예측\n", "from sklearn.datasets import load_iris\n", "from sklearn.tree import DecisionTreeClassifier\n", "from sklearn.metrics import accuracy_score\n", "\n", "iris = load_iris()\n", "dt_clf = DecisionTreeClassifier()\n", "train_data = iris.data\n", "train_label = iris.target\n", "dt_clf.fit(train_data, train_label)\n", "\n", "#학습 데이터 세트로 예측 수행\n", "pred = dt_clf.predict(train_data)\n", "print('예측 정확도:', accuracy_score(train_label, pred))" ] }, { "cell_type": "code", "execution_count": 10, "id": "6ea3e06c-fd5b-44a0-87a2-970d329948f9", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "붓꽃 데이터 세트 크기: 150\n" ] } ], "source": [ "#KFold 클래스\n", "from sklearn.tree import DecisionTreeClassifier\n", "from sklearn.metrics import accuracy_score\n", "from sklearn.model_selection import KFold\n", "import numpy as np\n", "\n", "iris = load_iris()\n", "features = iris.data\n", "label = iris.target\n", "dt_clf = DecisionTreeClassifier(random_state=156)\n", "\n", "#5개의 폴드 세트로 분리하는 KFold 객체와 폴드 세트별 정확도 담을 리스트 객체 생성\n", "kfold = KFold(n_splits=5)\n", "cv_accuracy = []\n", "print('붓꽃 데이터 세트 크기:', features.shape[0])" ] }, { "cell_type": "code", "execution_count": 11, "id": "33ec8e6c-f73d-443e-af50-8d392af376f6", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "#1 교차 검증 정확도 :1.0, 학습 데이터 크기: 120, 검증 데이터 크기: 30\n", "#1 검증 세트 인덱스:[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23\n", " 24 25 26 27 28 29]\n", "\n", "#2 교차 검증 정확도 :0.9667, 학습 데이터 크기: 120, 검증 데이터 크기: 30\n", "#2 검증 세트 인덱스:[30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53\n", " 54 55 56 57 58 59]\n", "\n", "#3 교차 검증 정확도 :0.8667, 학습 데이터 크기: 120, 검증 데이터 크기: 30\n", "#3 검증 세트 인덱스:[60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83\n", " 84 85 86 87 88 89]\n", "\n", "#4 교차 검증 정확도 :0.9333, 학습 데이터 크기: 120, 검증 데이터 크기: 30\n", "#4 검증 세트 인덱스:[ 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107\n", " 108 109 110 111 112 113 114 115 116 117 118 119]\n", "\n", "#5 교차 검증 정확도 :0.7333, 학습 데이터 크기: 120, 검증 데이터 크기: 30\n", "#5 검증 세트 인덱스:[120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137\n", " 138 139 140 141 142 143 144 145 146 147 148 149]\n", "\n", "## 평균 검증 정확도: 0.9\n" ] } ], "source": [ "# KFold 객체 분할(학습용, 검증용)\n", "n_iter = 0\n", "\n", "#KFold 객체의 split()를 호출하면 폴드별 학습용, 검증용 테스트의 로우 인덱스를 array로 변환\n", "for train_index, test_index in kfold.split(features):\n", " #kfold.split()으로 반환된 인덱스를 이용해 학습용, 검증용 테스트 데이터 추출\n", " X_train, X_test = features[train_index], features[test_index]\n", " y_train, y_test = label[train_index], label[test_index]\n", " #학습 및 예측\n", " dt_clf.fit(X_train,y_train)\n", " pred = dt_clf.predict(X_test)\n", " n_iter += 1\n", " #반복 시마다 정확도 측정\n", " accuracy = np.round(accuracy_score(y_test, pred), 4)\n", " train_size = X_train.shape[0]\n", " test_size = X_test.shape[0]\n", " print('\\n#{0} 교차 검증 정확도 :{1}, 학습 데이터 크기: {2}, 검증 데이터 크기: {3}'\n", " .format(n_iter, accuracy, train_size, test_size))\n", " print('#{0} 검증 세트 인덱스:{1}'.format(n_iter, test_index))\n", " cv_accuracy.append(accuracy)\n", "\n", "# 개별 iteration별 정확도를 합하여 평균 정확도 계산\n", "print('\\n## 평균 검증 정확도:', np.mean(cv_accuracy))" ] }, { "cell_type": "code", "execution_count": 12, "id": "64382e43-35f4-40ef-be2a-42bcc20951d4", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "label\n", "0 50\n", "1 50\n", "2 50\n", "Name: count, dtype: int64" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# k 폴드를 Stratifed K 폴드로 개선하기\n", "# 붓꽃 데이터 세트를 간단하게 DataFrame으로 생성하고 레이블 값의 분포도 확인\n", "import pandas as pd\n", "\n", "iris = load_iris()\n", "iris_df = pd.DataFrame(data=iris.data, columns=iris.feature_names)\n", "iris_df['label']=iris.target\n", "iris_df['label'].value_counts()" ] }, { "cell_type": "code", "execution_count": 15, "id": "6846e882-5f1f-4808-93d5-ddb016e9e147", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "## 교차 검증: 1\n", "학습 레이블 데이터 분포:\n", " label\n", "1 50\n", "2 50\n", "Name: count, dtype: int64\n", "검증 레이블 데이터 분포:\n", " label\n", "0 50\n", "Name: count, dtype: int64\n", "## 교차 검증: 2\n", "학습 레이블 데이터 분포:\n", " label\n", "0 50\n", "2 50\n", "Name: count, dtype: int64\n", "검증 레이블 데이터 분포:\n", " label\n", "1 50\n", "Name: count, dtype: int64\n", "## 교차 검증: 3\n", "학습 레이블 데이터 분포:\n", " label\n", "0 50\n", "1 50\n", "Name: count, dtype: int64\n", "검증 레이블 데이터 분포:\n", " label\n", "2 50\n", "Name: count, dtype: int64\n" ] } ], "source": [ "# KFold 생성 및 레이블 데이터 분포 확인\n", "kfold = KFold(n_splits=3)\n", "n_iter = 0\n", "for train_index, test_index in kfold.split(iris_df):\n", " n_iter += 1\n", " label_train = iris_df['label'].iloc[train_index]\n", " label_test = iris_df['label'].iloc[test_index]\n", " print('## 교차 검증: {0}'.format(n_iter))\n", " print('학습 레이블 데이터 분포:\\n', label_train.value_counts())\n", " print('검증 레이블 데이터 분포:\\n', label_test.value_counts())" ] }, { "cell_type": "code", "execution_count": 17, "id": "f841146b-04fa-4c40-b5d5-d725f7c25359", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "## 교차 검증: 1\n", "학습 레이블 데이터 분포:\n", " label\n", "2 34\n", "0 33\n", "1 33\n", "Name: count, dtype: int64\n", "검증 레이블 데이터 분포:\n", " label\n", "0 17\n", "1 17\n", "2 16\n", "Name: count, dtype: int64\n", "## 교차 검증: 2\n", "학습 레이블 데이터 분포:\n", " label\n", "1 34\n", "0 33\n", "2 33\n", "Name: count, dtype: int64\n", "검증 레이블 데이터 분포:\n", " label\n", "0 17\n", "2 17\n", "1 16\n", "Name: count, dtype: int64\n", "## 교차 검증: 3\n", "학습 레이블 데이터 분포:\n", " label\n", "0 34\n", "1 33\n", "2 33\n", "Name: count, dtype: int64\n", "검증 레이블 데이터 분포:\n", " label\n", "1 17\n", "2 17\n", "0 16\n", "Name: count, dtype: int64\n" ] } ], "source": [ "# Stratified K 폴드로 개선하기\n", "from sklearn.model_selection import StratifiedKFold\n", "\n", "skf = StratifiedKFold(n_splits=3) #폴드 세트는 3개로 설정\n", "n_iter = 0\n", "\n", "for train_index, test_index in skf.split(iris_df, iris_df['label']):\n", " n_iter += 1\n", " label_train = iris_df['label'].iloc[train_index]\n", " label_test = iris_df['label'].iloc[test_index]\n", " print('## 교차 검증: {0}'.format(n_iter))\n", " print('학습 레이블 데이터 분포:\\n', label_train.value_counts())\n", " print('검증 레이블 데이터 분포:\\n', label_test.value_counts())" ] }, { "cell_type": "code", "execution_count": 28, "id": "5071c2c8-3a89-4f8c-ac6a-a3795fb715f6", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "#1 교차 검증 정확도: 0.98, 학습 데이터 크기: 100, 검증 데이터 크기50\n", "#1 검증 세트 인덱스:[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 50\n", " 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 100 101\n", " 102 103 104 105 106 107 108 109 110 111 112 113 114 115]\n", "\n", "#2 교차 검증 정확도: 0.94, 학습 데이터 크기: 100, 검증 데이터 크기50\n", "#2 검증 세트 인덱스:[ 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 67\n", " 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 116 117 118\n", " 119 120 121 122 123 124 125 126 127 128 129 130 131 132]\n", "\n", "#3 교차 검증 정확도: 0.98, 학습 데이터 크기: 100, 검증 데이터 크기50\n", "#3 검증 세트 인덱스:[ 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 83 84\n", " 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 133 134 135\n", " 136 137 138 139 140 141 142 143 144 145 146 147 148 149]\n", "\n", "## 교차 검증별 정확도: [0.98 0.94 0.98]\n", "## 평균 검증 정확도: 0.9667\n" ] } ], "source": [ "# StratifiedKFold 를 이용해 붓꽃 데이터 교차 검증하기\n", "dt_clf = DecisionTreeClassifier(random_state=156)\n", "\n", "skfold = StratifiedKFold(n_splits=3)\n", "n_iter = 0\n", "cv_accuracy = []\n", "\n", "#StratifiedKFold의 split() 호출시 반드시 레이블 데이터 세트도 추가 입력 필요\n", "for train_index, test_index in skfold.split(features, label):\n", " #split() 으로 반횐된 인덱스를 이용해 학습용, 검증용 테스트 데이터 추출\n", " X_train, X_test = features[train_index], features[test_index]\n", " y_train, y_test = label[train_index], label[test_index]\n", " #학습 및 예측\n", " dt_clf.fit(X_train, y_train)\n", " pred = dt_clf.predict(X_test)\n", "\n", " #반복 시마다 정확도 측정\n", " n_iter += 1\n", " accuracy = np.round(accuracy_score(y_test, pred), 4)\n", " train_size = X_train.shape[0]\n", " test_size = X_test.shape[0]\n", " print('\\n#{0} 교차 검증 정확도: {1}, 학습 데이터 크기: {2}, 검증 데이터 크기{3}'\n", " .format(n_iter, accuracy, train_size, test_size))\n", " print('#{0} 검증 세트 인덱스:{1}'.format(n_iter, test_index))\n", " cv_accuracy.append(accuracy)\n", "\n", "# 교차 검증별 정확도 및 평균 정확도 계산\n", "print('\\n## 교차 검증별 정확도:', np.round(cv_accuracy, 4))\n", "print('## 평균 검증 정확도:', np.round(np.mean(cv_accuracy), 4))" ] }, { "cell_type": "code", "execution_count": 30, "id": "f0c8d307-ef00-49ae-9a5a-8333958c9f96", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "교차 검증별 정확도: [0.98 0.94 0.98]\n", "평균 검증 정확도: 0.9667\n" ] } ], "source": [ "# cross_val_score 사용법\n", "from sklearn.tree import DecisionTreeClassifier\n", "from sklearn.model_selection import cross_val_score, cross_validate\n", "from sklearn.datasets import load_iris\n", "\n", "iris_data = load_iris()\n", "dt_clf = DecisionTreeClassifier(random_state=156)\n", "\n", "data = iris_data.data\n", "label = iris_data.target\n", "\n", "#성능 지표는 정확도(accuracy), 교차 검증 세트는 3개\n", "scores = cross_val_score(dt_clf, data, label, scoring='accuracy', cv=3)\n", "print('교차 검증별 정확도:', np.round(scores, 4))\n", "print('평균 검증 정확도:', np.round(np.mean(scores), 4))" ] }, { "cell_type": "code", "execution_count": 31, "id": "193f19ce-b602-44c8-86a1-062715115b49", "metadata": {}, "outputs": [], "source": [ "# GridSearchCV\n", "grid_parameters = {'max_depth': [1, 2, 3],\n", " 'min_samples_split': [2, 3]\n", " }" ] }, { "cell_type": "code", "execution_count": 33, "id": "730df859-183d-4d71-a0f2-3297d81936a7", "metadata": {}, "outputs": [], "source": [ "# GridSearchCV API 익히기\n", "from sklearn.datasets import load_iris\n", "from sklearn.tree import DecisionTreeClassifier\n", "from sklearn.model_selection import GridSearchCV\n", "\n", "# 데이터를 로딩하고 학습 데이터와 테스트 데이터 분리\n", "iris_data = load_iris()\n", "X_train, X_test, y_train, y_test = train_test_split(iris_data.data, iris_data.target,\n", " test_size=0.2, random_state=121)\n", "\n", "dtree = DecisionTreeClassifier()\n", "\n", "#파라미터를 딕셔너리 형태로 저장\n", "parameters = {'max_depth': [1, 2, 3], 'min_samples_split': [2, 3]}" ] }, { "cell_type": "code", "execution_count": 34, "id": "5ba569e4-c9ea-4702-8d3a-809ffe91df19", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
paramsmean_test_scorerank_test_scoresplit0_test_scoresplit1_test_scoresplit2_test_score
0{'max_depth': 1, 'min_samples_split': 2}0.70000050.7000.70.70
1{'max_depth': 1, 'min_samples_split': 3}0.70000050.7000.70.70
2{'max_depth': 2, 'min_samples_split': 2}0.95833330.9251.00.95
3{'max_depth': 2, 'min_samples_split': 3}0.95833330.9251.00.95
4{'max_depth': 3, 'min_samples_split': 2}0.97500010.9751.00.95
5{'max_depth': 3, 'min_samples_split': 3}0.97500010.9751.00.95
\n", "
" ], "text/plain": [ " params mean_test_score rank_test_score \\\n", "0 {'max_depth': 1, 'min_samples_split': 2} 0.700000 5 \n", "1 {'max_depth': 1, 'min_samples_split': 3} 0.700000 5 \n", "2 {'max_depth': 2, 'min_samples_split': 2} 0.958333 3 \n", "3 {'max_depth': 2, 'min_samples_split': 3} 0.958333 3 \n", "4 {'max_depth': 3, 'min_samples_split': 2} 0.975000 1 \n", "5 {'max_depth': 3, 'min_samples_split': 3} 0.975000 1 \n", "\n", " split0_test_score split1_test_score split2_test_score \n", "0 0.700 0.7 0.70 \n", "1 0.700 0.7 0.70 \n", "2 0.925 1.0 0.95 \n", "3 0.925 1.0 0.95 \n", "4 0.975 1.0 0.95 \n", "5 0.975 1.0 0.95 " ] }, "execution_count": 34, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import pandas as pd\n", "\n", "# param_grid 하이퍼 파라미터를 3개의 train, test set fold로 나누어 테스트 수행 설정\n", "### refit=True가 default 임. True일 경우 가장 좋은 파라미터 설정으로 재학습시킴\n", "grid_dtree = GridSearchCV(dtree, param_grid=parameters, cv=3, refit=True)\n", "\n", "#붓꽃 학습 데이터로 param_grid의 하이퍼 파라미터를 순차적으로 학습/평가\n", "grid_dtree.fit(X_train, y_train)\n", "\n", "#GridSearchCV 결과를 추출해 DataFrame으로 변환\n", "scores_df = pd.DataFrame(grid_dtree.cv_results_)\n", "scores_df [['params', 'mean_test_score', 'rank_test_score',\n", " 'split0_test_score','split1_test_score','split2_test_score']]" ] }, { "cell_type": "code", "execution_count": 36, "id": "969d68d1-6642-45ec-9ce0-832e9091f831", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "GridSearchCV 최적 파라미터: {'max_depth': 3, 'min_samples_split': 2}\n", "GridSearchCV 최고 정확도:0.9750\n" ] } ], "source": [ "# 최적의 파라미터 (그 정확도)\n", "print('GridSearchCV 최적 파라미터:', grid_dtree.best_params_)\n", "print('GridSearchCV 최고 정확도:{0:.4f}'.format(grid_dtree.best_score_))" ] }, { "cell_type": "code", "execution_count": 37, "id": "dd7cac1d-f0ff-41f4-a0b1-b0aabc979829", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "테스트 데이터 세트 정확도: 0.9667\n" ] } ], "source": [ "# GridSearchCV의 refit으로 이미 학습된 esitmator 반환\n", "estimator = grid_dtree.best_estimator_\n", "\n", "# GridSearchCV의 best_estimator_는 이미 최적 학습이 됐으므로 별도 학습 필요 없음\n", "pred = estimator.predict(X_test)\n", "print('테스트 데이터 세트 정확도: {0:.4f}'.format(accuracy_score(y_test, pred)))" ] }, { "cell_type": "code", "execution_count": 1, "id": "312162dd-5163-43d6-b59f-7f4699d941b0", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "인코딩 변환값: [0 1 4 5 3 3 2 2]\n" ] } ], "source": [ "# 데이터 인코딩 - 레이블 인코딩\n", "from sklearn.preprocessing import LabelEncoder\n", "\n", "items = ['TV', '냉장고', '전자레인지', '컴퓨터', '선풍기', '선풍기', '믹서', '믹서']\n", "\n", "# LabelEndoer 를 객체로 생성, fit()과 transform()으로 레이블 인코딩 수행\n", "encoder=LabelEncoder()\n", "encoder.fit(items)\n", "labels=encoder.transform(items)\n", "print('인코딩 변환값:',labels)" ] }, { "cell_type": "code", "execution_count": 2, "id": "57ca91d5-21c1-4949-8526-b4ff4eb0d65d", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "인코딩 클래스: ['TV' '냉장고' '믹서' '선풍기' '전자레인지' '컴퓨터']\n" ] } ], "source": [ "print('인코딩 클래스:', encoder.classes_)" ] }, { "cell_type": "code", "execution_count": 3, "id": "6c4e0316-a7b5-461e-b888-9a28df46a8a2", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "디코딩 원본값: ['전자레인지' '컴퓨터' '믹서' 'TV' '냉장고' '냉장고' '선풍기' '선풍기']\n" ] } ], "source": [ "#인코딩 > 디코딩\n", "print('디코딩 원본값:', encoder.inverse_transform([4, 5, 2, 0, 1, 1, 3, 3]))" ] }, { "cell_type": "code", "execution_count": 5, "id": "99c7c8eb-9b44-460d-ab74-0b195d79ac3c", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "원-핫 인코딩 데이터\n", "[[1. 0. 0. 0. 0. 0.]\n", " [0. 1. 0. 0. 0. 0.]\n", " [0. 0. 0. 0. 1. 0.]\n", " [0. 0. 0. 0. 0. 1.]\n", " [0. 0. 0. 1. 0. 0.]\n", " [0. 0. 0. 1. 0. 0.]\n", " [0. 0. 1. 0. 0. 0.]\n", " [0. 0. 1. 0. 0. 0.]]\n", "원-핫 인코딩 데이터 차원\n", "(8, 6)\n" ] } ], "source": [ "# 데이터 인코딩 - 원-핫 인코딩\n", "from sklearn.preprocessing import OneHotEncoder\n", "import numpy as np\n", "\n", "items = ['TV', '냉장고', '전자레인지', '컴퓨터', '선풍기', '선풍기', '믹서', '믹서']\n", "\n", "#2차원 ndarray 로 변환\n", "items = np.array(items).reshape(-1, 1)\n", "\n", "#원-핫 인코딩 적용\n", "oh_encoder = OneHotEncoder()\n", "oh_encoder.fit(items)\n", "oh_labels = oh_encoder.transform(items)\n", "\n", "#OneHotEncoder로 변환한 결과는 희소행렬 이므로, toarray를 이용해 밀집 행렬로 변환\n", "print('원-핫 인코딩 데이터')\n", "print(oh_labels.toarray())\n", "print('원-핫 인코딩 데이터 차원')\n", "print(oh_labels.shape)" ] }, { "cell_type": "code", "execution_count": 6, "id": "2744d5db-eecc-41d4-b480-d036fa5099e8", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
item_TVitem_냉장고item_믹서item_선풍기item_전자레인지item_컴퓨터
0TrueFalseFalseFalseFalseFalse
1FalseTrueFalseFalseFalseFalse
2FalseFalseFalseFalseTrueFalse
3FalseFalseFalseFalseFalseTrue
4FalseFalseFalseTrueFalseFalse
5FalseFalseFalseTrueFalseFalse
6FalseFalseTrueFalseFalseFalse
7FalseFalseTrueFalseFalseFalse
\n", "
" ], "text/plain": [ " item_TV item_냉장고 item_믹서 item_선풍기 item_전자레인지 item_컴퓨터\n", "0 True False False False False False\n", "1 False True False False False False\n", "2 False False False False True False\n", "3 False False False False False True\n", "4 False False False True False False\n", "5 False False False True False False\n", "6 False False True False False False\n", "7 False False True False False False" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# get_dummies : 더 쉬운 원-핫 인코딩\n", "import pandas as pd\n", "\n", "df = pd.DataFrame({'item':['TV', '냉장고', '전자레인지', '컴퓨터', '선풍기', '선풍기', '믹서', '믹서']})\n", "pd.get_dummies(df)" ] }, { "cell_type": "code", "execution_count": 8, "id": "4e646468-4a42-4f03-b5f0-023cc5da8d74", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "feature 들의 평균 값\n", "sepal length (cm) 5.843333\n", "sepal width (cm) 3.057333\n", "petal length (cm) 3.758000\n", "petal width (cm) 1.199333\n", "dtype: float64\n", "\n", "feature 들의 분산 값\n", "sepal length (cm) 0.685694\n", "sepal width (cm) 0.189979\n", "petal length (cm) 3.116278\n", "petal width (cm) 0.581006\n", "dtype: float64\n" ] } ], "source": [ "#표준화: StandardScaler\n", "#표준화 전\n", "\n", "from sklearn.datasets import load_iris\n", "import pandas as pd\n", "\n", "#붓꽃 데이터 세트를 로딩하고 DF로 변환\n", "iris = load_iris()\n", "iris_data = iris.data\n", "iris_df = pd.DataFrame(data=iris_data, columns=iris.feature_names)\n", "\n", "print('feature 들의 평균 값')\n", "print(iris_df.mean())\n", "print('\\nfeature 들의 분산 값')\n", "print(iris_df.var())" ] }, { "cell_type": "code", "execution_count": 9, "id": "a3ceb2a0-c8fa-4eea-8480-ae2432e2219d", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "feature 들의 평균 값\n", "sepal length (cm) -1.690315e-15\n", "sepal width (cm) -1.842970e-15\n", "petal length (cm) -1.698641e-15\n", "petal width (cm) -1.409243e-15\n", "dtype: float64\n", "\n", "feature 들의 분산 값\n", "sepal length (cm) 1.006711\n", "sepal width (cm) 1.006711\n", "petal length (cm) 1.006711\n", "petal width (cm) 1.006711\n", "dtype: float64\n" ] } ], "source": [ "# 표준화\n", "from sklearn.preprocessing import StandardScaler\n", "\n", "#StandardScaler 객체 생성\n", "scaler = StandardScaler()\n", "#StandardScaler로 데이터 세트 변환. fit, transform 호출\n", "scaler.fit(iris_df)\n", "iris_scaled = scaler.transform(iris_df)\n", "\n", "#transform 시 스케일 변환된 데이터 세트가 NumPy ndarray로 반환돼 이를 DF로 변환\n", "iris_df_scaled = pd.DataFrame(data=iris_scaled, columns=iris.feature_names)\n", "print('feature 들의 평균 값')\n", "print(iris_df_scaled.mean())\n", "print('\\nfeature 들의 분산 값')\n", "print(iris_df_scaled.var())" ] }, { "cell_type": "code", "execution_count": 10, "id": "6ae1aac2-00e5-4565-8a05-3ae8a1e023df", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "feature 들의 최솟값\n", "sepal length (cm) 0.0\n", "sepal width (cm) 0.0\n", "petal length (cm) 0.0\n", "petal width (cm) 0.0\n", "dtype: float64\n", "\n", "feature 들의 최댓값\n", "sepal length (cm) 1.0\n", "sepal width (cm) 1.0\n", "petal length (cm) 1.0\n", "petal width (cm) 1.0\n", "dtype: float64\n" ] } ], "source": [ "#MinMax Scaler\n", "from sklearn.preprocessing import MinMaxScaler\n", "\n", "# MinMaxScaler 객체 생성\n", "scaler = MinMaxScaler()\n", "# MinMaxScaler로 데이터 세트 변환. fit, transform\n", "scaler.fit(iris_df)\n", "iris_scaled = scaler.transform(iris_df)\n", "\n", "#transform 시 스케일 변환된 데이터 세트가 NumPy ndarray로 반환돼 이를 DF로 변환\n", "iris_df_scaled = pd.DataFrame(data=iris_scaled, columns=iris.feature_names)\n", "print('feature 들의 최솟값')\n", "print(iris_df_scaled.min())\n", "print('\\nfeature 들의 최댓값')\n", "print(iris_df_scaled.max())" ] }, { "cell_type": "code", "execution_count": 11, "id": "3afae02d-1f0e-489a-957e-e8506707fabd", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "원본 train_array 데이터: [ 0 1 2 3 4 5 6 7 8 9 10]\n", "scale 된 train_array 데이터: [0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. ]\n" ] } ], "source": [ "# 데이터 스케일링 변환 시 유의점\n", "from sklearn.preprocessing import MinMaxScaler\n", "import numpy as np\n", "\n", "# 학습 데이터: 0~10, 테스트 데이터: 0~5\n", "# scaler 클래스의 fit, transform은 2차원 이상 데이터만 가능하므로 reshape(-1, 1)로 차원 변경\n", "train_array = np.arange(0, 11).reshape(-1, 1)\n", "test_array = np.arange(0, 6).reshape(-1, 1)\n", "\n", "# MinMaxScaler 객체의 별도의 feature_range 파리미터 값 미지정 시 0~1 값으로 변환\n", "scaler = MinMaxScaler()\n", "\n", "# fit() 하게 되면 train_array 데이터의 최솟값이 0, 최댓값이 10으로 설정\n", "scaler.fit(train_array)\n", "\n", "# 1/10 scale로 train_array 데이터 변환. 원본 10>1로 변환\n", "train_scaled = scaler.transform(train_array)\n", "\n", "print('원본 train_array 데이터:', np.round(train_array.reshape(-1), 2))\n", "print('scale 된 train_array 데이터:', np.round(train_scaled.reshape(-1), 2))" ] }, { "cell_type": "code", "execution_count": 12, "id": "0a6450c4-2396-4d98-a7d2-14a9caa7dd28", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "원본 test_array 데이터: [0 1 2 3 4 5]\n", "scale 된 test_array 데이터: [0. 0.2 0.4 0.6 0.8 1. ]\n" ] } ], "source": [ "# 데이터 스케일링 변환 시 유의점\n", "# 테스트 데이터 세트 변환\n", "\n", "# MinMaxScaler에 test_array 를 fit( )하게 되면 원본 데이터의 최솟값이 0, 최댓값이 5로 설정\n", "scaler.fit(test_array)\n", "\n", "# 1/5 scale로 test_array 데이터 변환. 원본 5>1로 변환\n", "test_scaled = scaler.transform(test_array)\n", "\n", "# test_array의 scale 변환 출력\n", "print('원본 test_array 데이터:', np.round(test_array.reshape(-1), 2))\n", "print('scale 된 test_array 데이터:', np.round(test_scaled.reshape(-1), 2))" ] }, { "cell_type": "code", "execution_count": 17, "id": "71bae21b-695e-43d9-b1c0-c778203d2fc1", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "원본 train_array 데이터: [ 0 1 2 3 4 5 6 7 8 9 10]\n", "scale 된 train_array 데이터: [0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. ]\n", "\n", "원본 test_array 데이터: [0 1 2 3 4 5]\n", "scale 된 test_array 데이터: [0. 0.1 0.2 0.3 0.4 0.5]\n" ] } ], "source": [ "scaler = MinMaxScaler()\n", "scaler.fit(train_array)\n", "train_scaled = scaler.transform(train_array)\n", "print('원본 train_array 데이터:', np.round(train_array.reshape(-1), 2))\n", "print('scale 된 train_array 데이터:', np.round(train_scaled.reshape(-1), 2))\n", "\n", "# test_array에 Scale 변환 시에는 반드시 fit( ) 을 호출하지 않고 transform( ) 만으로 변환해야 함\n", "test_scaled = scaler.transform(test_array)\n", "print('\\n원본 test_array 데이터:', np.round(test_array.reshape(-1), 2))\n", "print('scale 된 test_array 데이터:', np.round(test_scaled.reshape(-1), 2))" ] }, { "cell_type": "code", "execution_count": null, "id": "2ff0ba5b-391c-4e23-b6a9-1c3f9350bf8c", "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.11.7" } }, "nbformat": 4, "nbformat_minor": 5 }