레이블이 Python인 게시물을 표시합니다. 모든 게시물 표시
레이블이 Python인 게시물을 표시합니다. 모든 게시물 표시

2020년 8월 31일 월요일

PIP Install 중 disutils installed ... Error

pip로 패키지 install 중, 아래와 같은 오류가 발생할 때 해결법


- 에러메시지

Cannot uninstall 'pytz (pkg name)'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall. 


- 해결방법 : 걍 설치된 버전 무시해버려! 

pip install --ignore-installed pytz


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()

2016년 9월 1일 목요일

Tensorflow와 Docker, Jupyter 환경 설정

Docker Image를 이용하여 Tensorflow를 설치, 테스트 하는 - 몇달만에 띄우다가 까먹어서 헤깔린 내용들을 ㅠㅠ - 과정을 간단히 정리.

Docker의 특성상... 
 - 기존 환경과 완전히 격리시킬 수 있고, 
 - Light-weight container로 Host machine과 비교해도 Performance 또한 거의 손실이 없는 수준이고,  
 - 의존성 높은 tensorflow library 환경을 구축을 한번에 끝낼 수 있으니 
Tensorflow를 테스트해보고 싶은 사람에게는 Docker를 이용한 설치를 적극 추천한다. 
Production환경은 더 고려할게 많으니 논외. 

1. Docker 설치
MAC, 윈도우, 리눅스 모두 https://www.docker.com/ 에서 Installation Binary를 다운로드 받으면 쉽게 설치 가능하다. 
Docker의 Image는 Virtual Machine 이미지 자체,  이미지가 실행되어 떠 있는 아이는 Container 정도로 이해하면 쉽다. 

2. Tensorflow Docker Image Pull / Run
구글에서 제공하는 Tensorflow docker image를 다운로드 후 실행한다.
Docker는 로컬에 이미 image가 있는 경우 image를 container로 로딩, 
없으면 원격에서 image를 pulling 하여 인스톨 후 로딩한다.

간단하게 한줄이면 끝. 
$ docker run -it gcr.io/tensorflow/tensorflow  
Docker image Pull & Run
열심히 다운로드 하고, Jupyter Notebook을 띄웠다고 하고 끝난다. 

친절하게 
The Jupyter Notebook is running at: http://[all ip addresses on your system]:8888/
라고 하니, 어쩐지 늘 하던대로 http://127.0.0.1:8888/ 로 접속해 보자. 
localhost 접속 결과. 안된다.



그냥 접속하면 안된다. -_-;
docker는 container들에 virtual ip를 부여한다. 

VM IP를 확인하고... 
$ docker-machine ip default
virtual ip를 확인하자!

container port forwarding 옵션을 포함하여 다시 실행해주자.
$ docker run -it -p 8888:8888 gcr.io/tensorflow/tensorflow
port forwarding과 함께하는 docker

그리고 위에서 확인한 http://192.168.99.100:8888 로 접속해보면...
노트북 리스트가 떴다!
이렇게 jupyter가 뜨면 tensorflow 환경 간단 구축 끝. 

2016년 4월 5일 화요일

Python request package exception handling

사이트 목록을 돌며 title 내용을 가져오는 간단한 크롤링 코드를 짜서 돌리다가,
목록 중간 특정 웹사이트에서  에러가 발생하여 exception catch 처리한 내용. 기록/메모를 위해 남겨둔다.

[error msg] 
requests.exceptions.ConnectionError: HTTPConnectionPool(host='hostname', port=80): Max retries exceeded with url: hostname ...

response == none 인 경우를 잡아내 주면 보통 문제없이 돌았었는데, 이번처럼 request pkg의 ConnectionError를 handling 안해주면 죽는 경우가 생긴다. 

[Code]
import requests as rq
import bs4

header = {'User-Agent':'Mozilla/5.0'}

def get_html_title(url):        
    request = rq.Request('Get', url, headers = header)
    r = request.prepare()
    s = rq.Session()
    try: 
        response = s.send(r)
    except rq.exceptions.ConnectionError:
        return ''
    if response == None: 
        return ''
    html_content = response.text    
    navigator = bs4.BeautifulSoup(html_content, "html.parser")    
    title = navigator.find('title')
    if title == None:
        return ''
    return title.get_text() 

[Request PKG의 Exception Case]
http://docs.python-requests.org/en/latest/user/quickstart/#errors-and-exceptions

Errors and Exceptions

In the event of a network problem (e.g. DNS failure, refused connection, etc), Requests will raise aConnectionError exception.
In the rare event of an invalid HTTP response, Requests will raise an HTTPError exception.
If a request times out, a Timeout exception is raised.
If a request exceeds the configured number of maximum redirections, a TooManyRedirects exception is raised.
All exceptions that Requests explicitly raises inherit from requests.exceptions.RequestException.