
如何使用Requests-OAuthlib實(shí)現(xiàn)OAuth認(rèn)證
import xgboost as xgbimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import accuracy_scorefrom sklearn.datasets import load_breast_cancer
2、xgboost
繼續(xù)采用乳腺癌數(shù)據(jù)集進(jìn)行演示,該數(shù)據(jù)包含30個自變量與1個因變量,因變量表示癌癥的類型,為二分類數(shù)據(jù),分別是良性、惡性。乳腺癌數(shù)據(jù)集在前期多次展示過,具體的數(shù)據(jù)可以通過幫助文檔查看,這里就不列了。
# 加載乳腺癌數(shù)據(jù)集cancer = load_breast_cancer()
# 劃分訓(xùn)練集和測試集xtrain, xtest, ytrain, ytest = train_test_split(cancer.data, cancer.target, random_state=123,test_size=0.3)print(xtrain.shape)
# 定義XGBoost模型model = xgb.XGBClassifier( max_depth=3, learning_rate=0.01, n_estimators=200, objective='binary:logistic') # 訓(xùn)練模型model.fit(xtrain, ytrain)# 計(jì)算準(zhǔn)確率print(model.score(xtrain, ytrain)) #訓(xùn)練性能print(model.score(xtest, ytest)) #泛化性能# print(model.feature_importances_) #特征重要性
# 另一種計(jì)算準(zhǔn)確率的方法#y_pred = model.predict(xtest)# accuracy = accuracy_score(ytest, y_pred)# print(accuracy)
解讀:在這個例子中,我們使用XGBClassifier
類定義了一個二分類的XGBoost模型,并設(shè)置了一些超參數(shù),如max_depth
表示樹的最大深度,learning_rate
表示學(xué)習(xí)率,n_estimators
表示樹的個數(shù),objective
表示損失函數(shù)。使用fit
方法訓(xùn)練模型,計(jì)算準(zhǔn)確率并打印出來。
3、特征重要性的可視化
print(model.feature_importances_) #特征重要性
#自建繪圖函數(shù)
def plot_feature_importances_cancer(model):
n_features = cancer.data.shape[1] #獲取特征名稱
plt.barh(range(n_features), model.feature_importances_, align='center',color = 'gold') #條形圖
plt.yticks(np.arange(n_features), cancer.feature_names)
plt.xlabel("Feature importance")
plt.ylabel("Feature")
輸出的圖是可以自定義的,比如改變顏色等。另外,本例是手動設(shè)置xgboost的超參數(shù),實(shí)際上并不科學(xué),后續(xù)會介紹超參數(shù)調(diào)優(yōu)方法。
文章轉(zhuǎn)載自: python機(jī)器學(xué)習(xí):超越隨機(jī)森林(XGBoost篇)
如何使用Requests-OAuthlib實(shí)現(xiàn)OAuth認(rèn)證
2025年最新LangChain Agent教程:從入門到精通
Python實(shí)現(xiàn)五子棋AI對戰(zhàn)的詳細(xì)教程
2025年AI代碼生成工具Tabnine AI的9個替代者推薦
一步步教你配置Obsidian Copilot實(shí)現(xiàn)API集成
如何使用python和django構(gòu)建后端rest api
如何將soap api轉(zhuǎn)換為rest api
如何使用REST API自動化工具提升效率
如何處理REST API響應(yīng)的完整指南