{ "cells": [ { "attachments": {}, "cell_type": "markdown", "id": "6cfd2a8c-fdfc-4233-abd1-ece097069522", "metadata": {}, "source": [ "# __텍스트 분류 모델 만들기__" ] }, { "attachments": {}, "cell_type": "markdown", "id": "a8e34895-b8e4-417f-b992-6e47dd854748", "metadata": {}, "source": [ "- 튜토리얼 난이도: ★☆☆☆☆\n", "- 읽는데 걸리는 시간: 10분\n", "- 사용 언어: [SQL](https://ko.wikipedia.org/wiki/SQL) (100%)\n", "- 실행 파일 위치: tutorial/thanosql_ml/classification/text_classification.ipynb\n", "- 참고 문서: [(캐글) IMDB Movie Reviews](https://www.kaggle.com/code/lakshmi25npathi/sentiment-analysis-of-imdb-movie-reviews/data), [ELECTRA: Pre-training Text Encoders as Discriminators Rather Than Generators](https://arxiv.org/abs/2003.10555)" ] }, { "attachments": {}, "cell_type": "markdown", "id": "ac7823c2-8b90-4d7f-bbb8-2939f57583bd", "metadata": {}, "source": [ "## 튜토리얼 소개\n", "\n", "
\n", "

분류 작업 이해하기

\n", "

분류 작업은 목푯값(Target)이 속한 범주(Category 또는 Class)를 예측하기 위해 사용하는 머신러닝(기계학습/Machine Learning)의 한 형태입니다. 예를 들어, 남성 또는 여성을 분류하는 이진 분류와 동물의 종(개, 고양이, 토끼 등)을 예측하는 다중 분류 모두 분류 작업에 포함됩니다.

\n", "
\n", "\n", "[자연어 처리(NLP, Natural Language Processing)](https://ko.wikipedia.org/wiki/%EC%9E%90%EC%97%B0%EC%96%B4_%EC%B2%98%EB%A6%AC)는 인공지능의 한 분야로서 머신러닝을 사용하여 텍스트 기반 데이터를 처리하고 해석합니다.\n", "\n", "
\n", "

자연어 처리(NLP, Natural Language Processing)

\n", "

NLP는 작업의 목적에 따라 자연어 이해(NLU, Natural Language Understanding)와 자연어 생성(NLG, Natural Language Generation)으로 분류할 수 있습니다. 자연어 이해는 사람이 이해하는 자연어를 컴퓨터가 이해할 수 있는 값으로 바꾸는 처리를 의미합니다. 반면에 자연어 생성은 더 나아가 컴퓨터가 이해할 수 있는 값을 사람이 이해하도록 자연어로 바꾸는 과정을 의미합니다.

\n", "
\n", "\n", " 최근 BERT, [GPT-3](https://en.wikipedia.org/wiki/GPT-3) 등 사전 훈련 기술의 발전으로 언어를 이해하는 일반 모델을 우선 구축하고 원하는 NLP 작업 예컨대 감정 분석이나 질의 응답에 맞춰 미세 조정할 수 있게 되었습니다.\n", "\n", "
\n", "

즉, 대량의 데이터 세트에 대한 데이터 라벨링 작업을 최소화 함으로써 더욱 많은 데이터를 효율적으로 활용할 수 있습니다.

\n", "
\n", "\n", "ThanoSQL에서는 다양한 사전 훈련 된 인공지능 모델을 제공하고 있으며, 소량의 데이터 라벨링을 통해서도 쉽게 사용자만의 텍스트 분류 모델을 만들 수 있도록 다양한 기능을 제공합니다. 이를 통해, 사용자는 적절하게 학습된 텍스트 분류 모델을 활용하여 특징을 정량화하기 힘든 텍스트 데이터로부터 잠재적인 인사이트를 추출하고 다양한 서비스에 활용할 수 있습니다.\n", "\n", "__아래는 ThanoSQL 텍스트 분류 모델의 활용 및 예시입니다.__\n", "\n", "- 챗봇을 통한 상담이나 문의, 게시판 내의 텍스트의 감정 분석이나 범주 구분 작업에 텍스트 분류 모델을 쉽게 사용할 수 있게 합니다. 이 작업은 추후 고객에게 적절한 담당자와의 연결을 가능하게 합니다.\n", "- 뉴스나 게시물 공유 서비스에서 게시 콘텐츠의 그룹을 분류할 수 있게 합니다. 게시 콘텐츠의 댓글에 텍스트 분류 모델을 적용함으로써 감정 분석을 가능하게 합니다. 이 작업은 갑자기 이슈가 되거나 욕설이나 비방에 의해 발생할 수 있는 문제를 효율적으로 관리를 가능하게 합니다.\n", "\n", "
\n", "

본 튜토리얼에서는

\n", "

👉 대표적인 머신러닝 경진대회 플랫폼인 캐글의 IMDB Movie Reviews 데이터 세트를 사용하여 영화 리뷰의 감정을 분류하는 모델을 만듭니다. 이 데이터 세트는 50,000 개의 영화 리뷰 텍스트와 긍정 또는 부정 감정에 대한 목푯값(Target)으로 구성되어 있습니다. 영화 평점을 기준으로 5보다 작은 값을 부정, 7보다 큰 값을 긍정으로 표현하였으며 각 개별 영화는 30 개 이상의 리뷰 결과를 갖지 않습니다.

\n", "
\n", "\n", "
\n", "

튜토리얼 주의 사항

\n", " \n", "
" ] }, { "attachments": {}, "cell_type": "markdown", "id": "da62c91d-d726-4a7a-96b8-4a52b84b372a", "metadata": {}, "source": [ "## __0. 데이터 세트 및 모델 준비__\n", "\n", "ThanoSQL의 쿼리 구문을 사용하기 위해서는 [ThanoSQL 워크스페이스](https://docs.thanosql.ai/1.4/ko/getting_started/paas/workspace/lab/)에서 언급된 것처럼 API 토큰을 생성하고 아래의 쿼리를 실행해야 합니다." ] }, { "cell_type": "code", "execution_count": null, "id": "673f3d5d-8e1d-4fbd-ae09-3b8868957d31", "metadata": {}, "outputs": [], "source": [ "%load_ext thanosql\n", "%thanosql API_TOKEN=<발급받은_API_TOKEN>" ] }, { "attachments": {}, "cell_type": "markdown", "id": "a3fc89e5-600a-4c5f-bba2-289a425db405", "metadata": {}, "source": [ "### __데이터 세트 준비__" ] }, { "cell_type": "code", "execution_count": 2, "id": "ad07a885-ee2e-4eeb-a2f0-634af9b3b843", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Success\n" ] } ], "source": [ "%%thanosql\n", "GET THANOSQL DATASET movie_review_data\n", "OPTIONS (overwrite=True)" ] }, { "attachments": {}, "cell_type": "markdown", "id": "77319ae0", "metadata": {}, "source": [ "
\n", "

쿼리 세부 정보

\n", " \n", "
" ] }, { "cell_type": "code", "execution_count": 3, "id": "be768992-c5db-416a-803d-0e90bb42fbcd", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Success\n" ] } ], "source": [ "%%thanosql\n", "COPY movie_review_train\n", "OPTIONS (if_exists='replace')\n", "FROM 'thanosql-dataset/movie_review_data/movie_review_train.csv'" ] }, { "cell_type": "code", "execution_count": 4, "id": "418d182d-db65-4865-b128-869baab37523", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Success\n" ] } ], "source": [ "%%thanosql\n", "COPY movie_review_test\n", "OPTIONS (if_exists='replace')\n", "FROM 'thanosql-dataset/movie_review_data/movie_review_test.csv'" ] }, { "attachments": {}, "cell_type": "markdown", "id": "08d1f4e2", "metadata": {}, "source": [ "
\n", "

쿼리 세부 정보

\n", " \n", "
" ] }, { "attachments": {}, "cell_type": "markdown", "id": "bfab432b-32e0-4352-97cd-b9f2efd17640", "metadata": {}, "source": [ "### __모델 준비__" ] }, { "cell_type": "code", "execution_count": 5, "id": "ca098b9e-2b48-4965-9fd9-e58df2252472", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Success\n" ] } ], "source": [ "%%thanosql\n", "GET THANOSQL MODEL electra\n", "OPTIONS (\n", " model_name='tutorial_text_classification',\n", " overwrite=True\n", " )" ] }, { "attachments": {}, "cell_type": "markdown", "id": "0909b332", "metadata": {}, "source": [ "
\n", "

쿼리 세부 정보

\n", " \n", "
" ] }, { "attachments": {}, "cell_type": "markdown", "id": "e557a156-1075-41df-b19f-ff0812a14b4c", "metadata": {}, "source": [ "## __1. 데이터 세트 확인__\n", "\n", "영화 리뷰 감정 분류 모델을 만들기 위해 ThanoSQL 워크스페이스 데이터베이스에 저장되어 있는 __movie_review_train__ 테이블을 사용합니다. 아래의 쿼리 구문을 실행하고 테이블의 내용을 확인합니다." ] }, { "cell_type": "code", "execution_count": 6, "id": "49d801df-54d2-4809-bbed-69b2818e9cec", "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", "
reviewsentiment
0This is the kind of movie that BEGS to be show...negative
1Bulletproof is quite clearly a disposable film...negative
2A beautiful shopgirl in London is swept off he...positive
3VERY dull, obvious, tedious Exorcist rip-off f...negative
4Do we really need any more narcissistic garbag...negative
\n", "
" ], "text/plain": [ " review sentiment\n", "0 This is the kind of movie that BEGS to be show... negative\n", "1 Bulletproof is quite clearly a disposable film... negative\n", "2 A beautiful shopgirl in London is swept off he... positive\n", "3 VERY dull, obvious, tedious Exorcist rip-off f... negative\n", "4 Do we really need any more narcissistic garbag... negative" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "%%thanosql\n", "SELECT *\n", "FROM movie_review_train\n", "LIMIT 5" ] }, { "attachments": {}, "cell_type": "markdown", "id": "35132dce", "metadata": {}, "source": [ "
\n", "

데이터 테이블 이해하기

\n", "

movie_review_train 테이블은 아래와 같은 정보를 담고 있습니다.

\n", " \n", "
" ] }, { "attachments": {}, "cell_type": "markdown", "id": "d7c83528-ebc6-4a88-a29f-31afc0516935", "metadata": {}, "source": [ "## __2. 사전 학습된 모델을 사용하여 영화 리뷰 감정 분류 결과 예측__\n", "\n", "다음 쿼리 구문을 실행하여 __tutorial_text_classification__ 모델을 사용하여 결과를 예측합니다." ] }, { "cell_type": "code", "execution_count": 7, "id": "ae7a9324-9c5e-4be4-a933-8774bbdd01c9", "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", "
reviewsentimentpredict_result
0I read the book before seeing the movie, and t...positivepositive
1\"9/11,\" hosted by Robert DeNiro, presents foot...positivepositive
2Yesterday I attended the world premiere of \"De...positivepositive
3Moonwalker is a Fantasy Music film staring Mic...positivepositive
4Welcome to Oakland, where the dead come out to...positivepositive
............
995I remember catching this movie on one of the S...negativenegative
996CyberTracker is set in Los Angeles sometime in...negativenegative
997There is so much that is wrong with this film,...negativenegative
998I am a firm believer that a film, TV serial or...positivepositive
999I think vampire movies (usually) are wicked. E...negativenegative
\n", "

1000 rows × 3 columns

\n", "
" ], "text/plain": [ " review sentiment \\\n", "0 I read the book before seeing the movie, and t... positive \n", "1 \"9/11,\" hosted by Robert DeNiro, presents foot... positive \n", "2 Yesterday I attended the world premiere of \"De... positive \n", "3 Moonwalker is a Fantasy Music film staring Mic... positive \n", "4 Welcome to Oakland, where the dead come out to... positive \n", ".. ... ... \n", "995 I remember catching this movie on one of the S... negative \n", "996 CyberTracker is set in Los Angeles sometime in... negative \n", "997 There is so much that is wrong with this film,... negative \n", "998 I am a firm believer that a film, TV serial or... positive \n", "999 I think vampire movies (usually) are wicked. E... negative \n", "\n", " predict_result \n", "0 positive \n", "1 positive \n", "2 positive \n", "3 positive \n", "4 positive \n", ".. ... \n", "995 negative \n", "996 negative \n", "997 negative \n", "998 positive \n", "999 negative \n", "\n", "[1000 rows x 3 columns]" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "%%thanosql\n", "PREDICT USING tutorial_text_classification\n", "OPTIONS (\n", " text_col='review'\n", " )\n", "AS\n", "SELECT *\n", "FROM movie_review_test" ] }, { "attachments": {}, "cell_type": "markdown", "id": "e9b4137e-75ad-4bea-bda0-0c7fcdb3b72b", "metadata": {}, "source": [ "## __3. 텍스트 분류 모델 생성__\n", "\n", "이전 단계에서 확인한 __movie_review_train__ 테이블을 사용하여 텍스트 분류 모델을 만듭니다. 아래의 쿼리 구문을 실행하여 my_movie_review_classifier라는이라는 이름의 모델을 만듭니다. \n", "(쿼리 실행 시 예상 소요 시간: 3 min)" ] }, { "cell_type": "code", "execution_count": 8, "id": "8ffb0317-476e-409f-baa3-dc562d924e99", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Success\n" ] } ], "source": [ "%%thanosql\n", "BUILD MODEL my_movie_review_classifier\n", "USING ElectraEn\n", "OPTIONS (\n", " text_col='review',\n", " label_col='sentiment',\n", " max_epochs=1,\n", " batch_size=4,\n", " overwrite=True\n", " )\n", "AS\n", "SELECT *\n", "FROM movie_review_train" ] }, { "attachments": {}, "cell_type": "markdown", "id": "836ffcb0", "metadata": {}, "source": [ "
\n", "

쿼리 세부 정보

\n", " \n", "
\n", "\n", "
\n", "

여기서는 빠르게 학습하기 위해 \"max_epochs\"를 1로 지정했습니다. 일반적으로 숫자가 클수록 많은 계산 시간이 소요되지만 학습이 진행됨에 따라 예측 성능이 올라갑니다.

\n", "
" ] }, { "attachments": {}, "cell_type": "markdown", "id": "d6402263-ff45-45e8-b221-27c1ff97c556", "metadata": {}, "source": [ "## __4. 생성된 모델을 사용하여 영화 리뷰 감정 분류 결과 예측__\n", "\n", "이전 단계에서 생성한 텍스트 분류 모델을 사용해 특정 리뷰를 예측해 봅니다. 테스트용 데이터 세트(학습에 이용되지 않은 데이터 테이블, movie_review_test)를 사용합니다." ] }, { "cell_type": "code", "execution_count": 9, "id": "530b828d-962c-4115-a417-59ca2c621e98", "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", "
reviewsentimentpredict_result
0I read the book before seeing the movie, and t...positivepositive
1\"9/11,\" hosted by Robert DeNiro, presents foot...positivepositive
2Yesterday I attended the world premiere of \"De...positivepositive
3Moonwalker is a Fantasy Music film staring Mic...positivepositive
4Welcome to Oakland, where the dead come out to...positivenegative
............
995I remember catching this movie on one of the S...negativenegative
996CyberTracker is set in Los Angeles sometime in...negativenegative
997There is so much that is wrong with this film,...negativenegative
998I am a firm believer that a film, TV serial or...positivepositive
999I think vampire movies (usually) are wicked. E...negativenegative
\n", "

1000 rows × 3 columns

\n", "
" ], "text/plain": [ " review sentiment \\\n", "0 I read the book before seeing the movie, and t... positive \n", "1 \"9/11,\" hosted by Robert DeNiro, presents foot... positive \n", "2 Yesterday I attended the world premiere of \"De... positive \n", "3 Moonwalker is a Fantasy Music film staring Mic... positive \n", "4 Welcome to Oakland, where the dead come out to... positive \n", ".. ... ... \n", "995 I remember catching this movie on one of the S... negative \n", "996 CyberTracker is set in Los Angeles sometime in... negative \n", "997 There is so much that is wrong with this film,... negative \n", "998 I am a firm believer that a film, TV serial or... positive \n", "999 I think vampire movies (usually) are wicked. E... negative \n", "\n", " predict_result \n", "0 positive \n", "1 positive \n", "2 positive \n", "3 positive \n", "4 negative \n", ".. ... \n", "995 negative \n", "996 negative \n", "997 negative \n", "998 positive \n", "999 negative \n", "\n", "[1000 rows x 3 columns]" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "%%thanosql\n", "PREDICT USING my_movie_review_classifier\n", "OPTIONS (\n", " text_col='review',\n", " result_col='predict_result'\n", " )\n", "AS\n", "SELECT *\n", "FROM movie_review_test" ] }, { "attachments": {}, "cell_type": "markdown", "id": "cfd2e6c3-ebc8-404f-bd51-23d91c7a7de3", "metadata": { "tags": [] }, "source": [ "
\n", "

쿼리 세부 정보

\n", " \n", "
" ] }, { "attachments": {}, "cell_type": "markdown", "id": "9001d3db", "metadata": {}, "source": [ "## __5. 튜토리얼을 마치며__\n", "\n", "이번 튜토리얼에서는 IMDB Movie Reviews 데이터 세트를 사용하여 텍스트 분류 모델을 만들어 보았습니다. 초급 단계 튜토리얼인만큼 정확도 향상을 위한 과정 설명보다는 작동 위주의 설명으로 진행했습니다. 텍스트 분류 모델은 각 플랫폼이나 서비스에 맞는 정밀한 튜닝을 통해 정확도를 향상 시킬 수 있습니다. 나만의 데이터를 이용해서 베이스 모델을 학습하거나, [자가학습(Self-supervised Learning)](https://ko.wikipedia.org/wiki/%EC%9E%90%EA%B8%B0_%EC%A7%80%EB%8F%84_%ED%95%99%EC%8A%B5) 모델 등을 이용해 나의 데이터를 수치화하여 변환한 후 자동화 된 머신러닝(AutoML) 기법을 이용한 배포 또한 가능합니다. 다양한 비정형 데이터(이미지, 오디오, 비디오 등)와 수치형 데이터들을 결합하여 나만의 모델을 만들고 경쟁력있는 서비스를 제공해 보세요.\n", "\n", "* [나만의 데이터 업로드하기](https://docs.thanosql.ai/1.4/ko/getting_started/data_upload/)\n", "* [나만의 데이터 테이블 생성하기](https://docs.thanosql.ai/1.4/ko/how-to_guides/ThanoSQL_query/COPY_SYNTAX/)\n", "* [나만의 모델 업로드하기](https://docs.thanosql.ai/1.4/ko/how-to_guides/ThanoSQL_query/UPLOAD_MODEL_SYNTAX/)\n", "\n", "
\n", "

나만의 서비스를 위한 모델 배포 관련 문의

\n", "

ThanoSQL을 활용해 나만의 모델을 만들거나, 나의 서비스에 적용하는데 어려움이 있다면 언제든 아래로 문의주세요😊

\n", "

텍스트 분류 모델 구축 관련 문의: contact@smartmind.team

\n", "
" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "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.9.13 (v3.9.13:6de2ca5339, May 17 2022, 11:37:23) \n[Clang 13.0.0 (clang-1300.0.29.30)]" }, "toc-autonumbering": false, "vscode": { "interpreter": { "hash": "aee8b7b246df8f9039afb4144a1f6fd8d2ca17a180786b69acc140d282b71a49" } } }, "nbformat": 4, "nbformat_minor": 5 }