安全的關(guān)鍵.png)
使用這些基本 REST API 最佳實(shí)踐構(gòu)建出色的 API
import numpy as np
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings("ignore")
plt.rcParams['font.family'] = 'Times New Roman'
plt.rcParams['axes.unicode_minus'] = False
df = pd.read_excel('2024-11-10-公眾號(hào)Python機(jī)器學(xué)習(xí)AI.xlsx')
from sklearn.model_selection import train_test_split
X = df.drop(['待預(yù)測(cè)變量Y'],axis=1)
y = df['待預(yù)測(cè)變量Y']
# 劃分訓(xùn)練集和測(cè)試集
X_temp, X_test, y_temp, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 然后將訓(xùn)練集進(jìn)一步劃分為訓(xùn)練集和驗(yàn)證集
X_train, X_val, y_train, y_val = train_test_split(X_temp, y_temp, test_size=0.125, random_state=42) # 0.125 x 0.8 = 0.1
import optuna # 導(dǎo)入Optuna庫(kù),用于超參數(shù)優(yōu)化
from xgboost import XGBRegressor
from sklearn.metrics import mean_squared_error
from optuna.visualization import plot_optimization_history, plot_contour, plot_param_importances, plot_parallel_coordinate, plot_edf # 導(dǎo)入Optuna的可視化工具,用于繪制優(yōu)化歷史、參數(shù)重要性等
# 定義目標(biāo)函數(shù),用于Optuna的優(yōu)化
def objective(trial):
# 定義模型的超參數(shù)搜索空間,Optuna會(huì)在此范圍內(nèi)進(jìn)行參數(shù)采樣
params = {
# 'n_estimators':模型中要構(gòu)建的決策樹的數(shù)量
# 值越高,模型擬合越充分,但計(jì)算開(kāi)銷也更大。一般較低的值適合快速迭代和避免過(guò)擬合
'n_estimators': trial.suggest_categorical('n_estimators', [50, 100, 200, 300]), #離散的類別選擇范圍
# 'max_depth':控制每棵樹的深度,以防止過(guò)擬合。較高的深度會(huì)增加模型復(fù)雜性
'max_depth': trial.suggest_int('max_depth', 3, 15, step=1), #整數(shù)范圍
# 'learning_rate':學(xué)習(xí)率決定每棵樹對(duì)最終預(yù)測(cè)的貢獻(xiàn)。較小的學(xué)習(xí)率通常需要更大的'n_estimators'來(lái)充分學(xué)習(xí)
'learning_rate': trial.suggest_loguniform('learning_rate', 0.01, 0.3), # 對(duì)數(shù)均勻分布的連續(xù)浮點(diǎn)數(shù)范圍
# 'subsample':表示每棵樹隨機(jī)選擇的樣本比例,通常用于減少過(guò)擬合
'subsample': trial.suggest_uniform('subsample', 0.5, 1.0), # 線性均勻分布的連續(xù)浮點(diǎn)數(shù)范圍
# 'colsample_bytree':控制每棵樹使用的特征比例,以增強(qiáng)模型的魯棒性
'colsample_bytree': trial.suggest_uniform('colsample_bytree', 0.5, 1.0),
# 'gamma':控制是否允許分裂,越高的值會(huì)使算法更保守,幫助避免過(guò)擬合
'gamma': trial.suggest_uniform('gamma', 0, 5)
}
# 使用采樣的參數(shù)創(chuàng)建XGBRegressor模型
model = XGBRegressor(**params, random_state=42)
# 使用訓(xùn)練數(shù)據(jù)擬合模型
model.fit(X_train, y_train)
# 使用驗(yàn)證集進(jìn)行預(yù)測(cè)
y_pred = model.predict(X_val)
# 計(jì)算并返回均方誤差(MSE),作為優(yōu)化的目標(biāo)
return mean_squared_error(y_val, y_pred)
# 創(chuàng)建Optuna的Study對(duì)象,并設(shè)置優(yōu)化方向?yàn)椤癿inimize”表示最小化均方誤差
# 默認(rèn)情況下,Optuna使用的優(yōu)化算法是 TPE (Tree-structured Parzen Estimator),
# 這是一種貝葉斯優(yōu)化方法,適合高效地探索超參數(shù)空間
study = optuna.create_study(direction="minimize")
# 運(yùn)行優(yōu)化,進(jìn)行100次試驗(yàn)
study.optimize(objective, n_trials=100)
print("Best parameters:", study.best_params)
# 使用最佳參數(shù)重新訓(xùn)練模型
best_model = XGBRegressor(**study.best_params, random_state=42)
best_model.fit(X_train, y_train)
使用Optuna庫(kù)對(duì)XGBoost回歸模型進(jìn)行自動(dòng)化超參數(shù)優(yōu)化。首先,代碼將數(shù)據(jù)集劃分為訓(xùn)練集、驗(yàn)證集和測(cè)試集,然后定義目標(biāo)函數(shù)(objective)來(lái)指定要優(yōu)化的超參數(shù)范圍,包括n_estimators、max_depth、learning_rate、subsample、colsample_bytree和gamma。Optuna在此范圍內(nèi)自動(dòng)采樣超參數(shù)組合,通過(guò)最小化均方誤差(MSE)來(lái)找到最優(yōu)參數(shù),運(yùn)行100次試驗(yàn)后,代碼輸出最優(yōu)參數(shù)并用其重新訓(xùn)練XGBoost模型,從而提高模型性能
# 獲取優(yōu)化歷史中的數(shù)據(jù),每列的含義如下:
# 'trial_number': 每次試驗(yàn)的編號(hào),用于區(qū)分不同的試驗(yàn)
# 'value': 每次試驗(yàn)的目標(biāo)值(優(yōu)化過(guò)程中的結(jié)果),通常是需要最小化或最大化的目標(biāo)值
# 'datetime_start': 每次試驗(yàn)的開(kāi)始時(shí)間,用于記錄試驗(yàn)的開(kāi)始時(shí)間點(diǎn)
# 'datetime_complete': 每次試驗(yàn)的完成時(shí)間,用于記錄試驗(yàn)的結(jié)束時(shí)間點(diǎn)
optimization_history = {
'trial_number': [], # 試驗(yàn)編號(hào)
'value': [], # 目標(biāo)值
'datetime_start': [], # 試驗(yàn)開(kāi)始時(shí)間
'datetime_complete': [] # 試驗(yàn)完成時(shí)間
}
for trial in study.trials:
optimization_history['trial_number'].append(trial.number)
optimization_history['value'].append(trial.value)
optimization_history['datetime_start'].append(trial.datetime_start)
optimization_history['datetime_complete'].append(trial.datetime_complete)
# 將數(shù)據(jù)轉(zhuǎn)換為 DataFrame
optimization_history = pd.DataFrame(optimization_history)
optimization_history
從Optuna的study對(duì)象中提取每次試驗(yàn)的編號(hào)、目標(biāo)值、開(kāi)始和結(jié)束時(shí)間,存入字典并轉(zhuǎn)換為DataFrame,以便查看和分析優(yōu)化歷史
# 找到最優(yōu)試驗(yàn)
best_trial_idx = optimization_history['value'].idxmin()
best_trial_number = optimization_history['trial_number'][best_trial_idx]
best_value = optimization_history['value'][best_trial_idx]
plt.figure(figsize=(10, 6), dpi=1200)
# 繪制非最佳點(diǎn)
plt.plot(
optimization_history['trial_number'],
optimization_history['value'],
marker='o',
linestyle='-',
color='skyblue',
alpha=0.4,
label='All Trials'
)
# 繪制最佳點(diǎn)
plt.plot(
best_trial_number,
best_value,
marker='*',
color='darkblue',
markersize=15,
label=f'Best Trial (#{best_trial_number})'
)
plt.title("Optimization History")
plt.xlabel("Trial Number")
plt.ylabel("MSE")
plt.grid(True)
plt.legend(loc='upper right', bbox_to_anchor=(1, 1), frameon=True)
plt.savefig('1.pdf', format='pdf', bbox_inches='tight')
plt.show()
從優(yōu)化歷史中找到具有最低目標(biāo)值(MSE)的最佳試驗(yàn),并提取其編號(hào)和對(duì)應(yīng)的MSE值。然后,繪制優(yōu)化歷史折線圖,其中所有試驗(yàn)結(jié)果以點(diǎn)的形式呈現(xiàn),最佳試驗(yàn)點(diǎn)以星號(hào)標(biāo)出,使得用戶能夠清晰地看到整個(gè)調(diào)參過(guò)程中的性能變化
from optuna.importance import get_param_importances
# 獲取超參數(shù)的重要性數(shù)據(jù)
param_importances = get_param_importances(study)
# 將數(shù)據(jù)轉(zhuǎn)換為 DataFrame
Hyperparameter_Importances = pd.DataFrame(list(param_importances.items()), columns=['Parameter', 'Importance'])
Hyperparameter_Importances
使用Optuna的get_param_importances函數(shù)來(lái)計(jì)算超參數(shù)對(duì)優(yōu)化目標(biāo)的重要性,并將其結(jié)果轉(zhuǎn)換為DataFrame便于查看和分析。
# 對(duì)參數(shù)按重要性進(jìn)行排序,便于圖表的展示
Hyperparameter_Importances = Hyperparameter_Importances.sort_values(by='Importance', ascending=False)
# 繪制超參數(shù)重要性條形圖
plt.figure(figsize=(10, 6), dpi=1200)
bars = plt.barh(Hyperparameter_Importances['Parameter'], Hyperparameter_Importances['Importance'], color='skyblue')
plt.gca().invert_yaxis() # 反轉(zhuǎn)Y軸,使重要性最高的參數(shù)在頂部
# 為每個(gè)條形圖顯示數(shù)值
for bar, importance in zip(bars, Hyperparameter_Importances['Importance']):
plt.text(bar.get_width() + 0.01, bar.get_y() + bar.get_height() / 2,
f'{importance:.3f}', va='center')
plt.title("Hyperparameter Importances")
plt.xlabel("Importance")
plt.ylabel("Parameter")
# 設(shè)置x軸范圍
plt.xlim(0, max(Hyperparameter_Importances['Importance']) * 1.1)
plt.savefig('2.pdf', format='pdf', bbox_inches='tight')
plt.show()
對(duì)超參數(shù)的重要性數(shù)據(jù)進(jìn)行排序,然后使用水平條形圖展示每個(gè)超參數(shù)對(duì)模型性能的重要性,確保最重要的參數(shù)位于頂部。代碼還在每個(gè)條形上標(biāo)出數(shù)值,提供了各參數(shù)對(duì)結(jié)果影響的精確度量,結(jié)果圖顯示了gamma和learning_rate是對(duì)模型性能影響最大的兩個(gè)超參數(shù),而max_depth和subsample的影響較小。通過(guò)這種可視化,用戶可以更好地理解哪些超參數(shù)最值得關(guān)注和優(yōu)化
# 提取每次試驗(yàn)的參數(shù)組合和目標(biāo)值
data = {
'trial_number': [],
'value': []
}
# 提取所有參數(shù)名并初始化列
for param_name in study.trials[0].params.keys():
data[param_name] = []
# 遍歷所有試驗(yàn),提取參數(shù)和目標(biāo)值
for trial in study.trials:
data['trial_number'].append(trial.number)
data['value'].append(trial.value)
# 填充每個(gè)參數(shù)的值,如果該試驗(yàn)沒(méi)有設(shè)置某個(gè)參數(shù),則填充為 None
for param_name in data.keys():
if param_name not in ['trial_number', 'value']:
data[param_name].append(trial.params.get(param_name, None))
# 將數(shù)據(jù)轉(zhuǎn)換為 DataFrame
Parameter_Combinations = pd.DataFrame(data)
Parameter_Combinations
從每次試驗(yàn)中提取超參數(shù)組合和目標(biāo)值,將其整理成DataFrame,以便后續(xù)分析不同參數(shù)組合對(duì)目標(biāo)值的影響
from mpl_toolkits.mplot3d import Axes3D
Parameter_Combinations['gamma'] = Parameter_Combinations['gamma'].astype(float)
Parameter_Combinations['learning_rate'] = Parameter_Combinations['learning_rate'].astype(float)
plt.figure(figsize=(10, 8))
# 繪制散點(diǎn)圖,使用 'value' 進(jìn)行顏色編碼
sc = plt.scatter(
Parameter_Combinations['gamma'],
Parameter_Combinations['learning_rate'],
c=Parameter_Combinations['value'],
cmap='viridis',
s=50, # 設(shè)置散點(diǎn)大小
alpha=0.7 # 設(shè)置透明度
)
cbar = plt.colorbar(sc, format='%.3f')
cbar.set_label('Objective Value')
plt.xlabel("gamma")
plt.ylabel("learning_rate")
plt.title("2D Plot of gamma and learning_rate vs Objective Value")
plt.savefig('3.pdf', format='pdf', bbox_inches='tight')
plt.show()
繪制gamma和learning_rate兩個(gè)超參數(shù)對(duì)目標(biāo)值(Objective Value)的影響【排名影響前二參數(shù)】,通過(guò)散點(diǎn)圖展示每組參數(shù)組合的效果,并使用顏色編碼表示目標(biāo)值大小。結(jié)果顯示了不同參數(shù)組合下的目標(biāo)值分布,顏色越淺表示目標(biāo)值越低,從而幫助識(shí)別表現(xiàn)較優(yōu)的參數(shù)區(qū)域
繪制colsample_bytree、gamma和learning_rate三個(gè)超參數(shù)組合對(duì)目標(biāo)值(Objective MSE)的三維散點(diǎn)圖【排名影響前三參數(shù)】,使用顏色編碼目標(biāo)值大小。結(jié)果圖展示了不同參數(shù)組合的目標(biāo)值分布,顏色越淺表示目標(biāo)值越低,便于識(shí)別在多維參數(shù)空間中表現(xiàn)最佳的區(qū)域
文章轉(zhuǎn)自微信公眾號(hào)@Python機(jī)器學(xué)習(xí)AI
對(duì)比大模型API的內(nèi)容創(chuàng)意新穎性、情感共鳴力、商業(yè)轉(zhuǎn)化潛力
一鍵對(duì)比試用API 限時(shí)免費(fèi)