data analysis week 2

3 minute read

Ensembling (앙상블)

정의

  • 주어진 자료로 부터 여러개의 예측모형들을 만든후 예측 모형들을 조합하여 하나의 최종 예측 모형을 만드는 방법이고 아래 3 가지 방법으로 앙상플을 할 수 있다
  1. Voting Classifier

  2. 배깅 (Bagging)

  3. 부스팅 (Boosting)

보팅 ( Voting Classifier)

보팅은 여러개의 모형으로 부터 산출된 결과를 다수결에 의해서 최종 결과를 선정하는 과정이다.

가장 간단하게 예측을 합하는 방법이고 sub model의 prediction에 근거한 prediction 결과의 평균을 낸다.

from sklearn.ensemble import VotingClassifier
ensemble_lin_rbf=VotingClassifier(estimators=[('KNN',KNeighborsClassifier(n_neighbors=10)),
                                              ('RBF',svm.SVC(probability=True,kernel='rbf',C=0.5,gamma=0.1)),
                                              ('RFor',RandomForestClassifier(n_estimators=500,random_state=0)),
                                              ('LR',LogisticRegression(C=0.05)),
                                              ('DT',DecisionTreeClassifier(random_state=0)),
                                              ('NB',GaussianNB()),
                                              ('svm',svm.SVC(kernel='linear',probability=True))
                                             ], 
                       voting='soft').fit(train_X,train_Y)
print('The accuracy for ensembled model is:',ensemble_lin_rbf.score(test_X,test_Y))
cross=cross_val_score(ensemble_lin_rbf,X,Y, cv = 10,scoring = "accuracy")
print('The cross validated score is',cross.mean())

The accuracy for ensembled model is: 0.824626865672
The cross validated score is 0.823766031097

위에서 사용했던 모델들을 voting classifier에 넣으서 돌리면 83%로 정확도가 높게 조금 더 높게 나오는것을 확인할 수 있다.

배깅

배깅은 여러개의 붓스트랩자료를 생성하고 각 붓스트랩 자료에 예측모형을 만든후 결합하여 최종 예측 모형을 만드는 방법이다. 붓스트랩은 주어진 자료에서 동일한 크기의 표본을 랜덤 복원 추출로 뽑는 자료를 의미한다.

다른 말로는 샘플을 여러번 뽑아 각 모델을 학습시켜 결과를 집계하는것이다.

Bagged KNN

분산이 높은 모델들에게 사용할수있다. 램덤포레스트나 의사결정 나무 같은 경우 작은 n_neighbour 값을 주고 KNN 을 사용할 수 있다

from sklearn.ensemble import BaggingClassifier
model=BaggingClassifier(base_estimator=KNeighborsClassifier(n_neighbors=3),random_state=0,n_estimators=700)
model.fit(train_X,train_Y)
prediction=model.predict(test_X)
print('The accuracy for bagged KNN is:',metrics.accuracy_score(prediction,test_Y))
result=cross_val_score(model,X,Y,cv=10,scoring='accuracy')
print('The cross validated score for bagged KNN is:',result.mean())
The accuracy for bagged KNN is: 0.835820895522
The cross validated score for bagged KNN is: 0.814889342867

knn 을 사용한경우 정확도가 조금 더 높다

** bagged decision tree **

model=BaggingClassifier(base_estimator=DecisionTreeClassifier(),random_state=0,n_estimators=100)
model.fit(train_X,train_Y)
prediction=model.predict(test_X)
print('The accuracy for bagged Decision Tree is:',metrics.accuracy_score(prediction,test_Y))
result=cross_val_score(model,X,Y,cv=10,scoring='accuracy')
print('The cross validated score for bagged Decision Tree is:',result.mean())
The accuracy for bagged Decision Tree is: 0.824626865672
The cross validated score for bagged Decision Tree is: 0.820482635342

bagged decision tree 값이 더 높다

부스팅 (boosting)

예측력이 약한 (weak learners) 들을 결합 하여 강한 예측 모형을 만드는 방법이다. 훈련 오차를 빨리 그리고 쉽게 줄일수 있고 배깅에 비해 많은 경우 예측오차가 향상되어 adaboost의 성능이 배깅보다 뛰어난 경우가 많다.

adaBoost(adaptive boosting)

이진 분류 문제에서 랜덤 분류기 보다 조금더 좋은 분류기 n개에 각각 가중치를 설정하고 n개의 분류기를 결합하여 최종 분류기를 만드는 방법이다.

from sklearn.ensemble import AdaBoostClassifier
ada=AdaBoostClassifier(n_estimators=200,random_state=0,learning_rate=0.1)
result=cross_val_score(ada,X,Y,cv=10,scoring='accuracy')
print('The cross validated score for AdaBoost is:',result.mean())
The cross validated score for AdaBoost is: 0.824952616048

Stochastic Gradient Boosting

에이다부스트가 샘플들의 가중치를 수정했다면, 그래디언트 부스팅은 이전 예측기가 만든 잔여 오차(residual error)에 다음 예측기를 학습시킨다.

from sklearn.ensemble import GradientBoostingClassifier
grad=GradientBoostingClassifier(n_estimators=500,random_state=0,learning_rate=0.1)
result=cross_val_score(grad,X,Y,cv=10,scoring='accuracy')
print('The cross validated score for Gradient Boosting is:',result.mean())
The cross validated score for Gradient Boosting is: 0.818286233118

XGBoost

XGBoost는 Gradient Boosting 방법 중 한 가지이다.

XGBoost는 어원처럼 처럼 Extreme 하다. 많은 머신러닝 방법 중에 하나인데 Decision tree를 기반으로 한 Ensemble 방법. 그중에서도 Boosting을 기반으로 하는 머신러닝 방법이다.

import xgboost as xg
xgboost=xg.XGBClassifier(n_estimators=900,learning_rate=0.1)
result=cross_val_score(xgboost,X,Y,cv=10,scoring='accuracy')
print('The cross validated score for XGBoost is:',result.mean())
The cross validated score for XGBoost is: 0.810471002156

Hyper-Parameter Tuning for AdaBoost

n_estimators=list(range(100,1100,100))
learn_rate=[0.05,0.1,0.2,0.3,0.25,0.4,0.5,0.6,0.7,0.8,0.9,1]
hyper={'n_estimators':n_estimators,'learning_rate':learn_rate}
gd=GridSearchCV(estimator=AdaBoostClassifier(),param_grid=hyper,verbose=True)
gd.fit(X,Y)
print(gd.best_score_)
print(gd.best_estimator_)
Fitting 3 folds for each of 120 candidates, totalling 360 fits
[Parallel(n_jobs=1)]: Done 360 out of 360 | elapsed:  4.8min finished
0.83164983165
AdaBoostClassifier(algorithm='SAMME.R', base_estimator=None,
          learning_rate=0.05, n_estimators=200, random_state=None)

image

Confusion Matrix for the Best Model

ada=AdaBoostClassifier(n_estimators=200,random_state=0,learning_rate=0.05)
result=cross_val_predict(ada,X,Y,cv=10)
sns.heatmap(confusion_matrix(Y,result),cmap='winter',annot=True,fmt='2.0f')
plt.show()

image

Feature Importance

f,ax=plt.subplots(2,2,figsize=(15,12))
model=RandomForestClassifier(n_estimators=500,random_state=0)
model.fit(X,Y)
pd.Series(model.feature_importances_,X.columns).sort_values(ascending=True).plot.barh(width=0.8,ax=ax[0,0])
ax[0,0].set_title('Feature Importance in Random Forests')
model=AdaBoostClassifier(n_estimators=200,learning_rate=0.05,random_state=0)
model.fit(X,Y)
pd.Series(model.feature_importances_,X.columns).sort_values(ascending=True).plot.barh(width=0.8,ax=ax[0,1],color='#ddff11')
ax[0,1].set_title('Feature Importance in AdaBoost')
model=GradientBoostingClassifier(n_estimators=500,learning_rate=0.1,random_state=0)
model.fit(X,Y)
pd.Series(model.feature_importances_,X.columns).sort_values(ascending=True).plot.barh(width=0.8,ax=ax[1,0],cmap='RdYlGn_r')
ax[1,0].set_title('Feature Importance in Gradient Boosting')
model=xg.XGBClassifier(n_estimators=900,learning_rate=0.1)
model.fit(X,Y)
pd.Series(model.feature_importances_,X.columns).sort_values(ascending=True).plot.barh(width=0.8,ax=ax[1,1],color='#FD0F00')
ax[1,1].set_title('Feature Importance in XgBoost')
plt.show()

image

  1. 중요한 피쳐 중에 initial, Fare_cat, Pclass, Family_Size 경우 공통 적으로 값이 높게 나왔습니다.

  2. 성별은 중요한 피쳐가 아니였습니다. 이것은 이전에 보았던 성별과 Pclass와 합한게 좋은 요인이었다는 것을 반박한다. 성별은 랜덤 포레스트에서만 중요하다. 하지만 initial과 sex는 서로 양의 상관관계를 가지고 있고 서로 성별을 의미한다.

  3. 비슷한 관계로 Pclass 와 Fare_cat은 둘다 탑승객의 등급을 의미한다. Family_Size와 ALone 그리고 Parch(Number of Parents/Children Aboard) 와 SibSp(Number of Siblings/Spouses Aboard)

image

Observations in a Nutshell for all features: Sex: The chance of survival for women is high as compared to men.

Pclass:There is a visible trend that being a 1st class passenger gives you better chances of survival. The survival rate for Pclass3 is very low. For women, the chance of survival from Pclass1 is almost 1 and is high too for those from Pclass2. Money Wins!!!.

Age: Children less than 5-10 years do have a high chance of survival. Passengers between age group 15 to 35 died a lot.

Embarked: This is a very interesting feature. The chances of survival at C looks to be better than even though the majority of Pclass1 passengers got up at S. Passengers at Q were all from Pclass3.

Parch+SibSp: Having 1-2 siblings,spouse on board or 1-3 Parents shows a greater chance of probablity rather than being alone or having a large family travelling with you.

Leave a comment