Variables for Linear Regression LP
AnsweredI'm very new to Gurobi. I need to perform linear regression via Least Absolute Deviations, for which the LP formulation is written:

My code is

which gives the error:

though I am sure there are plenty more errors in my code than just this. I would really really appreciate any help to get my code working.
-
Official comment
This post is more than three years old. Some information may not be up to date. For current information, please check the Gurobi Documentation or Knowledge Base. If you need more help, please create a new post in the community forum. Or why not try our AI Gurobot?. -
Hi Samuel,
I think what you want to achieve is
for i in weeks:
for j in wpm:
m.addConstr(z_i >= y_i[j] - (a_1 * x_i[i] + a_0))
m.addConstr(z_i >= -y_i[j] + (a_1 * x_i[i] + a_0))Your version does not work because the for clauses can't be used without any context like that. You are practically telling Python to generate the constraint
z_i >= y_i[j] - (a_1 * x_i[i] + a_0)
over the two loops inside an \(\texttt{addConstr()}\) function which then results in this rather cryptic error.
Please also not that currently you have only one variable \(z_i\) while to me it seems like you would like to have multiple of those.
Best regards,
Jaromił0 -
Jaromil,
Thank you so much for the help. Z_i is my objective to be minimized. I cannot figure out what's going wrong, as the code now runs but a_0, a_1, and z_i are returned as 0, when I know that realistically the coefficients should be positive, given the data. Do you have any ideas?
0 -
Hi Samuel,
Currently all terms \(z_i, a_0, a_1, x_i,\) and \(y_i\) are optimization variables with default lower bound \(0\). From your formulation I assume that you would like to treat only \(z_i, a_0,\) and \(a_1\) as optimization variables and use values in the list \(\texttt{weeks}\) for \(x_i\) and values in the list \(\texttt{wpm}\) for \(y_i\). Then, you don't have to define \(x_i\) and \(y_i\) as optimization variables but you can rather directly work with the values in the two lists. This can be achieved by, e.g.,
weekList = range(1,11)
wpmList = [5, 9, 15, 19, 21, 24, 26, 30, 31, 35]
m = Model("Least Absolute Deviations Linear Regression")
z_i = m.addVar()
a_0 = m.addVar(vtype = GRB.INTEGER)
a_1 = m.addVar(vtype = GRB.INTEGER)
m.setObjective(z_i, GRB.MINIMIZE)
for week in weekList:
for wpm in wpmList:
m.addConstr(z_i >= wpm - (a_1 * week + a_0))
m.addConstr(z_i >= -wpm + (a_1 * week + a_0))You could use the Model.write() to write an LP file to see what the model you are modeling looks like via
m.write("myLP.lp")Best regards,
Jaromił0
Post is closed for comments.
Comments
4 comments