Python(212)
-
[vscode] 원격서버에서 docker container 접속하기
일단 원격을 접속하려면 docker는 굳이 설치할 필요가 없다고 한다. 원격 서버에서 docker container를 접속하려면, local (노트북) 같은 곳에서도 docker를 설치해줘야 한다. 현재 환경 local : windows 10 원격 : 16.04 docker 설치 docs.docker.com/docker-for-windows/install/ Install Docker Desktop on Windows docs.docker.com hub.docker.com/editions/community/docker-ce-desktop-windows/ Docker Desktop for Windows - Docker Hub Docker Desktop for Windows Docker Desktop for ..
2021.02.06 -
[PyGAD] Python 에서 Genetic Algorithm 을 사용해보기
파이썬에서 genetic algorithm을 사용하는 패키지들을 다 사용해보진 않았지만, 확장성이 있어 보이고, 시도할 일이 있어서 살펴봤다. 이 패키지에서 가장 인상 깊었던 것은 neural network에서 hyper parameter 탐색을 gradient descent 방식이 아닌 GA로도 할 수 있다는 것이다. 개인적으로 이 부분이 어느정도 초기치를 잘 잡아줄 수 있는 역할로도 쓸 수 있고, Loss가 gradient descent 하기 어려운 구조에서 대안으로 쓸 수 있을 것으로도 생각된다. 일단 큰 흐름은 다음과 같이 된다. 사실 완전히 흐름이나 각 parameter에 대한 이해는 부족한 상황 import pygad import numpy function_inputs = [4,-2,3.5,5..
2021.01.30 -
[Python] Icecream 패키지를 사용하여 디버깅하기
파이썬 코딩을 하다 보면, 모르는 부분에 디버깅 툴이 없다면, print를 해서 찾는 경우가 많다. 필자도 print로 하나하나 하는 습관이 많이 있었지만, 실수가 있기 때문에 디버깅에 어려움을 느낀다. 그래서 어쩌다 찾게된 패키지가 icecream이다. 해당 패키지를 사용하게 되면 디버깅 시에는 프린트가 되게 하고, 안될 때에는 전부 다 안되게 할 수 있는 설정이 있다. 아래와 같이 debug시에는 사용하는 모드와 비사용모드를 선택할 수 있기 때문에 항상 프린트를 하고 지우지 않아도 프린트가 안된다라는 장점이 있다. from icecream import ic ic(1) ic.disable() ic(2) ic.enable() ic(3) # ic| 1: 1 # ic| 3: 3 뿐만 아니라 custom pr..
2021.01.16 -
[Python] itertools
Chain list들을 연결해줄 때 쓸 수 있다. list를 더할 때 + 와 같은 역할을 해준다. import itertools letters = ['a', 'b', 'c', 'd', 'e', 'f'] booleans = [1, 0, 1, 0, 0, 1] decimals = [0.1, 0.7, 0.4, 0.4, 0.5] print(list(itertools.chain(letters, booleans, decimals))) print(letters + booleans + decimals) # ['a', 'b', 'c', 'd', 'e', 'f', 1, 0, 1, 0, 0, 1, 0.1, 0.7, 0.4, 0.4, 0.5] # ['a', 'b', 'c', 'd', 'e', 'f', 1, 0, 1, 0, 0,..
2021.01.01 -
[Python] 적절한 샘플 사이즈를 찾아주는 코드
모집단이 클 경우에는 샘플링을 통해 시각화를 위해서나 통계치를 뽑아줘야 할 것이다. 이때 가장 적절한 샘플사이즈를 알려주는 코드가 있어서 공유한다. 그리고 각각에 대해서 분포별로 실험을 진행해봤다. def sampleSize( population_size, margin_error=.05, confidence_level=.99, sigma=1/2 ): """ Calculate the minimal sample size to use to achieve a certain margin of error and confidence level for a sample estimate of the population mean. Inputs ------- population_size: integer Total size o..
2021.01.01 -
[Jupyter] GPU 사용량 주기적으로 체크하는 코드
import GPUtil from threading import Thread import time class Monitor(Thread): def __init__(self, delay): super(Monitor, self).__init__() self.stopped = False self.delay = delay # Time between calls to GPUtil self.start() def run(self): while not self.stopped: GPUtil.showUtilization() time.sleep(self.delay) def stop(self): self.stopped = True monitor = Monitor(10) 멈추는 것은 STOP을 해주면 됨 monitor.stop()
2021.01.01 -
[Python] Wordcloud Example
pip install wordcloud 폰트 다운로드하는 곳 https://creativestudio.kr/1734 코드 import jpype import base64 import numpy as np import pandas as pd from PIL import Image from pprint import pprint from matplotlib import font_manager, rc from wordcloud import ImageColorGenerator, WordCloud word = ["Statistics" , "Analysis" , "DATA" , "GAN", "R", "Python" , "SQL" , "tensorflow" , "ML" , "DL" , "Classification" ,..
2020.12.31 -
[TIP] 에러 발생할 때 Logging 파일 생성 및 적재하는 코드
파이썬에서 클래스로 짜거나 함수로 짜거나 하였을 때, 중간에 에러가 발생하는 경우가 있다. 이것들을 따로 로깅을 하지 않고 주피터 노트북에서 계속 돌린다면, 실수로 노트북이 꺼졌을 때나 잘 찾을 수가 없게 된다. 그래서 이번에는 함수나 클래스에서 에러가 발생했을 때 로그를 적재하는 파일 생성 및 계속해서 적재하는 코드를 만들어 봤다. 예를 들어 아래 함수처럼 divide라는 나눗셈 함수를 만들었는데, 들어오는 데이터에 따라서 에러가 발생하는 경우가 있다. 이때 어떠한 a 와 b 였으며, 무슨 에러인지를 표현하는 것을 공유한다. @log_error("./log.txt") def divde(a,b) : return a/b 아래가 풀 코드이다. 이 함수를 통해서 로그를 생성 및 argument를 적재하여 확인..
2020.11.15 -
[TIP / Installation] requirements.txt 로 pytorch package 설치하는 방법
보통 다른 패키지들은 아래와 같은 freeze를 이용해서 파일을 하나 생성하고 설치하면 정상적으로 설치가 된다. pip freeze > requirements.txt pip install -r requirements.txt 보통 requirements.txt 파일은 아래와 같이 생성된다. scikit-learn==0.23.2 scipy==1.5.3 seaborn==0.11.0 shap==0.36.0 six==1.15.0 slicer==0.0.4 statsmodels==0.12.0 tabulate==0.8.7 threadpoolctl==2.1.0 torch==1.6.0+cpu torchvision==0.7.0+cpu 하지만 이렇게 해서 설치를 하면, torch를 설치할 때 에러가 발생하게 된다. 그래서 검..
2020.10.25 -
[TIP / Vis ][plotly] 변수 중요도 시각화 하기 (bar_polar , bar plot)
패키지 로드 import pandas as pd import numpy as np from sklearn.ensemble import RandomForestRegressor import plotly.express as px from sklearn.datasets import load_boston 데이터 준비 및 적합시키기. data_info = load_boston(return_X_y=False) print(data_info.keys()) # dict_keys(['data', 'target', 'feature_names', 'DESCR', 'filename']) x = pd.DataFrame(data_info["data"], columns = data_info["feature_names"]) y = pd..
2020.10.10 -
[Python] pandas에서 데이터 더 빠르고 가볍게 읽는 방법
This is because when a process requests for memory, memory is allocated in two ways: Contiguous Memory Allocation (consecutive blocks are assigned) NonContiguous Memory Allocation(separate blocks at different locations) Pandas는 RAM에 데이터를 적재하기 위해서 Contiguous Memory 방식을 사용한다. 왜냐하면 읽고 쓰는 것은 디스크보다 RAM에서 하는 것이 더 빠르게 때문이다. Reading from SSDs: ~16,000 nanoseconds Reading from RAM: ~100 nanoseconds 몇 가지 ..
2020.10.07 -
[변수 선택] Genetic Algorithm를 이용 (Python)
파이썬에서 변수 선택 시 다양한 알고리즘이 있다. sklearn에서 통계적인 방법론들을 사용한 scikit-learn.org/stable/modules/feature_selection.html 여러개의 메서드들도 있고, brouta와 같은 방법론이나, 아니면 feature importance, correlation을 이용한 방법 등 참 다양한 것 같다. 하지만 실제로 이러한 방법들이 통계적으로 유의미한 것을 검증해주는데, 결국 단별량적으로 바라보거나 큰 범위에서는 잘 찾기 어려울 수가 있다. 이럴 때 쓰기 좋은 다른 방법론으로는 GA가 있다. GA는 랜덤으로 여러개를여러 개를 뿌려보면서, 최적의 해를 찾는 과정에서 주로 쓰이는데, 이때 변수 선택도 여러 개를 뿌려고 실제로 해보면서, 좋은 변수들을 찾는 ..
2020.10.07