欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python機(jī)器學(xué)習(xí)應(yīng)用之基于天氣數(shù)據(jù)集的XGBoost分類篇解讀

 更新時(shí)間:2022年01月18日 17:09:48   作者:柚子味的羊  
XGBoost是一個(gè)優(yōu)化的分布式梯度增強(qiáng)庫,旨在實(shí)現(xiàn)高效,靈活和便攜。它在?Gradient?Boosting?框架下實(shí)現(xiàn)機(jī)器學(xué)習(xí)算法。XGBoost提供并行樹提升(也稱為GBDT,GBM),可以快速準(zhǔn)確地解決許多數(shù)據(jù)科學(xué)問題

一、XGBoost

XGBoost并不是一種模型,而是一個(gè)可供用戶輕松解決分類、回歸或排序問題的軟件包。

1 XGBoost的優(yōu)點(diǎn)

  • 簡單易用。相對(duì)其他機(jī)器學(xué)習(xí)庫,用戶可以輕松使用XGBoost并獲得相當(dāng)不錯(cuò)的效果。
  • 高效可擴(kuò)展。在處理大規(guī)模數(shù)據(jù)集時(shí)速度快效果好,對(duì)內(nèi)存等硬件資源要求不高。
  • 魯棒性強(qiáng)。相對(duì)于深度學(xué)習(xí)模型不需要精細(xì)調(diào)參便能取得接近的效果。
  • XGBoost內(nèi)部實(shí)現(xiàn)提升樹模型,可以自動(dòng)處理缺失值。

2 XGBoost的缺點(diǎn)

  • 相對(duì)于深度學(xué)習(xí)模型無法對(duì)時(shí)空位置建模,不能很好地捕獲圖像、語音、文本等高維數(shù)據(jù)。
  • 在擁有海量訓(xùn)練數(shù)據(jù),并能找到合適的深度學(xué)習(xí)模型時(shí),深度學(xué)習(xí)的精度可以遙遙領(lǐng)先XGBoost。

二、實(shí)現(xiàn)過程

1 數(shù)據(jù)集

天氣數(shù)據(jù)集 提取碼:1234

2 實(shí)現(xiàn)

#%%導(dǎo)入基本庫
import numpy as np 
import pandas as pd

## 繪圖函數(shù)庫
import matplotlib.pyplot as plt
import seaborn as sns
#讀取數(shù)據(jù)
data=pd.read_csv('D:\Python\ML\data\XGBtrain.csv')

通過variable explorer查看樣本數(shù)據(jù)

也可以使用head()或tail()函數(shù),查看樣本前幾行和后幾行。不難看出,數(shù)據(jù)集中含有NAN,代表數(shù)據(jù)中存在缺失值,可能是在數(shù)據(jù)采集或者處理過程中產(chǎn)生的一種錯(cuò)誤,此處采用-1將缺失值進(jìn)行填充,還有其他的填充方法:

  • 中位數(shù)填補(bǔ)
  • 平均數(shù)填補(bǔ)

注:在數(shù)據(jù)的前期處理中,一定要注意對(duì)缺失值的處理。前期數(shù)據(jù)處理的結(jié)果將會(huì)嚴(yán)重影響后面是否可能得到合理的結(jié)果

data=data.fillna(-1)
#利用value_counts()函數(shù)查看訓(xùn)練集標(biāo)簽的數(shù)量(Raintomorrow=no)
print(pd.Series(data['RainTomorrow']).value_counts())
data_des=data.describe()

填充后:

#%%#可視化數(shù)據(jù)(特征值包括數(shù)字特征和非數(shù)字特征)
numerical_features = [x for x in data.columns if data[x].dtype == np.float]
category_features = [x for x in data.columns if data[x].dtype != np.float and x != 'RainTomorrow']
#%% 選取三個(gè)特征與標(biāo)簽組合的散點(diǎn)可視化
sns.pairplot(data=data[['Rainfall','Evaporation','Sunshine'] + ['RainTomorrow']], diag_kind='hist', hue= 'RainTomorrow')
plt.show()

#%%每個(gè)特征的箱圖
i=0
for col in data[numerical_features].columns:
    if col != 'RainTomorrow':
        plt.subplot(2,8,i+1)
        sns.boxplot(x='RainTomorrow', y=col, saturation=0.5, palette='pastel', data=data)
        plt.title(col)
        i=i+1
plt.show()

#%%非數(shù)字特征
tlog = {}
for i in category_features:
    tlog[i] = data[data['RainTomorrow'] == 'Yes'][i].value_counts()
flog = {}
for i in category_features:
    flog[i] = data[data['RainTomorrow'] == 'No'][i].value_counts()
#%%不同地區(qū)下雨情況
plt.figure(figsize=(20,10))
plt.subplot(1,2,1)
plt.title('RainTomorrow')
sns.barplot(x = pd.DataFrame(tlog['Location']).sort_index()['Location'], y = pd.DataFrame(tlog['Location']).sort_index().index, color = "red")
plt.subplot(1,2,2)
plt.title('Not RainTomorrow')
sns.barplot(x = pd.DataFrame(flog['Location']).sort_index()['Location'], y = pd.DataFrame(flog['Location']).sort_index().index, color = "blue")
plt.show()

#%%
plt.figure(figsize=(20,5))
plt.subplot(1,2,1)
plt.title('RainTomorrow')
sns.barplot(x = pd.DataFrame(tlog['RainToday'][:2]).sort_index()['RainToday'], y = pd.DataFrame(tlog['RainToday'][:2]).sort_index().index, color = "red")
plt.subplot(1,2,2)
plt.title('Not RainTomorrow')
sns.barplot(x = pd.DataFrame(flog['RainToday'][:2]).sort_index()['RainToday'], y = pd.DataFrame(flog['RainToday'][:2]).sort_index().index, color = "blue")
plt.show()

XGBoost無法處理字符串類型的數(shù)據(jù),需要將字符串?dāng)?shù)據(jù)轉(zhuǎn)化成數(shù)值

#%%對(duì)離散變量進(jìn)行編碼
## 把所有的相同類別的特征編碼為同一個(gè)值
def get_mapfunction(x):
    mapp = dict(zip(x.unique().tolist(),
         range(len(x.unique().tolist()))))
    def mapfunction(y):
        if y in mapp:
            return mapp[y]
        else:
            return -1
    return mapfunction
#將非數(shù)字特征離散化
for i in category_features:
    data[i] = data[i].apply(get_mapfunction(data[i]))
#%%利用XGBoost進(jìn)行訓(xùn)練與預(yù)測
## 為了正確評(píng)估模型性能,將數(shù)據(jù)劃分為訓(xùn)練集和測試集,并在訓(xùn)練集上訓(xùn)練模型,在測試集上驗(yàn)證模型性能。
from sklearn.model_selection import train_test_split

## 選擇其類別為0和1的樣本 (不包括類別為2的樣本)
data_target_part = data['RainTomorrow']
data_features_part = data[[x for x in data.columns if x != 'RainTomorrow']]

## 測試集大小為20%, 80%/20%分
x_train, x_test, y_train, y_test = train_test_split(data_features_part, data_target_part, test_size = 0.2, random_state = 2020)

#%%導(dǎo)入XGBoost模型
from xgboost.sklearn import XGBClassifier
## 定義 XGBoost模型 
clf = XGBClassifier()
# 在訓(xùn)練集上訓(xùn)練XGBoost模型
clf.fit(x_train, y_train)
#%% 在訓(xùn)練集和測試集上分布利用訓(xùn)練好的模型進(jìn)行預(yù)測
train_predict = clf.predict(x_train)
test_predict = clf.predict(x_test)
from sklearn import metrics

## 利用accuracy(準(zhǔn)確度)【預(yù)測正確的樣本數(shù)目占總預(yù)測樣本數(shù)目的比例】評(píng)估模型效果
print('The accuracy of the XGBoost is:',metrics.accuracy_score(y_train,train_predict))
print('The accuracy of the XGBoost is:',metrics.accuracy_score(y_test,test_predict))

## 查看混淆矩陣 (預(yù)測值和真實(shí)值的各類情況統(tǒng)計(jì)矩陣)
confusion_matrix_result = metrics.confusion_matrix(test_predict,y_test)
print('The confusion matrix result:\n',confusion_matrix_result)

# 利用熱力圖對(duì)于結(jié)果進(jìn)行可視化
plt.figure(figsize=(8, 6))
sns.heatmap(confusion_matrix_result, annot=True, cmap='Blues')
plt.xlabel('Predicted labels')
plt.ylabel('True labels')
plt.show()

#%%利用XGBoost進(jìn)行特征選擇:
#XGboost中可以用屬性feature_importances_去查看特征的重要度。
sns.barplot(y=data_features_part.columns,x=clf.feature_importances_)

初次之外,我們還可以使用XGBoost中的下列重要屬性來評(píng)估特征的重要性:

  • weight:是以特征用到的次數(shù)來評(píng)價(jià)
  • gain:當(dāng)利用特征做劃分的時(shí)候的評(píng)價(jià)基尼指數(shù)
  • cover:利用一個(gè)覆蓋樣本的指標(biāo)二階導(dǎo)數(shù)(具體原理不清楚有待探究)平均值來劃分。
  • total_gain:總基尼指數(shù)
  • total_cover:總覆蓋
#利用XGBoost的其他重要參數(shù)評(píng)估特征的重要性
from sklearn.metrics import accuracy_score
from xgboost import plot_importance

def estimate(model,data):
    #sns.barplot(data.columns,model.feature_importances_)
    ax1=plot_importance(model,importance_type="gain")
    ax1.set_title('gain')
    ax2=plot_importance(model, importance_type="weight")
    ax2.set_title('weight')
    ax3 = plot_importance(model, importance_type="cover")
    ax3.set_title('cover')
    plt.show()
def classes(data,label,test):
    model=XGBClassifier()
    model.fit(data,label)
    ans=model.predict(test)
    estimate(model, data)
    return ans
 
ans=classes(x_train,y_train,x_test)
pre=accuracy_score(y_test, ans)
print('acc=',accuracy_score(y_test,ans))

XGBoost中包括但不限于下列對(duì)模型影響較大的參數(shù):

  • learning_rate: 有時(shí)也叫作eta,系統(tǒng)默認(rèn)值為0.3。每一步迭代的步長,很重要。太大了運(yùn)行準(zhǔn)確率不高,太小了運(yùn)行速度慢。
  • subsample:系統(tǒng)默認(rèn)為1。這個(gè)參數(shù)控制對(duì)于每棵樹,隨機(jī)采樣的比例。減小這個(gè)參數(shù)的值,算法會(huì)更加保守,避免過擬合, 取值范圍零到一。
  • colsample_bytree:系統(tǒng)默認(rèn)值為1。我們一般設(shè)置成0.8左右。用來控制每棵隨機(jī)采樣的列數(shù)的占比(每一列是一個(gè)特征)。max_depth: 系統(tǒng)默認(rèn)值為6,我們常用3-10之間的數(shù)字。這個(gè)值為樹的最大深度。這個(gè)值是用來控制過擬合的。
  • max_depth越大,模型學(xué)習(xí)的更加具體。

調(diào)節(jié)模型參數(shù)的方法有貪心算法、網(wǎng)格調(diào)參、貝葉斯調(diào)參等。這里我們采用網(wǎng)格調(diào)參,它的基本思想是窮舉搜索:在所有候選的參數(shù)選擇中,通過循環(huán)遍歷,嘗試每一種可能性,表現(xiàn)最好的參數(shù)就是最終的結(jié)果

#%%通過調(diào)參獲得更好的效果
## 從sklearn庫中導(dǎo)入網(wǎng)格調(diào)參函數(shù)
from sklearn.model_selection import GridSearchCV

## 定義參數(shù)取值范圍
learning_rate = [0.1, 0.3, 0.6]
subsample = [0.8, 0.9]
colsample_bytree = [0.6, 0.8]
max_depth = [3,5,8]

parameters = { 'learning_rate': learning_rate,
              'subsample': subsample,
              'colsample_bytree':colsample_bytree,
              'max_depth': max_depth}
model = XGBClassifier(n_estimators = 50)

## 進(jìn)行網(wǎng)格搜索
clf = GridSearchCV(model, parameters, cv=3, scoring='accuracy',verbose=1,n_jobs=-1)
clf = clf.fit(x_train, y_train)
#%%網(wǎng)格搜索后的參數(shù)
print(clf.best_params_)

#%% 在訓(xùn)練集和測試集上分別利用最好的模型參數(shù)進(jìn)行預(yù)測
## 定義帶參數(shù)的 XGBoost模型 
clf = XGBClassifier(colsample_bytree = 0.6, learning_rate = 0.3, max_depth= 8, subsample = 0.9)
# 在訓(xùn)練集上訓(xùn)練XGBoost模型
clf.fit(x_train, y_train)

train_predict = clf.predict(x_train)
test_predict = clf.predict(x_test)

## 利用accuracy(準(zhǔn)確度)【預(yù)測正確的樣本數(shù)目占總預(yù)測樣本數(shù)目的比例】評(píng)估模型效果
print('The accuracy of the Logistic Regression is:',metrics.accuracy_score(y_train,train_predict))
print('The accuracy of the Logistic Regression is:',metrics.accuracy_score(y_test,test_predict))

## 查看混淆矩陣 (預(yù)測值和真實(shí)值的各類情況統(tǒng)計(jì)矩陣)
confusion_matrix_result = metrics.confusion_matrix(test_predict,y_test)
print('The confusion matrix result:\n',confusion_matrix_result)

# 利用熱力圖對(duì)于結(jié)果進(jìn)行可視化
plt.figure(figsize=(8, 6))
sns.heatmap(confusion_matrix_result, annot=True, cmap='Blues')
plt.xlabel('Predicted labels')
plt.ylabel('True labels')
plt.show()

三、Keys

XGBoost的重要參數(shù)

  • eta【默認(rèn)0.3】:通過為每一顆樹增加權(quán)重,提高模型的魯棒性。典型值為0.01-0.2。
  • min_child_weight【默認(rèn)1】:決定最小葉子節(jié)點(diǎn)樣本權(quán)重和。這個(gè)參數(shù)可以避免過擬合。當(dāng)它的值較大時(shí),可以避免模型學(xué)習(xí)到局部的特殊樣本。但是如果這個(gè)值過高,則會(huì)導(dǎo)致模型擬合不充分。
  • max_depth【默認(rèn)6】:這個(gè)值也是用來避免過擬合的,max_depth越大,模型會(huì)學(xué)到更具體更局部的樣本。典型值:3-10
  • max_leaf_nodes:樹上最大的節(jié)點(diǎn)或葉子的數(shù)量??梢蕴娲鷐ax_depth的作用。這個(gè)參數(shù)的定義會(huì)導(dǎo)致忽略max_depth參數(shù)。
  • gamma【默認(rèn)0】:在節(jié)點(diǎn)分裂時(shí),只有分裂后損失函數(shù)的值下降了,才會(huì)分裂這個(gè)節(jié)點(diǎn)。Gamma指定了節(jié)點(diǎn)分裂所需的最小損失函數(shù)下降值。這個(gè)參數(shù)的值越大,算法越保守。這個(gè)參數(shù)的值和損失函數(shù)息息相關(guān)。
  • max_delta_step【默認(rèn)0】:這個(gè)參數(shù)限制每棵樹權(quán)重改變的最大步長。如果這個(gè)參數(shù)的值為0,那就意味著沒有約束。如果它被賦予了某個(gè)正值,那么它會(huì)讓這個(gè)算法更加保守。但是當(dāng)各類別的樣本十分不平衡時(shí),它對(duì)分類問題是很有幫助的。
  • subsample【默認(rèn)1】:這個(gè)參數(shù)控制對(duì)于每棵樹,隨機(jī)采樣的比例。減小這個(gè)參數(shù)的值,算法會(huì)更加保守,避免過擬合。但是,如果這個(gè)值設(shè)置得過小,它可能會(huì)導(dǎo)致欠擬合。典型值:0.5-1
  • colsample_bytree【默認(rèn)1】:用來控制每棵隨機(jī)采樣的列數(shù)的占比(每一列是一個(gè)特征)。典型值:0.5-1
  • colsample_bylevel【默認(rèn)1】:用來控制樹的每一級(jí)的每一次分裂,對(duì)列數(shù)的采樣的占比。subsample參數(shù)和colsample_bytree參數(shù)可以起到相同的作用,一般用不到。
  • lambda【默認(rèn)1】:權(quán)重的L2正則化項(xiàng)。(和Ridge regression類似)。這個(gè)參數(shù)是用來控制XGBoost的正則化部分的。雖然大部分?jǐn)?shù)據(jù)科學(xué)家很少用到這個(gè)參數(shù),但是這個(gè)參數(shù)在減少過擬合上還是可以挖掘出更多用處的。
  • alpha【默認(rèn)1】:權(quán)重的L1正則化項(xiàng)。(和Lasso regression類似)。可以應(yīng)用在很高維度的情況下,使得算法的速度更快。
  • scale_pos_weight【默認(rèn)1】:在各類別樣本十分不平衡時(shí),把這個(gè)參數(shù)設(shè)定為一個(gè)正值,可以使算法更快收斂。

886~~

到此這篇關(guān)于Python機(jī)器學(xué)習(xí)應(yīng)用之基于天氣數(shù)據(jù)集的XGBoost分類篇解讀的文章就介紹到這了,更多相關(guān)Python XGBoost內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論