1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 | import pandas as pd from pandas import Series, DataFrame import numpy as np import matplotlib.pyplot as plt %matplotlib inline import sys, warnings if not sys.warnoptions: warnings.simplefilter("ignore") pd.set_option('max_columns', 30, 'max_rows', 30) from xgboost import XGBClassifier from lightgbm.sklearn import LGBMClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.svm import SVC from sklearn.neural_network import MLPClassifier # 모델 패키지 임포트 import numpy as np import xgboost as xgb from sklearn.linear_model import LogisticRegression from sklearn.tree import DecisionTreeClassifier from sklearn.naive_bayes import GaussianNB from sklearn.ensemble import VotingClassifier # 데이터 임포트 import pickle with open("train_data.pkl","rb") as tr: train = pickle.load(tr) with open("test_data.pkl","rb") as te: test = pickle.load(te) display(train) display(test) # 데이터셋 생성 X_train = train.drop(['OC'],axis=1) y_train = train[['OC']] X_test = test.drop(['OC'],axis=1) y_test = test[['OC']] # 모든 모델에 대하여 튜닝을 시켜 최적의 파라미터로 설정 학습하였습니다. # xgb 모델 튜닝 (grid search) from sklearn.model_selection import GridSearchCV # xgb from xgboost.sklearn import XGBClassifier estimator = XGBClassifier() parameters = {'nthread':[4], #when use hyperthread, xgboost may become slower 'objective':['binary:logistic'], 'learning_rate': [0.05], #so called `eta` value 'max_depth': [6], 'min_child_weight': [11], 'silent': [1], 'subsample': [0.8], 'colsample_bytree': [0.7], 'n_estimators': [5], #number of trees, change it to 1000 for better results 'missing':[-999], 'seed': [1337]} clf = GridSearchCV(estimator, parameters, n_jobs=5, cv=5, scoring='roc_auc', verbose=2, refit=True) clf.fit(X_train, y_train) print('Best parameters found by grid search are:', clf.best_params_) # 결과창 Best parameters found by grid search are: {'colsample_bytree': 0.7, 'learning_rate': 0.05, 'max_depth': 6, 'min_child_weight': 11, 'missing': -999, 'n_estimators': 5, 'nthread': 4, 'objective': 'binary:logistic', 'seed': 1337, 'silent': 1, 'subsample': 0.8} # 그리드 서치 결과로 모델 학습 xgb = XGBClassifier(colsample_bytree= 0.7, learning_rate= 0.05, max_depth= 6, min_child_weight= 11, missing= -999, n_estimators= 5, nthread= 4, objective= 'binary:logistic', seed= 1337, silent= 1, subsample= 0.8) xgb.fit(X_train, y_train) # gradient boost 모델 팔라미터 튜닝 from sklearn.ensemble import GradientBoostingClassifier eclf = GradientBoostingClassifier(n_estimators=100, learning_rate=0.1) # 파라미터 튜닝 params ={ "n_estimators" : [10, 20, 30, 50, 100, 200], "learning_rate" : [i for i in np.linspace(0.1,1, 10)]} from sklearn.model_selection import GridSearchCV grid = GridSearchCV(estimator=eclf, param_grid=params, cv=5, n_jobs=-1) grid = grid.fit(X_train, y_train) grid.best_params_ # 최적 파라미터값으로 학습 gbc=GradientBoostingClassifier(n_estimators=200, learning_rate=0.1) gbc.fit(X_train, y_train) #lightgbm 파라미터 튜닝 import lightgbm as lgb estimator = lgb.LGBMClassifier(num_leaves=2) param_grid = { 'learning_rate': [0.01, 0.1, 0.05, 0.5, 1], 'n_estimators': [20, 40, 60, 80, 100, 120] } grid = GridSearchCV(estimator, param_grid, cv=5, scoring='roc_auc') grid.fit(X_train, y_train) print('Best parameters found by grid search are:', grid.best_params_) #Best parameters found by grid search are: {'learning_rate': 1, 'n_estimators': 40} lgb=lgb.LGBMClassifier(learning_rate= 1, n_estimators= 40) lgb.fit(X_train, y_train) # rfc params ={ "n_estimators" : [10, 20, 30, 50, 100], "max_features" : [1,2,3,4,5,6,7, 10, 15, 20, 25] } from sklearn.model_selection import GridSearchCV grid = GridSearchCV(estimator=eclf, param_grid=params, cv=5, n_jobs=-1) grid = grid.fit(X_train, y_train) grid.best_params_ #{'max_features': 2, 'n_estimators': 100} from sklearn.ensemble import RandomForestClassifier rfc = RandomForestClassifier(n_estimators=10, max_features=4, n_jobs=-1, oob_score=True) rfc.fit(X_train, y_train) #svm 모델 from sklearn.svm import SVC svc = SVC(gamma='auto', probability=True) svc.fit(X_train, y_train) # svm은 튜닝을 돌리기엔 시간이 상당히 걸리는 모델이고, svm을 주로 모델 앙상블을 할 계획이 아니기에 파라미터 튜닝은 생략함. # svm 모델이 일반적인 모델과 달리 데이터 상에 이상치와 같이 되게 떨어져있는(?) 데이터를 맞추는데 좋다하여, svm을 앙상블에 사용. # 1. 기본적으로 아래 보이는 조합과 같이 여러 조합으로 기본 바닐라 앙상블을 시켰음. eclf = VotingClassifier(estimators=[('xgb', xgb), ('svc', svc), ('lgb', lgb)], voting='soft') # model1 = xgb, bgc, rgc # model2 = xgb, bgc, lgb # model3 = xgb, svc, lgb eclf.fit(X_train, y_train) y_prob=eclf.predict_proba(X_test) y_probe=y_prob[:,1]/0.8 # 결과값을 분류하는 임계값은 보통 0.8로 주었고, 경우에 따라 prod값을 보고 0.7과 0.8로 유연하게 주었습니다. y_pred=[] for i in range(len(y_probe)): if y_probe[i]>=1: y_pred.append(1) else: y_pred.append(0) model3_08=pd.DataFrame({'inst_id':test['inst_id'],'OC':y_pred}) # 위의 조합을 여러 데이터 셋을 생성. # 2. gmean 기법 사용. votingC = VotingClassifier(estimators=[('xgb', xgb), ('gbc', gbc), ('lgb', lgb)], voting='soft') pred_1 = votingC.fit(X_train, y_train).predict_proba(X_test)[:,1] votingC = VotingClassifier(estimators=[('xgb', xgb), ('gbc', gbc), ('rfc', rfc)], voting='soft') pred_2 = votingC.fit(X_train, y_train).predict_proba(X_test)[:,1] votingC = VotingClassifier(estimators=[('xgb', xgb), ('svc', gbc), ('lgb', lgb)], voting='soft') pred_3 = votingC.fit(X_train, y_train).predict_proba(X_test)[:,1] # 여러 조합으로 데이터를 학습시키고 pred값 도출 # 한번의 앙상블 결과보다는 여러 데이터셋으로 모델을 학습시키는 방식처럼! 여러 앙상블을 또 앙상블 시키는 2중 앙상블 개념을 적용하면 더 좋은 결과가 나올 것으로 생각. # 위의 모델에 의한 결과값은 다 같은 데이터에 단순 모델만 여러 조합으로 학습시켰음 # 따라서, 각 pred간 모델 결과간의 유사도가 높습니다. 그러므로 단순히 이 pred값을 앙상블 시키는 것보다 gmean 멱평균 앙상블 시키는 것이 더 좋음. # 결론적으로 여러 조합의 모델 앙상블을 gmean 시킨 값을 최종 pred로 삼았습니다. pred = (pred_1*pred_2*pred_3)**(1/3) y_probe=pred/0.8 y_pred=[] for i in range(len(y_probe)): if y_probe[i]>=1: y_pred.append(1) else: y_pred.append(0) model123_08=pd.DataFrame({'inst_id':test['inst_id'],'OC':y_pred}) model123_08 model123_08.to_csv('model123_08.csv') | cs |
Designed by sketchbooks.co.kr / sketchbook5 board skin
Sketchbook5, 스케치북5
Sketchbook5, 스케치북5
Sketchbook5, 스케치북5
Sketchbook5, 스케치북5