-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSupervised_learning(Ansemble_tech)py
More file actions
149 lines (123 loc) · 7.25 KB
/
Supervised_learning(Ansemble_tech)py
File metadata and controls
149 lines (123 loc) · 7.25 KB
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
import pickle
import numpy as np
from sklearn.model_selection import cross_val_score
from sklearn.ensemble import BaggingClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.calibration import CalibratedClassifierCV
from sklearn.calibration import calibration_curve
covertype_dataset = pickle.load(open("covertype_dataset.pickle", "rb"))
print (covertype_dataset.DESCR)
covertype_X = covertype_dataset.data[:15000,:]
covertype_y = covertype_dataset.target[:15000]
covertypes = ['Spruce/Fir', 'Lodgepole Pine', 'Ponderosa Pine','Cottonwood/Willow', 'Aspen', 'Douglas-fir', 'Krummholz']
# The advantage of using weak learners and ensembling them is that they can be trained more
# quickly than complex algorithms.
hypothesis = BaggingClassifier(KNeighborsClassifier(n_neighbors=1),max_samples=0.7, max_features=0.7,n_estimators=100)
scores = cross_val_score(hypothesis, covertype_X, covertype_y, cv=3,scoring='accuracy', n_jobs=-1)
print ("BaggingClassifier -> cross validation accuracy: mean = %0.3fstd = %0.3f" % (np.mean(scores), np.std(scores)))
# %time
hypothesis = RandomForestClassifier(n_estimators=100, random_state=101)
scores = cross_val_score(hypothesis, covertype_X, covertype_y,cv=3, scoring='accuracy', n_jobs=-1)
print ("RandomForestClassifier -> cross validation accuracy: \mean = %0.3f std = %0.3f" % (np.mean(scores), np.std(scores)))
hypothesis = ExtraTreesClassifier(n_estimators=100 , random_state=101)
scores = cross_val_score(hypothesis , covertype_X,covertype_y , cv=3 , scoring='accuracy',n_jobs=-1)
print ("ExtraTreesClassifier -> cross validation accuracy: mean = %0.3fstd = %0.3f" % (np.mean(scores), np.std(scores)))
# Covertype problem using CalibratedClassifierCV:
hypothesis = RandomForestClassifier(n_estimators=100,random_state=101)
calibration = CalibratedClassifierCV(hypothesis , method='sigmoid',cv=5)
covertype_X = covertype_dataset.data[:15000,:]
covertype_y = covertype_dataset.target[:15000]
covertype_test_X = covertype_dataset.data[15000:25000,:]
covertype_test_y = covertype_dataset.target[15000:25000]
hypothesis.fit(covertype_X,covertype_y)
calibration.fit(covertype_X,covertype_y)
prob_raw =hypothesis.predict_proba(covertype_test_X)
prob_cal = hypothesis.predict_proba(covertype_test_y)
# Sequences of models
# -->AdaBoost
from sklearn.ensemble import AdaBoostClassifier
hypothesis = AdaBoostClassifier(n_estimators=300, random_state=101)
scores = cross_val_score(hypothesis, covertype_X, covertype_y, cv=3,scoring='accuracy', n_jobs=-1)
print ("Adaboost -> cross validation accuracy: mean = %0.3fstd = %0.3f" % (np.mean(scores), np.std(scores)))
# --> Gradient tree boosting (GTB)
import pickle
covertype_dataset = pickle.load(open("covertype_dataset.pickle", "rb"))
covertype_X = covertype_dataset.data[:15000,:]
covertype_y = covertype_dataset.target[:15000] -1
covertype_val_X = covertype_dataset.data[15000:20000,:]
covertype_val_y = covertype_dataset.target[15000:20000] -1
covertype_test_X = covertype_dataset.data[20000:25000,:]
covertype_test_y = covertype_dataset.target[20000:25000] -1
from sklearn.model_selection import cross_val_score, StratifiedKFold
from sklearn.ensemble import GradientBoostingClassifier
hypothesis = GradientBoostingClassifier(max_depth=5,n_estimators=50,random_state=101)
hypothesis.fit(covertype_X, covertype_y)
from sklearn.metrics import accuracy_score
print ("GradientBoostingClassifier -> test accuracy:",accuracy_score(covertype_test_y,hypothesis.predict(covertype_test_X)))
# --> XGBoost
from sklearn.datasets import fetch_covtype
from sklearn.model_selection import cross_val_score, StratifiedKFold
covertype_dataset = fetch_covtype(random_state=101, shuffle=True)
covertype_dataset.target = covertype_dataset.target.astype(int)
covertype_X = covertype_dataset.data[:15000,:]
covertype_y = covertype_dataset.target[:15000] -1
covertype_val_X = covertype_dataset.data[15000:20000,:]
covertype_val_y = covertype_dataset.target[15000:20000] -1
covertype_test_X = covertype_dataset.data[20000:25000,:]
covertype_test_y = covertype_dataset.target[20000:25000] -1
import xgboost as xgb
hypothesis = xgb.XGBClassifier(objective= "multi:softprob",max_depth = 24,gamma=0.1,subsample = 0.90,learning_rate=0.01,n_estimators = 500,nthread=-1)
hypothesis.fit(covertype_X, covertype_y,eval_set=[(covertype_val_X, covertype_val_y)],eval_metric='merror', early_stopping_rounds=25,verbose=False)
from sklearn.metrics import accuracy_score, confusion_matrix
print ('test accuracy:', accuracy_score(covertype_test_y,hypothesis.predict(covertype_test_X)))
print (confusion_matrix(covertype_test_y,hypothesis.predict(covertype_test_X)))
# XGBoost peruses a breadth-first search (BFS), whereas LightGBM a depth first search (DFS).
# --> LightGBM
from sklearn.ensemble import lightgbm as lgb
import numpy as np
params = {'task': 'train','boosting_type': 'gbdt','objective': 'multiclass','num_class':len(np.unique(covertype_y)),
'metric': 'multi_logloss','learning_rate': 0.01,'max_depth': 128,'num_leaves': 256,'feature_fraction': 0.9,
'bagging_fraction': 0.9,'bagging_freq': 10}
train_data = lgb.Dataset(data=covertype_X, label=covertype_y)
val_data = lgb.Dataset(data=covertype_val_X, label=covertype_val_y)
bst = lgb.train(params,train_data,num_boost_round=2500,
valid_sets=val_data,verbose_eval=500,
early_stopping_rounds=25)
lgb_cv = lgb.cv(params,train_data,num_boost_round=2500,nfold=3,
shuffle=True,stratified=True,verbose_eval=500,early_stopping_rounds=25)
nround = lgb_cv['multi_logloss-mean'].index(np.min(lgb_cv['multi_logloss-mean']))
print("Best number of rounds: %i" % nround)
y_probs = bst.predict(covertype_test_X,num_iteration=bst.best_iteration)
y_preds = np.argmax(y_probs, axis=1)
from sklearn.metrics import accuracy_score, confusion_matrix
print('test accuracy:', accuracy_score(covertype_test_y, y_preds))
print(confusion_matrix(covertype_test_y, y_preds))
# --> catBoost
import numpy as np
from sklearn.datasets import fetch_covtype
from catboost import CatBoostClassifier, Pool
covertype_dataset = fetch_covtype(random_state=101,shuffle=True)
label = covertype_dataset.target.astype(int) - 1
wilderness_area =np.argmax(covertype_dataset.data[:,10:(10+4)],axis=1)
soil_type = np.argmax(covertype_dataset.data[:,(10+4):(10+4+40)],axis=1)
data = (covertype_dataset.data[:,:10],wilderness_area.reshape(-1,1),soil_type.reshape(-1,1))
data = np.hstack(data)
covertype_train = Pool(data[:15000,:],label[:15000], [10, 11])
covertype_val = Pool(data[15000:20000,:],label[15000:20000], [10, 11])
covertype_test = Pool(data[20000:25000,:],None, [10, 11])
covertype_test_y = label[20000:25000]
model = CatBoostClassifier(iterations=4000,
learning_rate=0.05,
depth=8,
custom_loss = 'Accuracy',
eval_metric = 'Accuracy',
use_best_model=True,
loss_function='MultiClass')
model.fit(covertype_train, eval_set=covertype_val,
verbose=False, plot=True)
preds_class = model.predict(covertype_test)
preds_proba = model.predict_proba(covertype_test)
print('test accuracy:', accuracy_score(covertype_test_y,preds_class))
print(confusion_matrix(covertype_test_y, preds_class))