Python训练营-Day11

DAY 11 常见的调参方式

超参数调整专题1

知识点回顾

1.  网格搜索

2.  随机搜索(简单介绍,非重点 实战中很少用到,可以不了解)

3.  贝叶斯优化(2种实现逻辑,以及如何避开必须用交叉验证的问题)

4.  time库的计时模块,方便后人查看代码运行时长

#LightGBM-网格优化
print("\n--- 3. 网格搜索优化LightGBM (训练集 -> 测试集) ---")
import lightgbm as lgb
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
import time
 
param_grid = {
    'max_depth': [10, 20, 30],  # 树的最大深度
    'num_leaves': [31, 50, 100],  # 叶子节点数
    'subsample': [0.6, 0.8, 1.0],  # 随机采样比例
}
grid_search = GridSearchCV(estimator=lgb.LGBMClassifier(random_state=42), param_grid=param_grid, cv=5, n_jobs=-1, scoring='accuracy') # 创建网格搜索对象
start_time = time.time() # 记录开始时间
grid_search.fit(X_train, y_train) # 训练模型
end_time = time.time() # 记录结束时间
 
print(f"网格搜索耗时: {end_time - start_time:.4f} 秒")
print("最佳参数: ", grid_search.best_params_) #best_params_属性返回最佳参数组合
best_model = grid_search.best_estimator_ # 获取最佳模型
best_pred = best_model.predict(X_test) # 在测试集上进行预测
print("\n网格搜索优化后的LightGBM 在测试集上的分类报告:")
print(classification_report(y_test, best_pred))
print("网格搜索优化后的LightGBM 在测试集上的混淆矩阵:")
print(confusion_matrix(y_test, best_pred))
#LightGBM-贝叶斯优化
print("\n--- 3. 贝叶斯优化LightGBM (训练集 -> 测试集) ---")
from skopt import BayesSearchCV
from skopt.space import Integer
 
search_space = {
    'max_depth': Integer(10, 30),
    'num_leaves': Integer(31, 100),
    'subsample': (0.6, 1.0),
}
 
bayes_search = BayesSearchCV(
    estimator=lgb.LGBMClassifier(random_state=42),
    search_spaces=search_space,
    n_iter=32,  # 迭代次数,可根据需要调整
    cv=5, # 5折交叉验证,这个参数是必须的,不能设置为1,否则就是在训练集上做预测了
    n_jobs=-1,
    scoring='accuracy'
)
start_time = time.time()
bayes_search.fit(X_train, y_train) # 训练模型
end_time = time.time() # 记录结束时间
print(f"贝叶斯优化耗时: {end_time - start_time:.4f} 秒")
print("最佳参数: ", bayes_search.best_params_)
 
# 使用最佳参数的模型进行预测
best_model = bayes_search.best_estimator_
best_pred = best_model.predict(X_test)
 
print("\n贝叶斯优化后的LightGBM 在测试集上的分类报告:")
print(classification_report(y_test, best_pred))
print("贝叶斯优化后的LightGBM 在测试集上的混淆矩阵:")
print(confusion_matrix(y_test, best_pred))
#KNN-网格优化
print("\n--- 4. 网格搜索优化KNN (训练集 -> 测试集) ---")
from sklearn.neighbors import KNeighborsClassifier
param_grid = {
    'n_neighbors': [3, 5, 7, 9],  # K值
    'weights': ['uniform', 'distance'],  # 权重类型
    'algorithm': ['auto', 'ball_tree', 'kd_tree', 'brute'],  # 算法
}
grid_search = GridSearchCV(estimator=KNeighborsClassifier(), param_grid=param_grid, cv=5, n_jobs=-1, scoring='accuracy') # 创建网格搜索对象
start_time = time.time() # 记录开始时间
grid_search.fit(X_train, y_train) # 训练模型
end_time = time.time() # 记录结束时间
print(f"网格搜索耗时: {end_time - start_time:.4f} 秒")
print("最佳参数: ", grid_search.best_params_) #best_params_属性返回最佳参数组合
best_model = grid_search.best_estimator_ # 获取最佳模型
best_pred = best_model.predict(X_test) # 在测试集上进行预测
print("\n网格搜索优化后的KNN 在测试集上的分类报告:")
print(classification_report(y_test, best_pred))
print("网格搜索优化后的KNN 在测试集上的混淆矩阵:")
print(confusion_matrix(y_test, best_pred))
#KNN-贝叶斯优化
print("\n--- 4. 贝叶斯优化KNN (训练集 -> 测试集) ---")
from skopt import BayesSearchCV
from skopt.space import Integer
from sklearn.neighbors import KNeighborsClassifier
 
search_space = {
    'n_neighbors': Integer(3, 20),
    'weights': ['uniform', 'distance'],
    'algorithm': ['auto', 'ball_tree', 'kd_tree', 'brute']
}
bayes_search = BayesSearchCV(
    estimator=KNeighborsClassifier(),
    search_spaces=search_space,
    n_iter=32,  # 迭代次数,可根据需要调整
    cv=5, # 5折交叉验证,这个参数是必须的,不能设置为1,否则就是在训练集上做预测了
    n_jobs=-1,
    scoring='accuracy'
)
start_time = time.time()
bayes_search.fit(X_train, y_train) # 训练模型
end_time = time.time() # 记录结束时间
print(f"贝叶斯优化耗时: {end_time - start_time:.4f} 秒")
print("最佳参数: ", bayes_search.best_params_)
# 使用最佳参数的模型进行预测
best_model = bayes_search.best_estimator_
best_pred = best_model.predict(X_test)
print("\n贝叶斯优化后的KNN 在测试集上的分类报告:")
print(classification_report(y_test, best_pred))
print("贝叶斯优化后的KNN 在测试集上的混淆矩阵:")
print(confusion_matrix(y_test, best_pred))

@浙大疏锦行

你可能感兴趣的:(Python训练营,python,机器学习,深度学习)