forked from AnupamKhare/code-Repository
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGrid Seach Classifier with Three Models and Ensembling All
188 lines (129 loc) · 5.46 KB
/
Grid Seach Classifier with Three Models and Ensembling All
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
########## Grid search classification with three models and Then ensembling to produce ensembled model##########
################### grid Serch Cv Code for classification with three models###################
# Cross validate model with Kfold stratified cross val
from sklearn.model_selection import GridSearchCV, cross_val_score, StratifiedKFold
kfold = StratifiedKFold(n_splits=10)
from sklearn.ensemble import ExtraTreesClassifier
ExtC = ExtraTreesClassifier()
## Search grid for optimal parameters
ex_param_grid = {"max_depth": [n for n in range(9, 14)],
"max_features": [1, 3, 10],
"min_samples_split": [n for n in range(4, 11)],
"min_samples_leaf": [n for n in range(2, 5)],
"bootstrap": [False],
"n_estimators" :[n for n in range(10, 60, 10)],
"criterion": ["gini"]}
gsExtC = GridSearchCV(ExtC,param_grid = ex_param_grid, cv=kfold, scoring="accuracy", n_jobs= 4, verbose = 1)
gsExtC.fit(X_train,y_train)
ExtC_best = gsExtC.best_estimator_
# Best score
gsExtC.best_score_
# RFC Parameters tunning
from sklearn.ensemble import RandomForestClassifier
### Random Forest #########
RFC = RandomForestClassifier()
## Search grid for optimal parameters
rf_param_grid = {"max_depth": [n for n in range(9, 14)],
"max_features": [1, 3, 10],
"min_samples_split": [n for n in range(4, 11)],
"min_samples_leaf": [n for n in range(2, 5)],
"bootstrap": [False],
"n_estimators" :[n for n in range(10, 60, 10)],
"criterion": ["gini"]}
gsRFC = GridSearchCV(RFC,param_grid = rf_param_grid, cv=kfold, scoring="accuracy", n_jobs= 4, verbose = 1)
gsRFC.fit(X_train,y_train)
RFC_best = gsRFC.best_estimator_
# Best score
gsRFC.best_score_
#### Adaboost
# Adaboost
from sklearn.ensemble import AdaBoostClassifier
from sklearn.tree import DecisionTreeClassifier
DTC = DecisionTreeClassifier()
adaDTC = AdaBoostClassifier(DTC, random_state=7)
ada_param_grid = {"base_estimator__criterion" : ["gini", "entropy"],
"base_estimator__splitter" : ["best", "random"],
"algorithm" : ["SAMME","SAMME.R"],
"n_estimators" :[30],
"learning_rate": [0.0001, 0.001, 0.01, 0.1, 0.2, 0.3,1.5]}
gsadaDTC = GridSearchCV(adaDTC,param_grid = ada_param_grid, cv=kfold, scoring="accuracy", n_jobs= 4, verbose = 1)
gsadaDTC.fit(X_train,y_train)
ada_best = gsadaDTC.best_estimator_
gsadaDTC.best_score_
##### SVC########
### SVC classifier
from sklearn.svm import SVC
SVMC = SVC(probability=True)
svc_param_grid = {'kernel': ['rbf'],
'gamma': [ 0.001, 0.01, 0.1, 1],
'C': [1, 10, 50, 100,200,300, 1000]}
gsSVMC = GridSearchCV(SVMC,param_grid = svc_param_grid, cv=kfold, scoring="accuracy", n_jobs= 4, verbose = 1)
gsSVMC.fit(X_train,y_train)
SVMC_best = gsSVMC.best_estimator_
# Best score
gsSVMC.best_score_
##### GB cassifier
# Gradient boosting tunning
from sklearn.ensemble import GradientBoostingClassifier
GBC = GradientBoostingClassifier()
gb_param_grid = {'loss' : ["deviance"],
'n_estimators' : [n for n in range(10, 60, 10)],
'learning_rate': [0.1, 0.05, 0.01],
'max_depth': [n for n in range(9, 14)],
'min_samples_leaf': [n for n in range(2, 5)],
'max_features': [0.3, 0.1]
}
gsGBC = GridSearchCV(GBC,param_grid = gb_param_grid, cv=kfold, scoring="accuracy", n_jobs= 4, verbose = 1)
gsGBC.fit(X_train,y_train)
GBC_best = gsGBC.best_estimator_
# Best score
gsGBC.best_score_
#### Ensembling#######
from sklearn.ensemble import VotingClassifier
votingC = VotingClassifier(estimators=[('rfc', RFC_best), ('extc', ExtC_best),('svm',SVMC_best),
('gbc',GBC_best)], voting='soft', n_jobs=4)
votingC = votingC.fit(X_train, y_train)
test_Survived = pd.Series(votingC.predict(test), name="Survived")
Submission = pd.concat([IDtest,test_Survived],axis=1)
Submission.to_csv("submission.csv",index=False)
################### Bayesina Parameter Tuning###################################################################
from skopt import BayesSearchCV
# Bayesian Optimization
opt = BayesSearchCV(
estimator = XGBRegressor(
n_jobs = -1,
tree_method='approx'
),
search_spaces = {
'learning_rate': (0.01, 1.0, 'log-uniform'),
'min_child_weight': (0, 20),
'max_depth': (3, 5),
# 'max_delta_step': (0, 20),
'subsample': (0.1, 1.0, 'uniform'),
'colsample_bytree': (0.1, 1.0, 'uniform'),
'colsample_bylevel': (0.1, 1.0, 'uniform'),
'reg_lambda': (1e-3, 1000, 'log-uniform'),
'reg_alpha': (1e-3, 1.0, 'log-uniform'),
# 'gamma': (1e-9, 0.5, 'log-uniform'),
'base_score':((1e-4, 0.5, 'log-uniform'))
},
scoring = scoring,
cv =3,
n_jobs = -1,
refit = True,
random_state = 42
)
opt.fit(X_train_scaled,y_train)
opt.best_params_
#Tuned Model
xgb=XGBRegressor(random_state=51,n_jobs=-1,**opt.best_params_)
xgb.fit(X_train_scaled,y_train)
y_train_pred=xgb.predict(X_train_scaled)
y_val_pred=xgb.predict(X_val_scaled)
y_pred_xgb=np.append(y_train_pred,y_val_pred)
print('Train RMSE:',np.sqrt(mean_squared_error(y_train,y_train_pred)))
print('Test RMSE:',np.sqrt(mean_squared_error(y_val,y_val_pred)))
#cross-val-score
xgb=XGBRegressor(random_state=50,**opt.best_params_)
scores=cross_val_score(xgb,X_train_scaled,y_train,n_jobs=-1,cv=3,scoring=scoring)
print('RMSE: ',np.sqrt(-scores).mean())