算法笔记(23)网格搜索及Python代码实现
網格搜索,搜索的是參數,即在指定的參數范圍內,按步長依次調整參數,利用調整的參數訓練學習器,從所有的參數中找到在驗證集上精度最高的參數,這其實是一個訓練和比較的過程。本節介紹三種網格搜索方法:簡單網格搜索、與交叉驗證結合的網格搜索、使用GridSearchCV的網格搜索。
網格搜索方法?
簡單網格搜索
for循環遍歷全部的參數設置,并找出最高分和對應的參數。
X_train, X_test, y_train, y_test=train_test_split(wine.data, wine.target,random_state=38) best_score = 0 for alpha in [0.01,0.1,1.0,10.0]:for max_iter in [100,1000,5000,10000]:lasso = Lasso(alpha=alpha,max_iter=max_iter)lasso.fit(X_train, y_train)score = lasso.score(X_test, y_test)if score > best_score:best_score = scorebest_parameters={'alpha':alpha,'最大迭代次數':max_iter}print("模型最高分為:{:.3f}".format(best_score)) print('最佳參數設置:{}'.format(best_parameters))模型最高分為:0.889
最佳參數設置:{'alpha': 0.01, '最大迭代次數': 100}
與交叉驗證結合的網格搜索
交叉驗證法和網格搜索法結合起來找到模型的最優參數。只用先前拆分好的X_train來進行交叉驗證,以便我們找到最佳參數之后,再用來擬合X_test來看一下模型的得分。
for alpha in [0.01,0.1,1.0,10.0]:for max_iter in [100,1000,5000,10000]:lasso = Lasso(alpha=alpha,max_iter=max_iter)scores = cross_val_score(lasso, X_train, y_train, cv=6)score = np.mean(scores)if score > best_score:best_score = scorebest_parameters={'alpha':alpha, '最大迭代數':max_iter}print("模型最高分為:{:.3f}".format(best_score)) print('最佳參數設置:{}'.format(best_parameters))模型最高分為:0.865
最佳參數設置:{'alpha': 0.01, '最大迭代數': 100}
測試數據集得分:0.819
使用GridSearchCV的網格搜索
GridSearchCV本身就是將交叉驗證和網格搜索封裝在一起。GridSearchCV需要反復建模,所需要的計算時間往往更長。
from sklearn.model_selection import GridSearchCV params = {'alpha':[0.01,0.1,1.0,10.0],'max_iter':[100,1000,5000,10000]} grid_search = GridSearchCV(lasso,params,cv=6) grid_search.fit(X_train, y_train) print('模型最高分:{:.3f}'.format(grid_search.score(X_test, y_test))) print('最優參數:{}'.format(grid_search.best_params_))模型最高分:0.819
最優參數:{'alpha': 0.01, 'max_iter': 100}
交叉驗證最高得分:0.865
分析:GridSearchCV有一個屬性best_score_,這個屬性會存儲模型在交叉驗證中所得的最高分,而不是在測試數據集上的得分。
想要完整代碼的朋友,可toutiao搜索“編程研究坊”關注后s信我,回復“算法筆記23“獲取
總結
以上是生活随笔為你收集整理的算法笔记(23)网格搜索及Python代码实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 网格搜索的原理以及实战以及相关API(G
- 下一篇: python刷课系统教师_让教师只想刷课