算法笔记(23)网格搜索及Python代码实现
網(wǎng)格搜索,搜索的是參數(shù),即在指定的參數(shù)范圍內(nèi),按步長(zhǎng)依次調(diào)整參數(shù),利用調(diào)整的參數(shù)訓(xùn)練學(xué)習(xí)器,從所有的參數(shù)中找到在驗(yàn)證集上精度最高的參數(shù),這其實(shí)是一個(gè)訓(xùn)練和比較的過程。本節(jié)介紹三種網(wǎng)格搜索方法:簡(jiǎn)單網(wǎng)格搜索、與交叉驗(yàn)證結(jié)合的網(wǎng)格搜索、使用GridSearchCV的網(wǎng)格搜索。
網(wǎng)格搜索方法?
簡(jiǎn)單網(wǎng)格搜索
for循環(huán)遍歷全部的參數(shù)設(shè)置,并找出最高分和對(duì)應(yīng)的參數(shù)。
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,'最大迭代次數(shù)':max_iter}print("模型最高分為:{:.3f}".format(best_score)) print('最佳參數(shù)設(shè)置:{}'.format(best_parameters))模型最高分為:0.889
最佳參數(shù)設(shè)置:{'alpha': 0.01, '最大迭代次數(shù)': 100}
與交叉驗(yàn)證結(jié)合的網(wǎng)格搜索
交叉驗(yàn)證法和網(wǎng)格搜索法結(jié)合起來找到模型的最優(yōu)參數(shù)。只用先前拆分好的X_train來進(jìn)行交叉驗(yàn)證,以便我們找到最佳參數(shù)之后,再用來擬合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, '最大迭代數(shù)':max_iter}print("模型最高分為:{:.3f}".format(best_score)) print('最佳參數(shù)設(shè)置:{}'.format(best_parameters))模型最高分為:0.865
最佳參數(shù)設(shè)置:{'alpha': 0.01, '最大迭代數(shù)': 100}
測(cè)試數(shù)據(jù)集得分:0.819
使用GridSearchCV的網(wǎng)格搜索
GridSearchCV本身就是將交叉驗(yàn)證和網(wǎng)格搜索封裝在一起。GridSearchCV需要反復(fù)建模,所需要的計(jì)算時(shí)間往往更長(zhǎng)。
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('最優(yōu)參數(shù):{}'.format(grid_search.best_params_))模型最高分:0.819
最優(yōu)參數(shù):{'alpha': 0.01, 'max_iter': 100}
交叉驗(yàn)證最高得分:0.865
分析:GridSearchCV有一個(gè)屬性best_score_,這個(gè)屬性會(huì)存儲(chǔ)模型在交叉驗(yàn)證中所得的最高分,而不是在測(cè)試數(shù)據(jù)集上的得分。
想要完整代碼的朋友,可toutiao搜索“編程研究坊”關(guān)注后s信我,回復(fù)“算法筆記23“獲取
總結(jié)
以上是生活随笔為你收集整理的算法笔记(23)网格搜索及Python代码实现的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 网格搜索的原理以及实战以及相关API(G
- 下一篇: python刷课系统教师_让教师只想刷课