【问题标题】:Recursive alternative to nested for loop嵌套 for 循环的递归替代方案
【发布时间】:2020-03-09 16:23:21
【问题描述】:

我有 4 个不同的 sklearn 回归器,我想使用每个预测的百分比来构建我的最终预测。

我的想法是遍历每个可能的版本并使用每个预测的百分比作为我的答案来计算 RMSE,即

reg1.predict(X_test) * 0.2  + reg2.predict(X_test) * 0.3 * reg3.predict(X_test) * 0.3  * reg4.predict(X_test) * 0.2  

我目前有以下内容,但我知道有一种更简洁的方法,如果需要,我还可以轻松添加更多回归量......但我无法理解它?我很确定我需要一个递归函数?但也许我错了?

欢迎任何想法/帮助?

step = 0.05
for x in np.arange(0,1,step):
    for y in np.arange(0,1,step):
        for z in np.arange(0,1,step):
            for p in np.arange(0,1,step):
                if round(x,2)+round(y,2)+round(z,2)+round(p,2) == 1:
                    print(f"x = {round(x,2)} y = {round(y,2)} z = {round(z,2)} p = {round(p,2)}")
                    ## RMSE calculation code goes, if best store X,Y,Z,P

【问题讨论】:

  • 与其依赖四舍五入的值总和为 1,不如检查未四舍五入的值的总和是否落在足够小的区间内,例如 (0.99, 1.01)。

标签: python loops recursion scikit-learn nested


【解决方案1】:

我想你想要一个笛卡尔积,对吧?所以你可以像这样使用itertools.product

import itertools

step = 0.05

configs = itertools.product(
    np.arange(0, 1, step),
    np.arange(0, 1, step),
    np.arange(0, 1, step),
    np.arange(0, 1, step),
)

for x, y, z, p in configs:
    if round(x, 2) + round(y, 2) + round(z, 2) + round(p, 2) == 1:
        print(f"x = {round(x,2)} y = {round(y,2)} z = {round(z,2)} p = {round(p,2)}")
        ## RMSE calculation code goes, if best store X,Y,Z,P

【讨论】:

    【解决方案2】:

    你不需要递归本身;您对四个系列中的产品感兴趣。

    from itertools import product
    
    for x, y, z, p in product(np.arange(0,1,step), repeat=4):
        ...
    

    【讨论】:

    • ..., repeat=...?施威特。不知道有没有
    【解决方案3】:

    您可以使用递归函数,但可以尝试itertools.product

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-25
      • 2020-01-15
      • 1970-01-01
      • 2019-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-25
      相关资源
      最近更新 更多