[英]What are the differences between the two implementation of for loops in Python
所以我有兩種不同的實現,我認為會導致相同的執行 -
實施1:
grid_searches = [GridSearchCV(m,grid,n_jobs=-1, cv = 3, return_train_score=True).fit(X,y) for m, grid in zip(models,params)]
實施2(我的實施):
grid_searches = []
for m, grid in zip(models,params):
grid_searches =[GridSearchCV(m,grid,n_jobs=-1, cv = 3, return_train_score=True).fit(X,y)]
我認為它們應該導致相同的結果,但是當我在稍后階段調用我的繪圖 function - 實施 1 正常運行時,實施 2 給出以下錯誤:ValueError:x 和 y 必須具有相同的第一維,但具有形狀(50 ,) 和 (2500,)
我在下面添加了我的繪圖 function -
fig, axes = plt.subplots(nrows=1, ncols=4,figsize = (15,5))
for grid_search, hyper_para, ax in zip(grid_searches[0:3],['alpha','alpha','n_neighbors','l1_ratio/alpha'], axes):
grid_plot(grid_search, hyper_para, ax)
def grid_plot(grid_search, param_name, axes):
m_test_score = grid_search.cv_results\_\["mean_test_score"\]
m_train_score = grid_search.cv_results\_\["mean_train_score"\]
ax.plot(grid_search.param_grid\[param_name\], m_train_score, marker = '.', label = 'Train score')
ax.plot(grid_search.param_grid\[param_name\], m_test_score, marker = '.', label = 'Test score')
ax.set_xscale('log')
ax.set_xlabel(hyper_para)
ax.set_ylabel('Score')
ax.legend(loc='lower left')
ax.set_title(grid_search.best_estimator\_.__class__.__name__)
我意識到我錯過了附加到列表的內容——所以正確的實現 2 版本應該是——
for m, grid in zip(models, params): grid_searches.append(GridSearchCV(m, grid, n_jobs = -1, cv = 3, return_train_score = True).fit(X, y))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.