분석 Python(344)
-
[TIP / Sklearn ] Custom Estimator (Ex : Combined Regressor)
sklearn을 사용하여 estimator를 만들 때, 참고하기 좋은 자료가 있어서 공유한다.이 자료는 Combined Regreesor라는 Estimator를 쓸 때 만든 자료인 것 같은데, Custom Estimator로 Grid Search도 돌리는 것을 보고 관심이 가게 되서 일단 저장해둔다. custom estimator를 만들어야하는 분이라면 참고하면 좋을 것 같다. Sklearn compatibilityIf we want to achieve full sklearn compatiblity (model selection, pipelines, etc.) and also use sklearn’s onboard testing utilities we have to do some modifications..
2020.10.27 -
[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 -
OR-Tools (Google Optimization Tools)
python에서 constraint 툴을 찾다가 발견함. combinatorial optimization에 사용할 수 있는 open source tool 여러 언어에서 제공하고 있는 것 같음! examples Root directory for all examples. contrib Examples from the community. cpp C++ examples. dotnet .Net examples. java Java examples. python Python examples. notebook Jupyter/IPython notebooks. flatzinc FlatZinc examples. data Data files for examples. tests Unit tests and bug reports...
2020.10.24 -
[TIP / Pytorch] Linear NN Model base Architecture
pytorch가 arhcitecture가 저장이 안 되니, 본 판때기를 잘 만들어서 한 구조에서 여러개의 파리미터를 넣을 수 있도록 해야 한다. 여기서는 본 판때기에 대한 base를 만들어봄. from torch import nn class Net(nn.Module) : def __init__(self, layers , activation, bn, dropout) : super(Net,self).__init__() self.model = self.make_model(layers , activation, bn, dropout) def forward(self, x) : self.model(x) def make_model(self, layers , activation, bn, dropout) : model =..
2020.10.23 -
[Python] Pandas를 활용하여 엑셀 시트별로 만들기
한 엑셀 파일에 여러 데이터를 담아두고 싶을 때 사용할 수 있다. 우리가 엑셀을 사용할 때 여러 엑셀 시트를 만드는 것과 동일하게 생각하면 됨. 어려운 것은 아니지만, 까먹을 수 있으므로 남겨둔다. with pd.ExcelWriter(f"./../../data/processed/hw/info.xlsx") as writer: dataset = [###] for idx , data in enumderate(datasets) : #### data.to_excel(writer, sheet_name=str(idx), index=False) 추가적으로 이미지 넣기 import xlsxwriter # Create an new Excel file and add a worksheet. workbook = xlsxwrit..
2020.10.20 -
[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 -
[Visualization] Interact Clustering with Kmeans (with any data)(continuous)
이번에 k-means를 이용해서 interact plot을 그려보는 것을 해볼 일이 있어서 서칭을 하다 보니, iris로 k-means를 활용해서 시각화한 것을 찾았다. 그래서 좀 더 확장하여 클래스로 만들어서 다양한 데이터가 들어왔을 때 적용할 수 있게 바꿔봤다. 일부 코드 중에 수정할 부분이 있어서 수정함 (argmax 보다는 dictionary로 관리를 해야 정확한 값을 뽑을 수 있음) 해당 글을 들어가면 잘 설명을 해줄 테니, 기술적인 내용은 들어가서 확인해주시기 바란다! 아주 대충 설명한다고 하면 cluster 예측값 각각에서 실제 값의 빈도를 세었을 때, 가장 많은 빈도를 가진 클래스로 매핑을 시켜줘서 라벨을 붙인다. 그리고 참고로 알다시피 k-means 같은 경우 거리 기반이 주로 유클리디안..
2020.10.09 -
[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 -
[변수 선택] 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] 2개 모델 비교하여 시각화 (binary case)
def vis(probs=[None,None],claess=[None,None],model_names=[None,None],label=None) : plt.style.use('dark_background') fig , ax = plt.subplots(1 , figsize = (15,15)) plt.scatter(probs[0] , probs[1] , c = valid_y , cmap='Set3' , s = 10 , alpha = 1.0) ax.grid(b=False) plt.xlabel(model_names[0] , fontsize =20) plt.ylabel(model_names[1] , fontsize =20) cbar = plt.colorbar(boundaries=np.array([0,1,3])) ..
2020.10.01 -
[Python] scikitplot metric visualization (binary case)
확률값을 기반으로 시각화 scikitplot을 사용해서 이진 분류 관련된 메트릭들 시각화하기 Confusion Matrix Roc Curve KS-Test(Kolmogorov-Smirnov) Precision-Recall Curve Cumulative Gains Curve Lift Curve def metric_vis_binary(probs , y_label, classes=[1,2]) : import scikitplot as skplt plt.style.use('classic') fig , ax = plt.subplots(nrows=3 , ncols=2,figsize=(15,15)) axes = ax.flatten() skplt.metrics.plot_confusion_matrix(y_label , n..
2020.10.01