小白python最小二乘法优化

#Définition des variables k0,ub,lb
k0 = np.array([15,50000,50,50,50,50],float)
lb = np.array([0,1000,0,0,0,0],float)
ub = np.array([1e9,3e6,1e5,1e4,1e5,1e4],float)

Graphflag=0


#k=[999999999.999467,55437.7219287506,5.31799014972964e-14,46.3319342084744,29.2685718745552,27.6259972700392]
#test
Graphflag = 1
a = ObjFun(k, Expdata, Graphflag)

我想做的事是这样的:Graphflag=0的时候,给一组k0初值,通过最小二乘法minimize误差err得到优化的k,然后在Graphflag=1的时候,把得到的k用到objfun里画图。现在的问题是我不知道在python里怎么进行最小二乘法优化得到k(之前在matlab上用lsqnonlin的。。。。),求大佬指导。

附函数程序(大部分都是实验数据处理2333):

def ObjFun(k,Expdata,Graphflag):
    Nexp = 6
    err = []
    stockage = []
    C_comp=[]
    x_comp=[]
    for i in range(0,Nexp,1):
        n = Expdata["Conc"][i].T
        tspan = Expdata["t"]
        # tspan_vec = np.linspace(tspan[0], tspan[-1],)
        # print(tspan_vec)
        w_cata = Expdata["w_cata"][i]
        T = Expdata["T"][i] + 273
        ntot = sum(n[0,:])
        C = (n/ntot) #Définition de la matrice activité par expérience
        size_C  = C.shape 
        C_comp.append(C)
 
        x0 = C[0,:] #Activité initiale

        solution = solve_ivp(Evalfun,[tspan[0],tspan[-1]],x0,method ='RK45',t_eval=tspan,dense_output=False,events = None,vectorized = True,args = (k,T,w_cata))
        x = solution["y"]
        x_comp.append(x)
        # print(x_comp)
        t = solution["t"]
        # print(C)
        # print(x)
        # print("x = ",x.T.shape,"C= ",C.shape)
        # print(np.array(C))
        if Graphflag==1:        
            stockage.append(x)
            ##première figure 
            plt.title('ASI0'+str(i+4)+';m-cata='+str(w_cata)+';T='+str(T-273)+';ratio ac/BuOH='+str(C[0,1]/C[0,0]*75.12/76.05))        
            plt.plot(t,x[0])  
            plt.scatter(t,C[:,0]) 
            plt.plot(t,x[1])  
            plt.scatter(t,C[:,1]) 
            plt.plot(t,x[2]) 
            plt.scatter(t,C[:,2]) 
            plt.show()
            
            #2eme figure 
            z=[0,1]           
            z1=[0,1+1*0.15] 
            z2=[0,1-1*0.15] 
            plt.title('ASI0'+str(i+4)+';m-cata='+str(w_cata)+';T='+str(T-273)+';ratio ac/BuOH='+str(C[0,1]/C[0,0]*75.12/76.05))
            plt.plot(z,z,'b') 
            plt.plot(z,z1,'r--') 
            plt.plot(z,z2,'y--') 
            plt.scatter(x.T,C)        
            plt.xlabel('x modele') 
            plt.ylabel('experimentale') 
            plt.xlim(0,1) 
            plt.ylim(0,1) 
            plt.show()
        else: 
             
            err=abs(C_comp-x_comp)
    return 

 

参考一下:https://blog.csdn.net/z2539329562/article/details/89312941

如果对你有帮助,可以点击我这个回答右上方的【采纳】按钮,给我个采纳吗,谢谢

您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632