{ "cells": [ { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "_ZG8oPMdvmxt" }, "source": [ "\n", "# **Chapter 3 | word2vec**\n", "## **1 데이터 전처리**\n", "[**word2vec matplotlib**](https://www.kaggle.com/jeffd23/visualizing-word-vectors-with-t-sne)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 1599 }, "colab_type": "code", "id": "gRW2JOSHvmxv", "outputId": "0b8ea769-0354-4693-c389-340526dc7707" }, "outputs": [], "source": [ "! apt-get update\n", "! apt-get install g++ openjdk-8-jdk \n", "! pip3 install nltk konlpy wordcloud matplotlib gensim \n", "\n", "! apt-get install fonts-nanum*\n", "! apt-get install fontconfig\n", "! fc-cache -fv\n", "! cp /usr/share/fonts/truetype/nanum/Nanum* /usr/local/lib/python3.6/dist-packages/matplotlib/mpl-data/fonts/ttf/\n", "! rm -rf /content/.cache/matplotlib/*\n", "\n", "script_text = \"https://raw.githubusercontent.com/YongBeomKim/nltk_rnd/master/data/movie_memories_of_murder_2003.txt\"\n", "font_file = \"/usr/local/lib/python3.6/dist-packages/matplotlib/mpl-data/fonts/ttf/NanumGothicCoding.ttf\"\n", "# script_text = \"../data/movie_memories_of_murder_2003.txt\"\n", "# font_file = \"../data/D2Coding.ttf\"\n", "\n", "import matplotlib as mpl \n", "import matplotlib.pyplot as plt\n", "import matplotlib.font_manager as fm\n", "\n", "font_name = fm.FontProperties(fname=font_file, size=10).get_name()\n", "plt.rc('font', family=font_name)\n", "fm._rebuild()\n", "mpl.rcParams['axes.unicode_minus'] = False" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "goJpTIIuvmx1" }, "outputs": [], "source": [ "%matplotlib inline\n", "from sklearn.manifold import TSNE\n", "import matplotlib.pyplot as plt\n", "\n", "def tsne_plot(model, figsize=(12,12)):\n", " \"Creates and TSNE model and plots it\"\n", " labels, tokens = [], []\n", " for word in model.wv.vocab:\n", " tokens.append(model[word])\n", " labels.append(word)\n", "\n", " tsne_model = TSNE(n_components=2)\n", " new_values = tsne_model.fit_transform(tokens)\n", "\n", " x, y = [], []\n", " for value in new_values:\n", " x.append(value[0])\n", " y.append(value[1])\n", "\n", " plt.figure(figsize=figsize) \n", " for i in range(len(x)):\n", " plt.scatter(x[i],y[i])\n", " plt.annotate(labels[i],\n", " xy = (x[i], y[i]),\n", " fontsize=15)\n", " plt.grid(True)\n", " plt.show()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "GvRrHEUlvmx3" }, "outputs": [], "source": [ "# 텍스트를 줄단위로 끊어서 불러온뒤\n", "# Token 단위로, 한글명사들을 추출한다\n", "def txtnoun(sentences , skip=False, tags=['Noun'], stem=True, set_tokens=False):\n", "\n", " r\"\"\"\n", " 살인의 추억 대본의 텍스트 전처리 작업을 진행합니다\n", " :param sentences: 단일한 Text String 데이터를 입력합니다\n", " :param skip: 분류된 Token 중 사용자가 원하는 형태로 변환된 내용을 출력\n", " :param tags: konlpy 로 분류된 품사중 추출하고자 하는 품사를 정의합니다\n", " :param stem: stemming 작업여부를 정의합니다.\n", " :param set_tokens: return 결과를 token list 객체로 출력할지를 정의합니다\n", " :return: set_tokens 내용에 따라 List, String 타입으로 출력합니다\n", " \"\"\"\n", " \n", " import re\n", " from konlpy.tag import Okt\n", " twitter = Okt()\n", " result = []\n", " sentences = sentences.replace('\\n', '\\n|')\n", " sentences = sentences.split('|')\n", " for content in sentences:\n", " texts = content.replace('\\n', '') # 해당줄의 줄바꿈 내용 제거\n", " tokenizer = re.compile(r'[^ ㄱ-힣]+') # 한글과 띄어쓰기를 제외한 모든 글자를 선택\n", " token_data = tokenizer.sub('', texts) # 한글과 띄어쓰기를 제외한 모든 부분을 제거\n", " token_data = token_data.split(' ')\n", " sentence = []\n", "\n", " for token in token_data:\n", " # skip 대상이 없을 떄\n", " if skip == False:\n", " chk_tok = twitter.pos(token, stem=stem)\n", " chk_tok = [temp[0] for temp in chk_tok if temp[1] in tags]\n", " ckeck = \"\".join(chk_tok)\n", " if len(ckeck) > 1:\n", " sentence.append(ckeck)\n", "\n", " # skip 내용이 있을 때\n", " else:\n", " if token.strip() in skip.keys():\n", " result.append(skip[token.strip()])\n", " else:\n", " chk_tok = twitter.pos(token, stem=stem)\n", " chk_tok = [temp[0] for temp in chk_tok if temp[1] in tags]\n", " ckeck = \"\".join(chk_tok)\n", "\n", " # 전처리가 끝난 결과가 skip에 해당여부 판단\n", " if ckeck.strip() in skip.keys():\n", " result.append(skip[ckeck.strip()])\n", " elif len(ckeck) > 1:\n", " sentence.append(ckeck)\n", "\n", " # 단락별 작업이 끝난 뒤 '\\n'를 덧붙여서 작업을 종료\n", " temp = \"\".join(sentence)\n", " if len(temp) > 1:\n", " sentence = \" \".join(sentence)\n", " sentence += \"\\n\"\n", " result.append(sentence)\n", "\n", " if set_tokens == True:\n", " from nltk.tokenize import word_tokenize\n", " set_token = word_tokenize(\" \".join(result))\n", " return list(set(set_token))\n", "\n", " else:\n", " return \" \".join(result)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "0e2HAbQcvmx5" }, "outputs": [], "source": [ "skips = {'두만':'박두만', '태윤':'서태윤', '용구':'조용구', '귀옥':'권귀옥', \n", " '희봉':'구희봉', '동철':'신동철', '광호':'백광호', '병순':'조병순', \n", " '해일':'박해일', '광호의':'백광호', '백광호의':'백광호'}" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 55 }, "colab_type": "code", "id": "mWa5GB5Mvmx7", "outputId": "9c2282b6-1094-4059-eb4e-4e6657b3c961" }, "outputs": [], "source": [ "import requests\n", "sentences = requests.get(script_text).text\n", "sentences[:300]\n", "\n", "# with open(script_text, 'r') as f:\n", "# sentences = f.read()\n", "# sentences[:300]" ] } ], "metadata": { "colab": { "collapsed_sections": [], "name": "03-Word2Vec.ipynb", "provenance": [], "version": "0.3.2" }, "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.6.3" } }, "nbformat": 4, "nbformat_minor": 2 }