代碼如下所示:
# -*- coding: utf-8 -*- #導入需要的包 import matplotlib.pyplot as plt from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.metrics import roc_auc_score from xgboost import XGBClassifier from xgboost import plot_importance ### 加載數據集,這里直接使用datasets包里面的波士頓房價數據 boston=datasets.load_breast_cancer() #輸出數據集的形狀,該數據集里面有569個樣本,每個樣本有30個特征(569, 30) print(boston.data.shape) #輸出標簽的個數為 569 print(boston.target.shape) # 使用train_test_split()函數對訓練集和測試集進行划分,第一個參數是數據集特征,第二個參數是標簽,第三個為測試集占總樣本的百分比 x_train,x_test,y_train,y_test = train_test_split(boston.data, boston.target, test_size = 0.3, random_state = 33) #使用XGBoost進行訓練 model = XGBClassifier() model.fit(x_train,y_train) # 繪制重要性曲線,max_num_feature參數設置輸出前20重要的特征() plot_importance(model,max_num_features=20) plt.show() # 輸入測試樣本做預測 y_pred=model.predict_proba(x_test)[:,1] # 輸出AUROC的值 roc=roc_auc_score(y_test,y_pred) print("The AUROC=%f",roc) """ 0.9841 """
運行結果:
其中,f2,f3,f4...這些是默認的按從0開始對特征的編號。但是這樣的話,我們不知道這些f2,f3到底對應的是哪些特征。我覺得應該有函數什么的吧,要不然的話,怎么進行具體的分析呢。這個問題有待解決。