如何针对不同数量的变量结构化地编写不同配置的代码

问题描述 投票:0回答:1

我正在使用任何方法校准一堆参数(不重要)。但我选择校准的参数数量会有所不同(从 1 到 4)。如果我想校准 4 个参数,我的代码将如下所示:

def derivative(a,b,c,d,p1,p2,p3,p4):
    
    du = my_func(a,b,c,d,p1*1.1,p2,p3,p4)
    dd = my_func(a,b,c,d,p1*0.9,p2,p3,p4)
    d1 = (du-dd) / (0.2*p1)
    
    du = my_func(a,b,c,d,p1,p2*1.1,p3,p4)
    dd = my_func(a,b,c,d,p1,p2*0.9,p3,p4)
    d2 = (du-dd) / (0.2*p2)
    
    #...
   
    return np.array([d1,d2,d3,d4])

def calibrating(old_params,a,b,c,d,p1,p2,p3,p4):
    # some for loop, looping and updating the parameters 
    J = derivative(a,b,c,d,old_params[0],old_params[1],old_params[2],old_params[3])

    new_params = old_params + J


initial_guess = np.array([p1,p2,p3,p4])

calibrated_params =  calibrating(initial_guesses,a,b,c,d,0,0,0,0)

但有时我希望修复

p1
p2
。我的代码看起来像这样:

def derivative(a,b,c,d,p1,p2,p3,p4):
    # d3 and d4 variable names aren't important. 
    du = my_func(a,b,c,d,p1,p2,p3*1.1,p4)
    dd = my_func(a,b,c,d,p1,p2,p3*0.9,p4)
    d3 = (du-dd) / (0.2*p3)
    
    du = my_func(a,b,c,d,p1,p2,p3,p4*1.1)
    dd = my_func(a,b,c,d,p1,p2,p3,p4*0.9)
    d4 = (du-dd) / (0.2*p4)
    
    return np.array([d3,d4])

def calibrating(old_params,a,b,c,d,p1,p2,p3,p4):
    # some for loop, looping and updating the parameters 
    J = derivative(a,b,c,d,p1,p2,old_params[2],old_params[3])
    new_params = old_params + J

p1=2
p2=3
initial_guess = np.array([p3,p4])

calibrated_params =  calibrating(initial_guesses,a,b,c,d,p1,p2,0,0)

有没有一种方法可以干净地编码,而无需对每个可能的配置进行编码?我最初的想法是将固定参数放入initial_guess数组中,如下所示,但仍然需要许多不同的衍生配置。

def derivative(a,b,c,d,old_params):
    # d3 and d4 variable names aren't important. 
    du = my_func(a,b,c,d,old_params[0],old_params[1],old_params[2]*1.1,old_params[3])
    dd = my_func(a,b,c,d,p1,p2,old_params[2]*0.9,old_params[3])
    d3 = (du-dd) / (0.2*old_params[2])
    
    du = my_func(a,b,c,d,old_params[0],old_params[1],old_params[2],old_params[3]*1.1)
    dd = my_func(a,b,c,d,old_params[0],old_params[1],old_params[2],old_params[3]*0.9)
    d4 = (du-dd) / (0.2*old_params[3])
    
    return np.array([d3,d4])

def calibrating(old_params,a,b,c,d):
    # some for loop, looping and updating the parameters 
    J = derivative(a,b,c,d,old_params)
    new_params = old_params + J

p1=2
p2=3
initial_guess = np.array([p1,p2,p3,p4])

calibrated_params =  calibrating(initial_guesses,a,b,c,d)
python performance data-structures coding-style structure
1个回答
0
投票

定义导数(a,b,c,d,p1,p2,p3,p4):

du = my_func(a,b,c,d,p1*1.1,p2,p3,p4)
dd = my_func(a,b,c,d,p1*0.9,p2,p3,p4)
d1 = (du-dd) / (0.2*p1)

du = my_func(a,b,c,d,p1,p2*1.1,p3,p4)
dd = my_func(a,b,c,d,p1,p2*0.9,p3,p4)
d2 = (du-dd) / (0.2*p2)

#...

return np.array([d1,d2,d3,d4])

def 校准(old_params,a,b,c,d,p1,p2,p3,p4): # 一些for循环,循环并更新参数 J = 导数(a,b,c,d,old_params[0],old_params[1],old_params[2],old_params[3])

new_params = old_params + J

initial_guess = np.array([p1,p2,p3,p4])

calibated_params = 校准(初始猜测,a,b,c,d,0,0,0,0)

© www.soinside.com 2019 - 2024. All rights reserved.