I am trying to constrain multi-variable non-linear regression using gekko. I constrained parameters c[i], but can't constrain part of function having both parameters and variables.
Basically, 0 < c[i] (xd[10]**c[10]) (xd[11]**(c[11]+c[12]*xd[12])) < 1 is what I need
import numpy
import pandas as pd
#Dataframe from excel (imported x0-x12 from excel)
#Gekko:
from gekko import GEKKO
m = GEKKO(remote=False); m.options.IMODE=2#parameter regression
c = m.Array(m.FV,13)#array of 13 fixed parameter
for ci in c:
ci.STATUS=1#calculate fixed parameter
ci.LOWER =0#constraint: lower limit
ci.UPPER =1#constraint: lower limit
#Define variables
xd = m.Array(m.Param,13); xd[0].value=x0; xd[1].value=x1; xd[2].value=x2; xd[3].value=x3;
xd[4].value=x4; xd[5].value=x5; xd[6].value=x6; xd[7].value=x7; xd[8].value=x8; xd[9].value=x9;
xd[10].value=x10; xd[11].value=x11; xd[12].value=x12
yd = m.Param(y); yp = m.Var()
#Equation of custom function
m.Equation(yp==(c[0]*xd[0]+c[1]*xd[1]+c[2]*xd[2]+c[3]*xd[3]+c[4]*xd[4]+c[5]*xd[5]+c[6]*xd[6]+c[7]*xd[7]+
c[8]*xd[8]+c[9]*xd[9])*(xd[10]**c[10])*(xd[11]**(c[11]+c[12]*xd[12])))
#Minimize difference between actual and predicted y
m.Minimize((yd-yp)**2)
#Solve
m.solve(disp=False)
#Retrain parameter values
a = [c[i].value[0] for i in range(13)]
print(a)
You can define new inequality constraints.
m.Equation(xd[10]**c[10])*(xd[11]**(c[11]+c[12]*xd[12])>=0)
m.Equation(xd[10]**c[10])*(xd[11]**(c[11]+c[12]*xd[12])<=1)
or define a new variable with lower and upper bounds.
#Inequality Constraints
z = m.Var(lb=0,ub=1)
m.Equation(z==(xd[10]**c[10])*(xd[11]**(c[11]+c[12]*xd[12])))
Here is a full script with the second approach.
import numpy as np
import pandas as pd
#Dataframe from excel (imported x0-x12 from excel)
x = [np.random.rand(10) for i in range(13)]
y = np.random.rand(10)
#Gekko:
from gekko import GEKKO
m = GEKKO(remote=False); m.options.IMODE=2
c = m.Array(m.FV,13)#array of 13 fixed parameter
for ci in c:
ci.STATUS = 1 #calculate fixed parameter
ci.LOWER = 0 #constraint: lower limit
ci.UPPER = 1 #constraint: lower limit
#Define variables
xd = m.Array(m.Param,13)
for i in range(13):
xd[i].value = x[i]
yd = m.Param(y); yp = m.Var()
#Equation of custom function
m.Equation(yp==(c[0]*xd[0]+c[1]*xd[1]+c[2]*xd[2]+\
c[3]*xd[3]+c[4]*xd[4]+c[5]*xd[5]+\
c[6]*xd[6]+c[7]*xd[7]+c[8]*xd[8]+\
c[9]*xd[9])*(xd[10]**c[10])*\
(xd[11]**(c[11]+c[12]*xd[12])))
#Inequality Constraints
z = m.Var(lb=0,ub=1)
m.Equation(z==(xd[10]**c[10])*(xd[11]**(c[11]+c[12]*xd[12])))
#Minimize difference between actual and predicted y
m.Minimize((yd-yp)**2)
#Solve
m.solve(disp=True)
#Retrieve parameter values
a = [c[i].value[0] for i in range(13)]
print(a)
This uses random numbers instead of the data from the Excel import that wasn't available from your question.
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.