从最小化中排除一些参数

2024-07-04 08:10:27 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我有一个函数func(x1,x2,x3),我可以使用最小化函数scipy.optimize.minimizex3从优化过程中排除,其中x3定义为numpy array。 在这种情况下,我如何定义参数?。我应该得到一个数组,其中包含每个x3值的最小值func

例如:

def func(thet1,phai1,thet2,phai2,c2):
    
    RhoABC = np.array([[1,0,thet1,0,0,0,0,c1],[0,1,0,0,phai2,0,c2,0],[0,0,1,0,0,c2,thet2,0],[0,0,0,1,c2,0,0,0],[0,phai1,0,c2,1,0,0,0],[0,0,c2,0,0,1,0,thet2],[0,c2,0,0,0,0,1,0],[c1,0,0,phai1,0,0,0,1]])   
    w, v = np.linalg.eig(RhoABC)  
    return w[1] 

我想最小化它,其中c2 = linspace(-1,1,10)和角度属于(0,2pi)


Tags: 函数定义nparrayfuncx1x2c2
2条回答

也许你可以用这样的东西:

def func(thet1,phai1,thet2,phai2,*args, c2 = []):
#considering c2 to be x3 in the above post
    
    RhoABC = np.array([[1,0,thet1,0,0,0,0,c1],[0,1,0,0,phai2,0,c2,0],[0,0,1,0,0,c2,thet2,0],[0,0,0,1,c2,0,0,0],[0,phai1,0,c2,1,0,0,0],[0,0,c2,0,0,1,0,thet2],[0,c2,0,0,0,0,1,0],[c1,0,0,phai1,0,0,0,1]])   
    w, v = np.linalg.eig(RhoABC)  
    return w[1] 

然后,当您调用该函数时:

retVal = func(thet1,phai1,thet2,phai2, c2=c2)

#you have to specify c2 first and then equate it to the value since this is an optional argument.

作为jimmie答案的替代方法,您可以使用lambda函数和解包运算符*

minimize(lambda x: func(*x, linspace(-1,1,10)), x0=x0, ...)

将使用给定的c2=linspace(-1,1,10)最小化变量thet1,phai1,thet2,phai2的函数func

相关问题 更多 >

    热门问题