Python(212)
-
[ Python ] seaborn subplots x_ticklables rotate 하는 법
import seaborn as sns fig , axes = plt.subplots(1,2) axx = axes.flatten() g = sns.countplot(x="dt", data=tmp , hue = "occur" , ax = axx[0] ,) g.set_xticklabels(g.get_xticklabels(), rotation=45, horizontalalignment='right', fontweight='light', fontsize='x-small' ) g = sns.countplot(x="region", data=tmp , hue = "occur" , ax = axx[1]) g.set_xticklabels(g.get_xticklabels(), rotation=45, horizontalal..
2019.09.13 -
[변수 처리] Python에서 범주형 변수(Categorical) 다루기
http://contrib.scikit-learn.org/categorical-encoding/onehot.html One Hot — Category Encoders latest documentation options are ‘error’, ‘return_nan’, ‘value’, and ‘indicator’. The default is ‘value’. Warning: if indicator is used, an extra column will be added in if the transform matrix has unknown categories. This can cause unexpected changes in dimension in some case contrib.scikit-learn.org ##..
2019.09.13 -
[ Python ] custom logging level 만들기
logging level 추가하기. import logging trace = 15 class user(logging.Logger) : def trace(self , msg , *args ,**kwargs ): self.log( trace ,msg , *args ,**kwargs ) logging.setLoggerClass(user) logging.addLevelName(15 , "user") logger = logging.getLogger("test") logger.setLevel("user") ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) logger.addHandler(ch) logger.debug(" debug test") logger.trace..
2019.09.11 -
[ 변수 처리] 파이썬 결측치 대체 알고리즘 비교 예시
Class로 만들어서 비교해보기 from autoimpute import imputations import impyute as impy import numpy as np from missingpy import MissForest from tqdm import tqdm_notebook n = 30 arr = np.random.uniform(high=6, size=(n, n)) arr[:,0:5] = arr[:,0:5].astype(int) true = arr.copy() arr.ravel()[np.random.choice(arr.size , 100 , replace = False )] = np.nan mask = np.isnan(arr) * 1 class Evaluate : """ X = missing d..
2019.09.10 -
[ Python ] imputation algorithm package 정리
도움이 되셨다면, 광고 한번만 눌러주세요. 블로그 관리에 큰 힘이 됩니다 ^^ categorical 변수 가장 빈도수 많은 것으로 대체할 때, df_most_common_imputed = colors.apply(lambda x: x.fillna(x.value_counts().index[0])) df_most_common_imputed ## scikit-learn 0.2 버전 imputer=CategoricalImputer(strategy='most_frequent', axis=1) imputer.fit(df[["col1", "col2"]]) imputer.transform(df) (https://stackoverflow.com/questions/25239958/impute-categorical-missi..
2019.09.10 -
[ Python ] SHAP (SHapley Additive exPlanations) Decision plot 설명
도움이 되셨다면, 광고 한번만 눌러주세요. 블로그 관리에 큰 힘이 됩니다 ^^ 기존에 내가 들었던 것은 Lime이라는 것이 있었지만, SHAP도 많이 언급되는 것 같아서 잘 정리된 자료를 리뷰해보려고 한다. SHAP FRAMEWORK는 머신러닝 모델 해석 분야에서 중요한 진보를 증명하고 있다고 한다. Scott Lundberg 그리고 Su-In Lee에 의해서 개발한 SHAP는 기존의 몇 가지 방법을 조합하여 직관적이고 이론적으로 잘 된 접근법을 만들어 어떤 모델에 대한 예측을 설명할 수 있다. SHAP 각 예측과 변수에 대한 같은 질문을 함으로써 모델의 설명을 build 한다. "변수 j가 이 모델로부터 제거될 때 얼마나 이 예측 i 에 변화를 줄까?" 그래서 이 물음에 대한 답은 SHAP values..
2019.09.08 -
[Python] confluent-Kafka 연습하기
## Producer 1 (topic odd) from confluent_kafka import Producer import numpy as np p = Producer({'bootstrap.servers': 'localhost'}) def delivery_report(err, msg): """ Called once for each message produced to indicate delivery result. Triggered by poll() or flush(). """ if err is not None: print('Message delivery failed: {}'.format(err)) else: print('Message delivered to {} [{}]'.format(msg.topic(..
2019.09.03 -
[ Python ] logging 만들어보기 (FileHandler 와 StreamHandler 위주로)
도움이 되셨다면, 광고 한번만 눌러주세요. 블로그 관리에 큰 힘이 됩니다 ^^ 파이썬에서 logging 쌓기 (FileHandler 와 StreamHandler 위주로) StreamHandler Console에 log 남기기 logging.StreamHandler() FileHandler log를 계속 쌓고 싶을 때 FileHandler('./log.txt' ,mode = "w") RotatingFileHandler 파일 용량을 정해서 log를 쌓고 제거할 때 RotatingFileHandler( filename, ## ~~.log / ~~.txt mode='a', ## a : append / w : overwrite maxBytes=0, ## 한 파일당 몇 몇가 byte까지 만들 수 있는지 backup..
2019.08.25 -
[ Python ] multiprocessing / concurrent.futures
멀티프로세싱 공부 Queues FIFO(선입선출) 먼저 들어온 놈이 먼저 나간다라고 한다. 안에서 쌓아놨다고 내뱉는 머 그런 느낌! 순서가 중요할 때 안전하게 사용해야 하는 느낌이다. from multiprocessing import Process, Queue import random def rand_num(queue , x): #num = random.random() queue.put(x) if __name__ == "__main__": processes = [Process(target=rand_num, args=(queue,x,)) for x in range(10)] for p in processes: p.start() for p in processes: p.join() results = [queue..
2019.08.18 -
[ Python ] kafka consume multiprocessing 해보기
https://stackoverflow.com/questions/46491616/python-kafka-multiprocess-vs-thread Python Kafka multiprocess vs thread I can use KafkaConsumer to consume messages in separate threads. However, when I use multiprocessing.Process instead of threading.Thread, I get an error: OSError: [Errno 9] Bad file descriptor T... stackoverflow.com 같은 group_id를 가지면서( offset 순차적 ) 같은 토픽에서 정보 가져오기 이렇게 하면 얻는 효과는 더 빨..
2019.08.17 -
[Python] Kafka offset 확인
Producer from time import sleep from json import dumps from kafka import KafkaProducer import numpy as np producer = KafkaProducer(bootstrap_servers=['localhost:9092'], key_serializer = None , value_serializer=lambda x: dumps(x).encode('utf-8')) ## for _ in range(100): value = np.random.normal(loc = 10 , scale = 20 ,size= 3).astype(str).tolist() values = ",".join( value ) data = {'number' : valu..
2019.08.17 -
[ Python ] 사용한 package 모두 저장해서 다른 곳에서 그대로 사용하는방법
최근에 사용한 패키지 상태를 그대로 유지하면서, 다시 사용해야 할 때 전달해야 하는 이슈가 있었다. 그래서 처음에는 pickle로 저장해봤는데, 안되서 이유를 찾아보니 밑에 글에 잘 정리된 게 있으니 확인해보시길 바란다! 사실 R에서는 .RData로 몽땅 집어넣을 수가 있는데, 이것이 되는지가 궁금했다 https://lovit.github.io/analytics/2019/01/15/python_dill/ Python dill 로 class definition 까지 binary 로 저장하기 파이썬으로 작업을 할 때, 사용자가 정의하는 클래스 인스턴스를 저장할 일들이 있습니다. 예를 들면 namedtuple 을 이용한 데이터 타입이라던지, PyTorch 에서 nn.Module 을 상속받은 모델들이 그 예입니..
2019.08.12