简体   繁体   中英

scipy minimize TypeError: unsupported operand type(s) for -: 'tuple' and 'tuple'

I'm playing a bit with some SIR models, and trying to minimize a function with scipy.

def SIR_Model(parametros, valores_iniciais, valores_reais):

    Dias = len(valores_reais)-1
    Dia=[0]

    N=valores_iniciais[0]

    S=[]
    E=[]
    A=[]
    I=[]
    H=[]
    R=[]

    S.append(valores_iniciais[1])
    E.append(valores_iniciais[2])
    A.append(valores_iniciais[3])
    I.append(valores_iniciais[4])
    H.append(valores_iniciais[5])
    R.append(valores_iniciais[6])


    sigma=valores_iniciais[7]
    lambda_model=valores_iniciais[8]
    k1=valores_iniciais[9]
    k2=valores_iniciais[10]
    delta=valores_iniciais[11]

    beta1=parametros[0]
    beta2=parametros[1]
    beta3=parametros[2]
    gamma=parametros[3]

    for i in range(0,Dias):
        Dia.append(i+1)
        S.append(S[i]*(1-beta1*A[i]/N-beta2*I[i]/N-beta3*H[i]/N))
        E.append(E[i]*(1-sigma)+S[i]/N*(beta1*A[i]+beta2*I[i]+beta3*H[i]))
        A.append(A[i]*(1-k1)+(1-gamma)*sigma*E[i])
        I.append(sigma*gamma*E[i]-lambda_model*I[i])
        H.append(H[i]*(1-k2-delta)+lambda_model*I[i])
        R.append(R[i]+k1*A[i]+(k2+delta)*H[i])

    df_model=pd.DataFrame(np.column_stack([S, E, A, I, H, R, Dia, valores_reais]), columns=['Susceptible','Exposed','Asymptomatic','Infected','Hospitalized','Removed','Dia', 'Infected Portugal'])

    RMSE = ((df_model["Infected"] - df_model["Infected Portugal"]) ** 2).mean() ** .5
    R_0 = ((1-gamma)*beta1*S[0])/(k1*N) + (gamma*beta2*S[0])/(lambda_model*N) + (gamma*beta3*S[0])/((k2+delta)*N)

    return RMSE, df_model, R_0

Calling the function with some values, it works fine eg RMSE_Model, df_Model, R_0_Model = SIR_Model(parametros_x0, valores_inicio, infected_portugal)

When I try to minimize I get the error: TypeError: unsupported operand type(s) for -: 'tuple' and 'tuple'

from scipy.optimize import minimize
res = minimize(SIR_Model,x0=parametros, args=(valores_inicio, infected_portugal))

May you help pls? Thanks

The function SIR_model returns a tuple but scipy.optimize.minimize expects the function to return a scalar.

The description in the docs says:

Minimization of scalar function of one or more variables.

A function that return a tuple could probably work on the condition that the tuples can be ordered with comparison. In your case, the tuple contains objects that can't be ordered.

You may want to wrap the SIR_Model function so that it returns a scalar and apply the minimize function to the wrapper.

def wrapper(parametros, valores_iniciais, valores_reais):
    res = SIR_Model(parametros, valores_iniciais, valores_reais)
    return res[0]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM