1、集成學習是指對於同一個基礎數據集使用不同的機器學習算法進行訓練,最后結合不同的算法給出的意見進行決策,這個方法兼顧了許多算法的"意見",比較全面,因此在機器學習領域也使用地非常廣泛。生活中其實也普遍存在集成學習的方法,比如買東西找不同的人進行推薦,病情診斷進行多專家會診等,考慮各方面的意見進行最終的綜合的決策,這樣得到的結果可能會更加的全面和准確。另外,sklearn中也提供了集成學習的接口voting classifier。
sklearn中具體調用集成學習方法的具體代碼如下:
#使用集成學習的方法進行數據訓練和預測
#1-1導入原始基礎數據集並且進行數據的預處理
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
x,y=datasets.make_moons(n_samples=500,noise=0.3,random_state=42) #生成數據默認為100個數據樣本
print(x.shape)
print(y.shape)
plt.figure()
plt.scatter(x[y==0,0],x[y==0,1],color="r")
plt.scatter(x[y==1,0],x[y==1,1],color="g")
plt.show()
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(x,y,random_state=42)
#導入sklearn中的不同機器學習算法
#1邏輯回歸算法
from sklearn.linear_model import LogisticRegression
log_reg=LogisticRegression()
log_reg.fit(x_train,y_train)
print(log_reg.score(x_test,y_test))
#2支撐向量機SVM算法
from sklearn.svm import SVC
svc_reg=SVC()
svc_reg.fit(x_train,y_train)
print(svc_reg.score(x_test,y_test))
#KNN算法
from sklearn.neighbors import KNeighborsClassifier
knn_reg=KNeighborsClassifier(n_neighbors=3)
knn_reg.fit(x_train,y_train)
print(knn_reg.score(x_test,y_test))
#決策樹算法
from sklearn.tree import DecisionTreeClassifier
tree_reg=DecisionTreeClassifier()
tree_reg.fit(x_train ,y_train)
print(tree_reg.score(x_test,y_test))
y_predict1=log_reg.predict(x_test)
y_predict2=knn_reg.predict(x_test)
y_predict3=svc_reg.predict(x_test)
y_predict4=tree_reg.predict(x_test)
y_predict=np.array(y_predict1+y_predict2+y_predict3+y_predict4>=3,dtype="int") #自己簡單采用集成學習的方法來進行相應的預測
from sklearn.metrics import accuracy_score
score=accuracy_score(y_predict,y_test)
print(score)
#使用sklearn中的集成學習接口進行相應的訓練和預測—hard voting是投票時少數服從多數的原則(可以先把每個算法調到最好的結果,然后再用集成學習的算法進行預測)
from sklearn.ensemble import VotingClassifier
vote_reg=VotingClassifier(estimators=[
("log_cla",LogisticRegression()),
("svm_cla",SVC()),
("knn",KNeighborsClassifier()),
("tree",DecisionTreeClassifier(random_state=666))
],voting="hard")
vote_reg.fit(x_train,y_train)
print(vote_reg.score(x_test,y_test))
#使用sklearn中的集成學習接口進行相應的訓練和預測—soft voting是投票時不同算法不同權重的原則(可以先把每個算法調到最好的結果,然后再用集成學習的算法進行預測)
from sklearn.ensemble import VotingClassifier
vote_reg1=VotingClassifier(estimators=[
("log_cla",LogisticRegression()),
("svm_cla",SVC(probability=True)), #SVC算法本來是計算不了概率的,但是經過一定的改進便可以計算概率,需要使得probability=true
("knn",KNeighborsClassifier()),
("tree",DecisionTreeClassifier(random_state=666))
],voting="soft")
vote_reg1.fit(x_train,y_train)
print(vote_reg1.score(x_test,y_test))
#采用有放回bagging和無放回pasting兩種不同的方式來進行集成學習的訓練(bootstrap決定有無放回,true代表有放回)
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
x,y=datasets.make_moons(n_samples=500,noise=0.3,random_state=42) #生成數據默認為100個數據樣本
print(x.shape)
print(y.shape)
plt.figure()
plt.scatter(x[y==0,0],x[y==0,1],color="r")
plt.scatter(x[y==1,0],x[y==1,1],color="g")
plt.show()
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(x,y,random_state=42)
#使用bagging的方式進行集成學習
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import BaggingClassifier
bag_reg=BaggingClassifier(DecisionTreeClassifier(),n_estimators=500,max_samples=100,bootstrap=True)
bag_reg.fit(x_train,y_train)
print(bag_reg.score(x_test,y_test))
#采用oob的方式對於訓練模型進行數據的測試驗證oob_score=true
bag_reg1=BaggingClassifier(DecisionTreeClassifier(),n_estimators=500,max_samples=100,bootstrap=True,oob_score=True,n_jobs=-1)
bag_reg1.fit(x_train,y_train)
print(bag_reg1.score(x_test,y_test))
print(bag_reg1.oob_score_)
#采用隨機特征數目的方式對於訓練模型進行數據的測試驗證 max_features=樣本隨機特征數(主要用於圖像識別領域數據樣本特征比較多的數據集)
bag_reg2=BaggingClassifier(DecisionTreeClassifier(),n_estimators=500,max_samples=100,bootstrap=True,oob_score=True,n_jobs=-1,max_features=1,bootstrap_features=True)
bag_reg2.fit(x_train,y_train)
print(bag_reg1.score(x_test,y_test))
print(bag_reg1.oob_score_)
#使用隨機森林的算法進行集成學習的訓練和預測
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
x,y=datasets.make_moons(n_samples=500,noise=0.3,random_state=42) #生成數據默認為100個數據樣本
print(x.shape)
print(y.shape)
plt.figure()
plt.scatter(x[y==0,0],x[y==0,1],color="r")
plt.scatter(x[y==1,0],x[y==1,1],color="g")
plt.show()
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(x,y,random_state=42)
from sklearn.ensemble import RandomForestClassifier
rf1=RandomForestClassifier(n_estimators=500,random_state=666,oob_score=True,n_jobs=-1) #利用隨機森林的方法用取不到的數據進行相應的訓練
rf1.fit(x,y)
print(rf1.oob_score_)
rf1=RandomForestClassifier(n_estimators=500,random_state=666,max_leaf_nodes=16,oob_score=True,n_jobs=-1)
rf1.fit(x,y)
print(rf1.oob_score_)
#使用極其隨機森林的算法進行集成學習的訓練和預測(extra tree是指特征隨機,並且節點閾值也隨機,使得決策樹之間差異更大,增加了隨機性,降低了過擬合,不過也增加了一定的偏差)
from sklearn.ensemble import ExtraTreesClassifier
et=ExtraTreesClassifier(n_estimators=500,n_jobs=-1,bootstrap=True,oob_score=True)
et.fit(x,y)
print(et.oob_score_)
###利用集成學習解決回歸問題
from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import ExtraTreesRegressor
from sklearn.ensemble import BaggingRegressor
#回歸問題和分類問題是一致的,超參數也是統一的,使用參照以上分類算法,只不過其輸出結果是一個數值而非類別
#集成學習的第二種類:Boosting集成多個模型,模型之間是用關系的,它們均在增強整體的效果,主要有Ada Boosting 和Gradient Boosting
#第一種boosting的方式Ada Boosting方式
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
x,y=datasets.make_moons(n_samples=500,noise=0.3,random_state=666) #生成數據默認為100個數據樣本
print(x.shape)
print(y.shape)
plt.figure()
plt.scatter(x[y==0,0],x[y==0,1],color="r")
plt.scatter(x[y==1,0],x[y==1,1],color="g")
plt.show()
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(x,y,random_state=666)
from sklearn.ensemble import AdaBoostClassifier
from sklearn.tree import DecisionTreeClassifier
ada_boost=AdaBoostClassifier(DecisionTreeClassifier(max_depth=2,min_samples_leaf=10,max_leaf_nodes=20),n_estimators=1000,random_state=666)
ada_boost.fit(x_train,y_train)
print(ada_boost.score(x_test,y_test))
#第二種boosting方式:Gradient Boosting,利用特定的機器學習算法對於數據進行訓練和預測,然后將模型誤差再進行訓練,然后再對誤差的誤差訓練,依次疊加,最終得到的訓練結果就是最終的結果
from sklearn.ensemble import GradientBoostingClassifier
gb_boost=GradientBoostingClassifier(max_depth=5,n_estimators=3000)
gb_boost.fit(x_train,y_train)
print(gb_boost.score(x_test,y_test))
#第三種集成學習的思路stacking集成學習的方法:多模型多層次的模型融合集成學習方法
最終的運行結果如下所示: