簡體   English   中英

嵌套 for 循環的遞歸替代方案

[英]Recursive alternative to nested for loop

我有 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  

我目前有以下內容,但我知道有一種更清潔的方法可以做到這一點,如果需要,我還可以輕松添加更多回歸量......但我無法理解它? 我很確定我需要遞歸 function? 但也許我錯了?

歡迎任何想法/幫助?

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

您本身不需要遞歸; 您對四個系列的產品感興趣。

from itertools import product

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

您可以使用遞歸 function 但也許嘗試itertools.product

我想你想要一個笛卡爾積,對吧? 所以你可以像這樣使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM