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-10-31-公眾號(hào)Python機(jī)器學(xué)習(xí)AI—regression.xlsx')
from sklearn.model_selection import train_test_split, KFold

X = df.drop(['待預(yù)測(cè)變量Y'],axis=1)
y = df['待預(yù)測(cè)變量Y']

# 劃分訓(xùn)練集和測(cè)試集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

from hyperopt import fmin, tpe, hp
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error

# 定義超參數(shù)搜索空間
parameter_space_rf = {
'n_estimators': hp.choice('n_estimators', [50, 100, 200, 300]), # 決策樹(shù)數(shù)量
'max_depth': hp.choice('max_depth', [5, 10, 20, None]), # 樹(shù)的最大深度
'min_samples_split': hp.uniform('min_samples_split', 0.01, 0.5), # 分裂所需最小樣本比例
'min_samples_leaf': hp.uniform('min_samples_leaf', 0.01, 0.5) # 葉節(jié)點(diǎn)最小樣本比例
}

# 定義目標(biāo)函數(shù)
def objective(params):
# 使用超參數(shù)創(chuàng)建隨機(jī)森林回歸模型
model = RandomForestRegressor(
n_estimators=params['n_estimators'],
max_depth=params['max_depth'],
min_samples_split=params['min_samples_split'],
min_samples_leaf=params['min_samples_leaf'],
random_state=42
)

# 在訓(xùn)練集上擬合模型
model.fit(X_train, y_train)

# 在測(cè)試集上預(yù)測(cè)
y_pred = model.predict(X_test)

# 計(jì)算均方誤差(MSE)
mse = mean_squared_error(y_test, y_pred)

# 返回MSE,Hyperopt會(huì)最小化該目標(biāo)值
return mse

# 運(yùn)行超參數(shù)優(yōu)化
best_params = fmin(
fn=objective, # 優(yōu)化的目標(biāo)函數(shù)
space=parameter_space_rf, # 搜索空間
algo=tpe.suggest, # 貝葉斯優(yōu)化算法
max_evals=100 # 最大評(píng)估次數(shù)
)

# 顯示最優(yōu)超參數(shù)組合
print("Best hyperparameters:", best_params)

# 使用最佳超參數(shù)組合重新訓(xùn)練模型
best_model_regression = RandomForestRegressor(
n_estimators=[50, 100, 200, 300][best_params['n_estimators']],
max_depth=[5, 10, 20, None][best_params['max_depth']],
min_samples_split=best_params['min_samples_split'],
min_samples_leaf=best_params['min_samples_leaf'],
random_state=42
)

# 在訓(xùn)練集上訓(xùn)練模型
best_model_regression.fit(X_train, y_train)

利用貝葉斯優(yōu)化(通過(guò)hyperopt庫(kù))來(lái)自動(dòng)調(diào)整隨機(jī)森林回歸模型的超參數(shù),以最小化測(cè)試集上的均方誤差(MSE)。首先,定義了一個(gè)超參數(shù)空間,包括決策樹(shù)數(shù)量、最大深度、最小分裂樣本比例和最小葉子樣本比例,接著,定義目標(biāo)函數(shù)以構(gòu)建并評(píng)估隨機(jī)森林模型,將模型在測(cè)試集上的MSE作為優(yōu)化目標(biāo),通過(guò)fmin函數(shù)使用貝葉斯優(yōu)化搜索最佳參數(shù)組合,并用該組合重新訓(xùn)練最終的隨機(jī)森林模型,從而獲得更優(yōu)的預(yù)測(cè)性能

評(píng)估模型性能:訓(xùn)練集與測(cè)試集的回歸指標(biāo)對(duì)比

from sklearn import metrics

# 預(yù)測(cè)
y_pred_train = best_model_regression.predict(X_train)
y_pred_test = best_model_regression.predict(X_test)

y_pred_train_list = y_pred_train.tolist()
y_pred_test_list = y_pred_test.tolist()

# 計(jì)算訓(xùn)練集的指標(biāo)
mse_train = metrics.mean_squared_error(y_train, y_pred_train_list)
rmse_train = np.sqrt(mse_train)
mae_train = metrics.mean_absolute_error(y_train, y_pred_train_list)
r2_train = metrics.r2_score(y_train, y_pred_train_list)

# 計(jì)算測(cè)試集的指標(biāo)
mse_test = metrics.mean_squared_error(y_test, y_pred_test_list)
rmse_test = np.sqrt(mse_test)
mae_test = metrics.mean_absolute_error(y_test, y_pred_test_list)
r2_test = metrics.r2_score(y_test, y_pred_test_list)

print("訓(xùn)練集評(píng)價(jià)指標(biāo):")
print("均方誤差 (MSE):", mse_train)
print("均方根誤差 (RMSE):", rmse_train)
print("平均絕對(duì)誤差 (MAE):", mae_train)
print("擬合優(yōu)度 (R-squared):", r2_train)

print("\n測(cè)試集評(píng)價(jià)指標(biāo):")
print("均方誤差 (MSE):", mse_test)
print("均方根誤差 (RMSE):", rmse_test)
print("平均絕對(duì)誤差 (MAE):", mae_test)
print("擬合優(yōu)度 (R-squared):", r2_test)

計(jì)算并輸出隨機(jī)森林回歸模型在訓(xùn)練集和測(cè)試集上的性能指標(biāo),包括均方誤差(MSE)、均方根誤差(RMSE)、平均絕對(duì)誤差(MAE)和擬合優(yōu)度(R-squared),以評(píng)估模型在訓(xùn)練集和測(cè)試集上的預(yù)測(cè)準(zhǔn)確度和擬合效果,從而幫助判斷模型的泛化能力

模型預(yù)測(cè)可視化

利用散點(diǎn)圖和回歸線(xiàn),直觀展示隨機(jī)森林模型在訓(xùn)練集和測(cè)試集上的預(yù)測(cè)表現(xiàn),圖中每個(gè)點(diǎn)代表真實(shí)值和預(yù)測(cè)值的配對(duì)關(guān)系,越接近對(duì)角線(xiàn)(即x=y線(xiàn))的點(diǎn)表示預(yù)測(cè)越準(zhǔn)確,通過(guò)不同顏色區(qū)分訓(xùn)練集和測(cè)試集,邊緣的柱狀圖則顯示了數(shù)據(jù)分布情況,此外,右下角標(biāo)注了訓(xùn)練集和測(cè)試集的R^2(擬合優(yōu)度),左上角注明模型名稱(chēng),幫助更全面地評(píng)估模型的預(yù)測(cè)效果與泛化能力,為模型的有效性提供了直觀的支持。

分類(lèi)模型

利用貝葉斯優(yōu)化提升隨機(jī)森林(分類(lèi))模型性能

import pandas as pd
import numpy as np
from hyperopt import fmin, tpe, hp
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score

# 讀取數(shù)據(jù)
df = pd.read_excel('2024-10-31-公眾號(hào)Python機(jī)器學(xué)習(xí)AI—class.xlsx')

# 劃分特征和目標(biāo)變量
X = df.drop(['目標(biāo)'], axis=1)
y = df['目標(biāo)']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42, stratify=df['目標(biāo)'])

# 定義超參數(shù)空間
parameter_space_rf = {
'n_estimators': hp.choice('n_estimators', [50, 100, 200, 300]), # 決策樹(shù)數(shù)量
'max_depth': hp.choice('max_depth', [5, 10, 20, None]), # 最大深度
'min_samples_split': hp.uniform('min_samples_split', 0.01, 0.5), # 分裂所需最小樣本比例
'min_samples_leaf': hp.uniform('min_samples_leaf', 0.01, 0.5) # 葉節(jié)點(diǎn)最小樣本比例
}

# 定義目標(biāo)函數(shù)
def objective(params):
# 初始化模型并傳入超參數(shù)
model = RandomForestClassifier(
n_estimators=params['n_estimators'],
max_depth=params['max_depth'],
min_samples_split=params['min_samples_split'],
min_samples_leaf=params['min_samples_leaf'],
random_state=42
)

# 模型擬合
model.fit(X_train, y_train)

# 測(cè)試集上的預(yù)測(cè)
y_pred = model.predict(X_test)

# 計(jì)算準(zhǔn)確率
accuracy = accuracy_score(y_test, y_pred)

# 返回負(fù)的準(zhǔn)確率(因?yàn)镠yperopt默認(rèn)最小化目標(biāo)函數(shù))
return -accuracy

# 運(yùn)行貝葉斯優(yōu)化
best_params = fmin(
fn=objective, # 目標(biāo)函數(shù)
space=parameter_space_rf, # 搜索空間
algo=tpe.suggest, # 貝葉斯優(yōu)化算法
max_evals=100 # 最大評(píng)估次數(shù)
)

# 顯示最優(yōu)參數(shù)
print("Best hyperparameters:", best_params)

# 使用最佳參數(shù)創(chuàng)建最終模型
best_model_class = RandomForestClassifier(
n_estimators=[50, 100, 200, 300][best_params['n_estimators']],
max_depth=[5, 10, 20, None][best_params['max_depth']],
min_samples_split=best_params['min_samples_split'],
min_samples_leaf=best_params['min_samples_leaf'],
random_state=42
)

# 在訓(xùn)練集上擬合模型
best_model_class.fit(X_train, y_train)

通過(guò)貝葉斯優(yōu)化(使用hyperopt庫(kù))為隨機(jī)森林分類(lèi)模型選擇最佳超參數(shù)組合,以最大化在測(cè)試集上的準(zhǔn)確率,首先將數(shù)據(jù)集劃分為訓(xùn)練集和測(cè)試集,并定義隨機(jī)森林的超參數(shù)空間,包括決策樹(shù)數(shù)量、最大深度、最小分裂樣本比例和最小葉節(jié)點(diǎn)樣本比例,然后使用目標(biāo)函數(shù)創(chuàng)建和評(píng)估模型,以測(cè)試集準(zhǔn)確率的負(fù)值作為優(yōu)化目標(biāo)(因?yàn)閔yperopt最小化目標(biāo)值),通過(guò)100次評(píng)估后,代碼選出最佳超參數(shù)組合,并用其重新訓(xùn)練隨機(jī)森林模型,從而獲得更優(yōu)的分類(lèi)性能

模型性能評(píng)估:多維度分類(lèi)指標(biāo)分析

from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, roc_auc_score, classification_report
# 計(jì)算各項(xiàng)指標(biāo)
accuracy = accuracy_score(y_test, y_pred)
precision = precision_score(y_test, y_pred)
recall = recall_score(y_test, y_pred)
f1 = f1_score(y_test, y_pred)
# 如果是二分類(lèi)且有預(yù)測(cè)概率值
try:
y_pred_proba = best_model_class.predict_proba(X_test)[:, 1] # 僅適用于二分類(lèi)
auc = roc_auc_score(y_test, y_pred_proba)
except AttributeError:
auc = None # 對(duì)于多分類(lèi)或無(wú) predict_proba 時(shí)不適用
metrics_df = pd.DataFrame({
'Metric': [ 'AUC', 'Precision', 'Recall', 'F1 Score','Accuracy'],
'Value': [auc, precision, recall, f1, accuracy]
})
metrics_df

計(jì)算隨機(jī)森林分類(lèi)模型在測(cè)試集上的多個(gè)評(píng)估指標(biāo),包括準(zhǔn)確率(accuracy)、精確率(precision)、召回率(recall)、F1分?jǐn)?shù)(F1 Score)和AUC(僅適用于二分類(lèi)),這些指標(biāo)各自反映模型不同方面的性能:準(zhǔn)確率表示整體預(yù)測(cè)的準(zhǔn)確程度,精確率關(guān)注正類(lèi)預(yù)測(cè)的準(zhǔn)確性,召回率衡量模型找到所有正類(lèi)的能力,F(xiàn)1分?jǐn)?shù)則平衡了精確率和召回率的權(quán)重。AUC則進(jìn)一步評(píng)估了模型在不同閾值下區(qū)分正負(fù)類(lèi)的能力。因此,使用多個(gè)指標(biāo)能夠更全面地了解模型的表現(xiàn),從而幫助我們避免因單一指標(biāo)誤導(dǎo)而造成的模型優(yōu)化偏差.

模型預(yù)測(cè)可視化

繪制模型各評(píng)估指標(biāo)的雷達(dá)圖,將不同性能指標(biāo)如準(zhǔn)確率、精確率、召回率等在極坐標(biāo)上可視化,方便直觀對(duì)比模型在多個(gè)維度上的表現(xiàn),從而幫助識(shí)別模型的優(yōu)勢(shì)和改進(jìn)方向。

文章轉(zhuǎn)自微信公眾號(hào)@Python機(jī)器學(xué)習(xí)AI

上一篇:

復(fù)現(xiàn)Nature圖表——基于PCA降維與模型預(yù)測(cè)概率的分類(lèi)效果可視化

下一篇:

K折交叉驗(yàn)證結(jié)合RFE與隨機(jī)森林:特征選擇全過(guò)程可視化
#你可能也喜歡這些API文章!

我們有何不同?

API服務(wù)商零注冊(cè)

多API并行試用

數(shù)據(jù)驅(qū)動(dòng)選型,提升決策效率

查看全部API→
??

熱門(mén)場(chǎng)景實(shí)測(cè),選對(duì)API

#AI文本生成大模型API

對(duì)比大模型API的內(nèi)容創(chuàng)意新穎性、情感共鳴力、商業(yè)轉(zhuǎn)化潛力

25個(gè)渠道
一鍵對(duì)比試用API 限時(shí)免費(fèi)

#AI深度推理大模型API

對(duì)比大模型API的邏輯推理準(zhǔn)確性、分析深度、可視化建議合理性

10個(gè)渠道
一鍵對(duì)比試用API 限時(shí)免費(fèi)