简体   繁体   中英

What are the differences between the two implementation of for loops in Python

So I have two different implementations of what I thought would lead to the same execution -

Implementation 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)]

Implementation 2 (My implementation):

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)]

I thought they should lead to the same results, but when I at a later stage call my plotting function - implementation 1 runs properly, implementation 2 gives the following error: ValueError: x and y must have same first dimension, but have shapes (50,) and (2500,)

I have added my plotting function below -

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__)

I realized I missed appending to the list - so the correct version of implementation 2 should be -

 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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM