From 8baa54baa1e43cbbd2e271098faa1ec085ff1ebf Mon Sep 17 00:00:00 2001 From: goforit615 Date: Mon, 22 Jun 2026 19:09:22 +0900 Subject: [PATCH] update ml-05 --- ...5\231\354\212\265_Linear_Classifier.ipynb" | 399 ++++++++++++++++++ 1 file changed, 399 insertions(+) create mode 100644 "ml_05_\354\247\200\353\217\204\355\225\231\354\212\265_Linear_Classifier.ipynb" diff --git "a/ml_05_\354\247\200\353\217\204\355\225\231\354\212\265_Linear_Classifier.ipynb" "b/ml_05_\354\247\200\353\217\204\355\225\231\354\212\265_Linear_Classifier.ipynb" new file mode 100644 index 0000000..40c73f2 --- /dev/null +++ "b/ml_05_\354\247\200\353\217\204\355\225\231\354\212\265_Linear_Classifier.ipynb" @@ -0,0 +1,399 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "id": "JpPDNLyjxy2-" + }, + "source": [ + "# Linear Classifier (선형분류)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "UyQchOwzx2eo" + }, + "source": [ + "- 계산한 값이 0보다 작은 클래스는 -1, 0보다 크면 +1이라고 예측(분류)\n", + "> ŷ = w[0] * x[0] + w[1] * x[1] + … + w[p] * x[p] + b > 0
\n", + "> Linear Regression와 매우 비슷하지만 가중치(w) 합을 사용하는 대신 예측한 값을 임계치 0 과 비교\n", + "\n", + "- 이진 선형 분류기는 선, 평면, 초평면을 이용하여 2개의 클래스를 구분하는 분류기\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "DDseWGpl6e03" + }, + "source": [ + "경사하강법(Gradient Descent) 최적화 알고리즘을 사용하여 선형 모델을 작성\n", + "\n", + "[SGDClassifier()](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.SGDClassifier.html)\n", + "\n", + "```\n", + "SGDClassifier(alpha, average, class_weight, epsilon, eta0, fit_intercept, l1_ratio, learning_rat, loss, max_iter, n_iter, n_jobs, penalty, power_t, random_state, shuffle, tol, verbose, warm_start)\n", + "```\n", + "확률적 경사하강법(SGD, Stochastic Gradient Descent)을 이용하여 선형모델을 구현\n", + "\n", + "- lossstr : 손실함수 (default='hinge')\n", + "- penalty : {'l2', 'l1', 'elasticnet'}, default='l2'\n", + "- alpha : 값이 클수록 강력한 정규화(규제) 설정 (default=0.0001)\n", + "- l1_ratio : L1 규제의 비율(Elastic-Net 믹싱 파라미터 경우에만 사용) (default=0.15)\n", + "- fit_intercept : 모형에 상수항 (절편)이 있는가 없는가를 결정하는 인수 (default=True)\n", + "- max_iter : 계산에 사용할 작업 수 (default=1000)\n", + "- tol : 정밀도\n", + "- shuffle : 에포크 후에 트레이닝 데이터를 섞는 유무 (default=True)\n", + "- epsilon : 손실 함수에서의 엡실론, 엡실론이 작은 경우, 현재 예측과 올바른 레이블 간의 차이가 임계 값보다 작으면 무시 (default=0.1)\n", + "- n_jobs : 병렬 처리 할 때 사용되는 CPU 코어 수\n", + "- random_state : 난수 seed 설정\n", + "- learning_rate : 학습속도 (default='optimal')\n", + "- eta0 : 초기 학습속도 (default=0.0)\n", + "- power_t : 역 스케일링 학습률 (default=0.5)\n", + "- early_stopping : 유효성 검사 점수가 향상되지 않을 때 조기 중지여부 (default=False)\n", + "- validation_fraction : 조기 중지를위한 검증 세트로 설정할 교육 데이터의 비율 (default=0.1)\n", + "- n_iter_no_change : 조기중지 전 반복횟수 (default=5)\n", + "- class_weight : 클래스와 관련된 가중치 {class_label: weight} or “balanced”, default=None\n", + "- warm_start : 초기화 유무 (default=False)\n", + "- average : True로 설정하면 모든 업데이트에 대한 평균 SGD 가중치를 계산하고 결과를 coef_속성에 저장 (default=False)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "7AuxaPtIEKD-" + }, + "source": [ + "#### LinearClassifier 실습 01\n", + "\n", + "붓꽃 데이터 셋에 선형분류 적용" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "executionInfo": { + "elapsed": 281, + "status": "ok", + "timestamp": 1715230391939, + "user": { + "displayName": "박병운", + "userId": "04400398390095856511" + }, + "user_tz": -540 + }, + "id": "X4AvkNOtroC2", + "outputId": "dae5715b-daf2-452f-84af-88b90ce813ce" + }, + "outputs": [], + "source": [ + "from sklearn.datasets import load_iris\n", + "iris = load_iris()\n", + "iris.keys()\n", + "iris.data.shape\n", + "iris.target" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "executionInfo": { + "elapsed": 6, + "status": "ok", + "timestamp": 1715230442569, + "user": { + "displayName": "박병운", + "userId": "04400398390095856511" + }, + "user_tz": -540 + }, + "id": "MpWiOqZ_uuEL", + "outputId": "09cc5067-452e-4192-dbed-c1fe8cbd7caa" + }, + "outputs": [], + "source": [ + "X = \n", + "y = \n", + "# 꽃받침의 길이와 넓이\n", + "X2 = \n", + "X2[:5]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 450 + }, + "executionInfo": { + "elapsed": 825, + "status": "ok", + "timestamp": 1715230489049, + "user": { + "displayName": "박병운", + "userId": "04400398390095856511" + }, + "user_tz": -540 + }, + "id": "6omzP2HdvNUB", + "outputId": "b5d1f00b-0d87-486b-f552-8a169e0cbc50" + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n", + "%matplotlib inline\n", + "\n", + "plt.scatter(...)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 450 + }, + "executionInfo": { + "elapsed": 948, + "status": "ok", + "timestamp": 1715230606664, + "user": { + "displayName": "박병운", + "userId": "04400398390095856511" + }, + "user_tz": -540 + }, + "id": "hNcT6dFuvuj6", + "outputId": "25ea7b57-b3d1-424e-a46a-554654e5b687" + }, + "outputs": [], + "source": [ + "y2 = \n", + "y2[y2 == 2] = 1\n", + "plt.scatter(... )" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "executionInfo": { + "elapsed": 266, + "status": "ok", + "timestamp": 1715230713993, + "user": { + "displayName": "박병운", + "userId": "04400398390095856511" + }, + "user_tz": -540 + }, + "id": "7P5trqnBvyca", + "outputId": "6f52a885-82bb-430d-eb2c-32b476f449e4" + }, + "outputs": [], + "source": [ + "from sklearn.model_selection import train_test_split\n", + "\n", + "X_train, X_test, y_train, y_test = ...\n", + "X_train.shape" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "executionInfo": { + "elapsed": 256, + "status": "ok", + "timestamp": 1715230843394, + "user": { + "displayName": "박병운", + "userId": "04400398390095856511" + }, + "user_tz": -540 + }, + "id": "XWd4ENPevyZp", + "outputId": "241c39a5-e686-4d04-b60e-b6177f92fb7e" + }, + "outputs": [], + "source": [ + "from sklearn.linear_model import SGDClassifier\n", + "model = ...\n", + "model....\n", + "model...." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "executionInfo": { + "elapsed": 3, + "status": "ok", + "timestamp": 1715230875231, + "user": { + "displayName": "박병운", + "userId": "04400398390095856511" + }, + "user_tz": -540 + }, + "id": "tmsHD-bkvyWx", + "outputId": "7f23e972-9575-4fdb-d8c8-0e4a9fd1522e" + }, + "outputs": [], + "source": [ + "model...., model...." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 447 + }, + "executionInfo": { + "elapsed": 951, + "status": "ok", + "timestamp": 1715231130615, + "user": { + "displayName": "박병운", + "userId": "04400398390095856511" + }, + "user_tz": -540 + }, + "id": "2EOUe4CNvyT6", + "outputId": "bbb89b79-27bf-4390-a838-e01b61d735ce" + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "\n", + "w0 = ...\n", + "w1 = ...\n", + "b = ...\n", + "\n", + "plt....\n", + "x0 = ...\n", + "x1 = ...\n", + "plt.plot(x0, x1)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "Xb7SWFmlroDd" + }, + "source": [ + "#### 4개 속성 모두 이용\n", + "\n", + "세가지 꽃 구분" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "executionInfo": { + "elapsed": 286, + "status": "ok", + "timestamp": 1715231337213, + "user": { + "displayName": "박병운", + "userId": "04400398390095856511" + }, + "user_tz": -540 + }, + "id": "EcJl93ESroDe", + "outputId": "44e40dc8-ab01-481c-bc4a-909ec0f71077" + }, + "outputs": [], + "source": [ + "from sklearn import datasets\n", + "from sklearn.linear_model import SGDClassifier\n", + "from sklearn import metrics\n", + "\n", + "iris = ...\n", + "X, y = ...\n", + "X_train, X_test, y_train, y_test = ...\n", + "model = ...\n", + "model....\n", + "model...., model...." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "executionInfo": { + "elapsed": 2, + "status": "ok", + "timestamp": 1715231368093, + "user": { + "displayName": "박병운", + "userId": "04400398390095856511" + }, + "user_tz": -540 + }, + "id": "j26qqvkj2gIP", + "outputId": "0e135773-81aa-4c20-a3c7-65a6625fa462" + }, + "outputs": [], + "source": [ + "model...." + ] + } + ], + "metadata": { + "colab": { + "provenance": [] + }, + "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.9" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +}