繁体   English   中英

Python中for循环的两种实现有什么区别

[英]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.

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