Skip to main content

Variables for Linear Regression LP

Answered

Comments

4 comments

  • Official comment
    Simranjit Kaur
    • Gurobi Staff
    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?.
  • Jaromił Najman
    • Gurobi Staff

    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
  • Samuel Zhang
    • Gurobi-versary
    • First Comment
    • First Question

    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
  • Jaromił Najman
    • Gurobi Staff

    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.