如何将最小绝对回归作为线性优化问题

时间:2019-01-07 21:33:16

标签: python optimization regression pyomo minimization

我是对此的初学者,所以我打算根据以下公式将最小绝对回归作为线性优化问题来实现:

a lineal formulation

更新代码  到目前为止,这是我的代码,但是我确定它不好,因为我遇到下一个错误:

  

错误:为约束neg_Constraint生成表达式时,规则失败       索引为1:AttributeError:'NoneType'对象没有属性'getname'

#Settings my variables
nsample = 100
nvariables = 2
beta=np.random.randint(-5,5,size=([nvariables+1,1]));
x0 = np.ones([nsample,1])
x1 = np.random.uniform(0,5,([nsample,nvariables]))
X = np.concatenate([x0,x1], axis = 1)
error = np.random.normal(0,1, (nsample,1))
Y = np.dot(X, beta) + error

#Defining my model
from pyomo.environ import *
opt = SolverFactory("glpk")
from pyomo.environ import SolverFactory

def la_reg_opt(n,m,x,y):

    model =  AbstractModel()
    model.n = n
    model.m = m

    model.I = RangeSet(1, model.n)
    model.J = RangeSet(1, model.m)

    model.y = y
    model.x = x
    model.b = Var(model.J, domain = NonNegativeReals)
    model.t = Var(model.I, domain = NonNegativeReals) #Tercera restriccion

    def obj_funct(model):
        return summation(model.t)
    model.OBJ = Objective(rule = obj_funct)

    def lower_bound(model,i):
        return   model.y[i] - sum(model.x[i,j]*model.b[j] for j in model.J) >= -model.t[i]
    model.neg_Constraint = Constraint (model.I, rule = lower_bound) 

    def upper_bound(model,i):
        return  model.y[i] - sum(model.x[i,j]*model.b[j] for j in model.J) >= model.t[i] 
    model.pos_Constraint = Constraint (model.I, rule = upper_bound) 

    instance = model.create_instance()
    instance.dual = Suffix(direction=Suffix.IMPORT)
    results = opt.solve(instance)

    return results


#calling my model
res=la_reg_opt(nsample, nvariables, X, Y)
print (res)

我在做什么错了?

非常感谢您。

0 个答案:

没有答案