분석 Python/구현 및 자료(105)
-
[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] Class에 사전(dict)으로 property 추가하는 법
아래 코드는 특정 값들을 바로 propert에 추가하는 코드다 kwargs에 config라는 것이 들어오면, 각각의 값들을 다 property를 해준다. import numpy as np def assign_config(self, kwargs): for key, value in kwargs.items(): setattr(self, key, value) if hasattr(self, 'config'): # print(self.env_config) for key, value in self.config.items(): # Check types based on default settings if hasattr(self, key): if type(getattr(self,key)) == np.ndarray: set..
2020.12.18 -
[변수 선택] Genetic Algorithm를 이용 (Python)
파이썬에서 변수 선택 시 다양한 알고리즘이 있다. sklearn에서 통계적인 방법론들을 사용한 scikit-learn.org/stable/modules/feature_selection.html 여러개의 메서드들도 있고, brouta와 같은 방법론이나, 아니면 feature importance, correlation을 이용한 방법 등 참 다양한 것 같다. 하지만 실제로 이러한 방법들이 통계적으로 유의미한 것을 검증해주는데, 결국 단별량적으로 바라보거나 큰 범위에서는 잘 찾기 어려울 수가 있다. 이럴 때 쓰기 좋은 다른 방법론으로는 GA가 있다. GA는 랜덤으로 여러개를여러 개를 뿌려보면서, 최적의 해를 찾는 과정에서 주로 쓰이는데, 이때 변수 선택도 여러 개를 뿌려고 실제로 해보면서, 좋은 변수들을 찾는 ..
2020.10.07 -
[변수 선택] BorutaShap 활용 (Python)
이전에도 Boruta를 이용해서 리뷰를 한 적이 있는데, 이번에는 Shap과 Brouta를 결합한 패키지를 찾게 되어서 공유한다. 해당 패키지의 장점이라고 생각하는 점은 일단 SHAP을 이용해서 변수 선택을 한다는 것이 가장 마음에 들었고, 그리고 변수 선택에서 사용하는 알고리즘이 Tree Based 알고리즘은 다 되긴 하는데, XGB , CATBOOST, DT(sklearn), RF(sklearn)... ensemble method(sklearn)이다. 특히 xgb나 catboost 같이 category feature를 변환하지 않고 변수 선택 모델링할 수 있는 패키지를 사용할 수 있어서, 실제로 category에 대한 영향도를 더 잘 표현해줄 것으로 기대한다. Algorithm Start by cre..
2020.10.06 -
[Python] python-constraint packages
python-constraint 패키지에서 제공하는 모듈을 소개 이 모듈 여러개를 적절하게 결합하면 제한 조건을 설정할 수 있을 것 같다. Type AllDifferentConstraint Constraint enforcing that values of all given variables are different problem = Problem() problem.addVariables(["a", "b"], [1, 2]) problem.getSolutions() # [{'a': 2, 'b': 2}, {'a': 2, 'b': 1}, {'a': 1, 'b': 2}, {'a': 1, 'b': 1}] problem.addConstraint(AllDifferentConstraint()) problem.getSolu..
2020.09.15 -
[Python] 특정 command psutil로 사용하여 pid 종료하기
여기서는 command에 파이썬이면서 joblib이 있는 것들 킬하기 import psutil , re results = [] for proc in psutil.process_iter(['pid', 'name', 'username',"cmdline"]): if (proc.info["cmdline"] != []) & (proc.info["name"] == "python") : bool_sum = np.sum([True for i in proc.info["cmdline"] if re.search("joblib" , i) is not None]) if bool_sum > 0 : results.append(proc.info["pid"]) for pid in results : psutil.Process(pid)...
2020.09.14 -
[Python] dictionary filter
dict에서 value나 key에 따라서 필터링을 하고 싶은 경우에 사용하면 좋을 것 같아서 공유 아래는 key안에 value의 길이가 3 이상인 애들만 추출하기 dict(filter(lambda elem: len(elem[1]) >=3, data.items())) 아래 참고! hello-bryan.tistory.com/77 [Python] Dictionary Filter Dictionary Filter score_dict = { 'sam':23, 'john':30, 'mathew':29, 'riti':27, 'aadi':31, 'sachin':28 } 이런 dictionary 가 있을 때 30점이 넘는 사람만 가지는 dictionary 를 얻고 싶다면, 기본 적으로 for.. hello-bryan.ti..
2020.09.12 -
[Python] re.sub에서 특정한 것만 바꾸고 싶을 때 하는 방법
전처리 앞으로 해야 할 것이 더 많지만, 일단 찾은 것까지만 기록해보고자 한다. import re string = '@@He11o Wor1d!' string = re.sub(r'([a-zA-Z])[@31!]+(?=[a-zA-Z])', r'\1', string) string string = 'n"t' re.sub(r'([a-zA-Z])"(?=[a-zA-Z])',r"\1'",string) string = '4"t' re.sub(r'([a-zA-Z1-9])"(?=[a-zA-Z])',r"\1'",string) string = 'n" ' re.sub(r'([a-zA-Z])" ',r"\1",string) 'n' string = ' "nL' re.sub(r'\s"([a-zA-Z]{2,})', r" \1",string..
2020.08.26 -
[Python] ConfigSpace 여러 기능 사용해보기
import ConfigSpace as CS config_space = CS.ConfigurationSpace() config_space.add_hyperparameter( CS.UniformIntegerHyperparameter('hidden_size_1', lower=50, upper=100)) config_space.add_hyperparameter( CS.UniformIntegerHyperparameter('hidden_size_2', lower=10, upper=50)) # config_space.add_hyperparameter( # CS.UniformIntegerHyperparameter('hidden_size_3', lower=10, upper=100)) config_space.add_hy..
2020.08.20 -
[Python] 딥러닝 학습하는 도중에 GPU 사용량 확인하기
이번 글은 실제 학습 동안에, GPU를 얼마나 사용하는지를 프린트해주는 것을 찾게 되어서 공유한다. 실제로는 nvidia-smi를 통해서 확인할 수 있지만, 도커를 쓰다보면 이러한 사용량을 알 수 없는 경우가 생긴다. 그래서 이번에는 학습하면서 중간 중간에 출력을 해줘서 실제로 사용 여부를 확인할 수가 있다. 추가적으로 threading을 사용해서 학습하면서, 병렬로 돌릴 수 있는 코드를 발견해서 공유한다. # Import MNIST data from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("./", one_hot=False) import tensorflow as tf import mat..
2020.08.19 -
[Python] H2O로 Randomforest 해보기
알고리즘 설정하기 import h2o h2o.init() from h2o.estimators import H2ORandomForestEstimator # Import the cars dataset into H2O: cars = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/junit/cars_20mpg.csv") ## 타겟 변수 (classfication) cars["economy_20mpg"] = cars["economy_20mpg"].asfactor() ## 타겟 변수 (regression) cars["economy"] = cars["economy"].asnumeric() predictors = ["displaceme..
2020.08.10