2017년 3월 14일 화요일

박근혜 탄핵 결정문 전문 Word2Vec Visualization w/Tensorflow


https://www.lawtimes.co.kr/Legal-News/Legal-News-View…
헌법재판소의 박근혜 탄핵 결정문 전문을 이용하여,
gensim으로 word2vec model을 만들고 Tensorflow의 embedding projector에 올려봤다.

탄핵 결정문을 읽어보다가 이정미 재판관이 낭독한 판결문과는 다가오는 느낌이 또 달라서, 
- 낭독버전과는 달리 세월호를 비롯하여 불성실한 직무 수행과 관련하여 구체적으로 짚어간다 - 
겸사겸사 word2vec과 Tensorboard를 사용해 보기로 하고 konlpy를 이용한 tokenizing과 간단한 수준의 전처리만 적용하고 돌려봤다.
전처리와 파라미터 튜닝에 시간을 더 쓰면 좀 더 깔끔하게 볼 수 있지 않았을까 싶지만 뭐 간단히만..

'머리'와 '손질', 그리고 그 아래로는 '탈출', 우측으로는 '출입문' 등등이 있는게 참 씁쓸하다.

아래는 Jupyter notebook에서 python으로 export시킨 코드. 
수행 후 tensorboard를 띄우면 됨.

# coding: utf-8

# 

# #### Gensim model building

# In[98]:

# Import required modules
import gensim, codecs
import re

# In[99]:

sentences_vocab = []
for line in codecs.open('impeachment_sentence.txt', encoding='utf-8'):
    sentences = [word+'다.' for word in line.split('다. ') if word!='\n']
    for sentence in sentences:
        sentence = re.sub('\\n다.' , '' ,sentence)
        sentence = re.sub('\\u3000.' , '' ,sentence)
        sentences_vocab.append(sentence)   

# In[101]:

from konlpy.tag import Twitter
pos_tagger = Twitter()

def tokenize(doc):
    return ['/'.join(t) for t in pos_tagger.pos(doc, norm=True, stem=True) ]

# In[102]:

tokenize('전국경제인연합회(다음부터 \'전경련\'이라 한다)가 주도하여 만든 것으로 알려져있던')

# In[103]:

# Preprocessing
sentences_vocab = []
for line in codecs.open('impeachment_sentence.txt', encoding='utf-8'):
    sentences = [word+'다.' for word in line.split('다. ') if word!='\n']
    for sentence in sentences:
        sentences_vocab.append(tokenize(sentence))

# In[104]:

sentences_vocab[41]

# In[105]:

import multiprocessing 
config = { 'min_count': 1, 
          'size': 300, 
          'sg': 1, 
          'batch_words': 10, 
          'iter': 100, 
          'workers': multiprocessing.cpu_count(), } 

model = gensim.models.Word2Vec(**config)

# In[106]:

model.build_vocab(sentences_vocab)

# In[140]:

num_w2v = len(model.wv.index2word)
print (num_w2v)

# In[141]:

import numpy as np
w2v = np.zeros((num_w2v,300))
with open("./projector/metadata.tsv", 'w+') as file_metadata:
    for i,word in enumerate(model.wv.index2word):
        w2v[i] = model[word]
        file_metadata.write(word + '\n')

# #### Tensorflow Visualization

# In[134]:

import tensorflow as tf
from tensorflow.contrib.tensorboard.plugins import projector
import numpy as np

# setup a TensorFlow session
tf.reset_default_graph()
sess = tf.InteractiveSession()

X = tf.Variable([0.0], name='embedding')
place = tf.placeholder(tf.float32, shape=[None, 300])
set_x = tf.assign(X, place, validate_shape=False)

sess.run(tf.global_variables_initializer())
sess.run(set_x, feed_dict={place: w2v})

# create a TensorFlow summary writer
summary_writer = tf.summary.FileWriter('projector', sess.graph)
config = projector.ProjectorConfig()
embedding_conf = config.embeddings.add()
embedding_conf.tensor_name = 'embedding:0'
embedding_conf.metadata_path = './projector/metadata.tsv' 
projector.visualize_embeddings(summary_writer, config)

# save the model
saver = tf.train.Saver()
saver.save(sess, './projector/model.ckpt')
sess.close()

댓글 2개:

  1. 안녕하세요 글잘보았습니다~^^
    텍스트 마이닝에 대해 배우고 있는 학생입니다.
    혹시 metadata.tsv 파일은 어떻게 생성하는지요?

    답글삭제
    답글
    1. 위 소스에서 이 부분이 metadata.tsv 를 생성하는 과정입니다.

      with open("./projector/metadata.tsv", 'w+') as file_metadata:
      for i,word in enumerate(model.wv.index2word):
      w2v[i] = model[word]
      file_metadata.write(word + '\n')

      삭제