# Optimization in Python

You might have noticed that we didn't do anything related to sparsity with scikit-learn models. A lot of the work we covered in the machine learning class is very recent research, and as such is typically not implemented by the popular libraries.

If we want to do things like sparse regression, we're going to have to roll up our sleeves and do it ourselves. For that, we need to be able to solve optimization problems. In Julia, we did this with JuMP. In Python, we'll use a similar library called *pyomo*.

# Installing pyomo

You can run the following command to install pyomo if you haven't already.


```python
!pip install pyomo --user
```

# Intro to pyomo

Let's see how we translate a simple, 2 variable LP to pyomo code.

$$
\begin{align*}
\max_{x,y} \quad& x + 2y \\
\text{s.t.}\quad& x + y \leq 1 \\
& x, y \geq 0.
\end{align*}
$$

First thing is to import the pyomo functions:


```python
from pyomo.environ import *
from pyomo.opt import SolverFactory
```

Next, we construct a model object. This is a container for everything in our optimization problem: variables, constraints, solver options, etc.


```python
m = ConcreteModel()
```

Next, we define the two decision variables in our optimization problem. We use the ``Var`` function to create the variables. The `within` keyword is used to specify the bounds on the variables, or equivalently the `bounds` keyword. The variables are added to the model object with names `x` and `y`.


```python
m.x = Var(within=NonNegativeReals)
m.y = Var(bounds=(0, float('inf')))
```

We now add the single constraint of our problem using the ``Constraint`` function. We write it algebraically, and save the result to the model.


```python
m.con = Constraint(expr=m.x + m.y <= 1)
```

We specify the objective function with the `Objective` function:


```python
m.obj = Objective(sense=maximize, expr=m.x + 2 * m.y)
```

We solve the optimization problem by first specifying a solver using `SolverFactory` and then using this solver to solve the model:


```python
solver = SolverFactory('gurobi')
solver.solve(m)
```




    {'Problem': [{'Name': 'x3', 'Lower bound': 2.0, 'Upper bound': 2.0, 'Number of objectives': 1, 'Number of constraints': 2, 'Number of variables': 3, 'Number of binary variables': 0, 'Number of integer variables': 0, 'Number of continuous variables': 3, 'Number of nonzeros': 3, 'Sense': 'maximize'}], 'Solver': [{'Status': 'ok', 'Return code': '0', 'Message': 'Model was solved to optimality (subject to tolerances), and an optimal solution is available.', 'Termination condition': 'optimal', 'Termination message': 'Model was solved to optimality (subject to tolerances), and an optimal solution is available.', 'Wall time': '0.06682205200195312', 'Error rc': 0, 'Time': 1.0039210319519043}], 'Solution': [OrderedDict([('number of solutions', 0), ('number of solutions displayed', 0)])]}



We can now inspect the solution values and optimal cost.


```python
m.obj()
```




    2.0




```python
m.x.value
```




    0.0




```python
m.y.value
```




    1.0



Let's put it all together to compare with Julia/JuMP


```python
# Create model
m = ConcreteModel()
# Add variables
m.x = Var(within=NonNegativeReals)
m.y = Var(bounds=(0, float('inf')))
# Add constraint
m.con = Constraint(expr=m.x + m.y <= 1)
# Add objective
m.obj = Objective(sense=maximize, expr=m.x + 2 * m.y)
# Solve model
solver = SolverFactory('gurobi')
solver.solve(m)
# Inspect solution
print(m.obj())
print(m.x.value)
print(m.y.value)
```

    2.0
    0.0
    1.0


```julia
# Create model
m = Model(solver=GurobiSolver())
# Add variables
@variable(m, x >= 0)
@variable(m, y >= 0)
# Add constraint
@constraint(m, x + y <= 1)
# Add objective
@objective(m, Max, x + 2y)
# Solve model
solve(m)
# Inspect solution
@show getobjectivevalue(m)
@show getvalue(x)
@show getvalue(y)
```

### Exercise

Code and solve the following optimization problem:

$$
\begin{align*}
\min_{x,y} \quad& 3x - y \\
\text{s.t.}\quad& x + 2y \geq 1 \\
& x \geq 0 \\
& 0 \leq y \leq 1.
\end{align*}
$$


```python
# Create the model
m = ConcreteModel()
# Add the variables
m.x = Var(within=NonNegativeReals)
m.y = Var(bounds=(0, 1))
# Add the constraint
m.con = Constraint(expr=m.x + 2 * m.y >= 1)
# Add the objective
m.obj = Objective(sense=minimize, expr=3 * m.x - m.y)

solver = SolverFactory('gurobi')
solver.solve(m)

print(m.x.value, m.y.value)
```

    0.0 1.0



```python
for v in m.component_data_objects(Var, active=True):
    print(v, value(v)) # doctest: +SKIP
```

    x 0.0
    y 1.0



```python
m.pprint()
```

    2 Var Declarations
        x : Size=1, Index=None
            Key  : Lower : Value : Upper : Fixed : Stale : Domain
            None :     0 :   0.0 :  None : False : False : NonNegativeReals
        y : Size=1, Index=None
            Key  : Lower : Value : Upper : Fixed : Stale : Domain
            None :     0 :   1.0 :     1 : False : False :  Reals
    
    1 Objective Declarations
        obj : Size=1, Index=None, Active=True
            Key  : Active : Sense    : Expression
            None :   True : minimize : 3*x - y
    
    1 Constraint Declarations
        con : Size=1, Index=None, Active=True
            Key  : Lower : Body    : Upper : Active
            None :   1.0 : x + 2*y :  +Inf :   True
    
    4 Declarations: x y con obj


# Index sets

Let's now move to a more complicated problem. We'll look at a transportation problem:

$$
\begin{align}
\min & \sum\limits_{i = 1}^{m} \sum\limits_{j = 1}^{n} c_{ij} x_{ij}\\
& \sum\limits_{j = 1}^{n} x_{ij} \leq b_i && i = 1, \ldots, m\\
& \sum\limits_{i = 1}^{m} x_{ij} = d_j && j = 1, \ldots, n\\
& x_{ij} \ge 0 && i = 1, \ldots, m, j = 1, \ldots, n
\end{align}
$$

And with some data:


```python
import numpy as np

m = 2  # Number of supply nodes
n = 5  # Number of demand nodes
# Supplies
b = np.array([1000, 4000])
# Demands
d = np.array([500, 900, 1800, 200, 700])
# Costs
c = np.array([[2, 4, 5, 2, 1], 
              [3, 1, 3, 2, 3]])
```

Now we can formulate the problem with pyomo


```python
model = ConcreteModel()
```

First step is adding variables. We can add variables with indices by passing the relevant index sets to the `Var` constructor. In this case, we need a $m$-by$n$ matrix of variables:


```python
model.x = Var(range(m), range(n), within=NonNegativeReals)
```

Now to add the constraints. We have to add one supply constraint for each factory, so we might try something like:


```python
for i in range(m):
    model.supply = Constraint(expr=sum(model.x[i, j] for j in range(n)) <= b[i])
```

    WARNING: Implicitly replacing the Component attribute supply (type=<class
        'pyomo.core.base.constraint.SimpleConstraint'>) on block unknown with a
        new Component (type=<class
        'pyomo.core.base.constraint.SimpleConstraint'>). This is usually
        indicative of a modelling error. To avoid this warning, use
        block.del_component() and block.add_component().


Can you see the problem? We are overwriting `model.supply` in each iteration of the loop, and so only the last constraint is applied.

Luckily, pyomo has a (not-so-easy) way to add multiple constraints at a time. We first define a *rule* that takes in the model and any required indices, and then returns the expression for the constraint:


```python
def supply_rule(model, i):
    return sum(model.x[i, j] for j in range(n)) <= b[i]
```

We then add the constraint by referencing this rule along with the index set we want the constraint to be defined over:


```python
model.supply2 = Constraint(range(m), rule=supply_rule)
```

We then apply the same approach for the demand constraints


```python
def demand_rule(model, j):
    return sum(model.x[i, j] for i in range(m)) == d[j]

model.demand = Constraint(range(n), rule=demand_rule)
```

Finally, we add the objective:


```python
model.obj = Objective(sense=minimize, 
    expr=sum(c[i, j] * model.x[i, j] 
    for i in range(m) for j in range(n)))
```

Now we can solve the problem


```python
solver = SolverFactory('gurobi')
solver.solve(model)
```




    {'Problem': [{'Name': 'x11', 'Lower bound': 8600.0, 'Upper bound': 8600.0, 'Number of objectives': 1, 'Number of constraints': 9, 'Number of variables': 11, 'Number of binary variables': 0, 'Number of integer variables': 0, 'Number of continuous variables': 11, 'Number of nonzeros': 26, 'Sense': 'minimize'}], 'Solver': [{'Status': 'ok', 'Return code': '0', 'Message': 'Model was solved to optimality (subject to tolerances), and an optimal solution is available.', 'Termination condition': 'optimal', 'Termination message': 'Model was solved to optimality (subject to tolerances), and an optimal solution is available.', 'Wall time': '0.04288291931152344', 'Error rc': 0, 'Time': 0.31615591049194336}], 'Solution': [OrderedDict([('number of solutions', 0), ('number of solutions displayed', 0)])]}



It solved, so we can extract the results


```python
flows = np.array([[model.x[i, j].value for j in range(n)] for i in range(m)])
flows
```




    array([[ 300.,    0.,    0.,    0.,  700.],
           [ 200.,  900., 1800.,  200.,    0.]])



We can also check the objective value for the cost of this flow


```python
model.obj()
```




    8600.0



For simplicity, here is the entire formulation and solving code together:


```python
model = ConcreteModel()
# Variables
model.x = Var(range(m), range(n), within=NonNegativeReals)
# Supply constraint
def supply_rule(model, i):
    return sum(model.x[i, j] for j in range(n)) <= b[i]
model.supply2 = Constraint(range(m), rule=supply_rule)
# Demand constraint
def demand_rule(model, j):
    return sum(model.x[i, j] for i in range(m)) == d[j]
model.demand = Constraint(range(n), rule=demand_rule)
# Objective
model.obj = Objective(sense=minimize, 
    expr=sum(c[i, j] * model.x[i, j] 
    for i in range(m) for j in range(n)))
# Solve
solver = SolverFactory('gurobi')
solver.solve(model)
# Get results
flows = np.array([[model.x[i, j].value for j in range(n)] for i in range(m)])
model.obj()
```

# Machine Learning

Now let's put our pyomo knowledge to use and implement some of the same methods we saw in the machine learning class

First, specify your solver executable location:


```python
executable='C:/Users/omars/.julia/v0.6/Ipopt/deps/usr/bin/ipopt.exe'
```

To use the version left over from Julia
### On MacOS and Linux

`executable="~/.julia/v0.6/Homebrew/deps/usr/Cellar/ipopt/3.12.4_1/bin/ipopt")`

### On Windows

The path is probably under WinRPM:

`executable='%HOME%/.julia/v0.6/WinRPM/...')")`


# Linear Regression

Let's just try a simple linear regression


```python
def linear_regression(X, y):
    n, p = X.shape

    # Create model
    m = ConcreteModel()

    # Add variables
    m.beta = Var(range(p))

    # Add constraints

    # Add objective
    m.obj = Objective(sense=minimize, expr=sum(
        pow(y[i] - sum(X[i, j] * m.beta[j] for j in range(p)), 2) 
        for i in range(n)))

    solver = SolverFactory('ipopt', executable=executable)
    
    ## tee=True enables solver output
    # results = solver.solve(m, tee=True)
    results = solver.solve(m, tee=False)

    return [m.beta[j].value for j in range(p)]
```

Let's load up some data to test it out on:


```python
from sklearn.datasets import load_boston
data = load_boston()
X = data.data
y = data.target
```

Try our linear regression function:


```python
print(linear_regression(X, y))
```

    [-0.0928965170276332, 0.04871495518299193, -0.004059979574994615, 2.8539988199938313, -2.8684363704210067, 5.928147779053185, -0.007269334576040927, -0.9685141573949657, 0.1711511282943897, -0.009396215397156512, -0.39219092629505153, 0.014905610228206412, -0.4163044707374162]


We can compare with sklearn to make sure it's right:


```python
from sklearn.linear_model import LinearRegression
m = LinearRegression(fit_intercept=False)
m.fit(X, y)
m.coef_
```




    array([-9.28965170e-02,  4.87149552e-02, -4.05997958e-03,  2.85399882e+00,
           -2.86843637e+00,  5.92814778e+00, -7.26933458e-03, -9.68514157e-01,
            1.71151128e-01, -9.39621540e-03, -3.92190926e-01,  1.49056102e-02,
           -4.16304471e-01])



Just for reference, let's look back at how we do the same thing in JuMP!

```julia
using JuMP, Gurobi
function linear_regression(X, y)
    n, p = size(X)
    m = Model(solver=GurobiSolver())
    @variable(m, beta[1:p])
    @objective(m, Min, sum((y[i] - sum(X[i, j] * beta[j] for j = 1:p)) ^ 2 for i = 1:n))
    solve(m)
    getvalue(beta)
end
```

or even

```julia
using JuMP, Gurobi
function linear_regression(X, y)
    n, p = size(X)
    m = Model(solver=GurobiSolver())
    @variable(m, beta[1:p])
    @objective(m, Min, sum((y - X * beta) .^ 2))
    solve(m)
    getvalue(beta)
end
```

Much simpler!

### Exercise

Modify the linear regression formulation to include an intercept term, and compare to scikit-learn's LinearRegression with `fit_intercept=False` to make sure it's the same


```python
def linear_regression_intercept(X, y):
    n, p = X.shape

    # Create model
    m = ConcreteModel()

    # Add variables
    m.beta = Var(range(p))
    m.b0 = Var()

    # Add constraints

    # Add objective
    m.obj = Objective(sense=minimize, expr=sum(
        pow(y[i] - sum(X[i, j] * m.beta[j] for j in range(p)) - m.b0, 2) 
        for i in range(n)))

    solver = SolverFactory('ipopt', executable=executable)
    
    ## tee=True enables solver output
    # results = solver.solve(m, tee=True)
    results = solver.solve(m, tee=False)

    return [m.beta[j].value for j in range(p)]

linear_regression_intercept(X, y)
```




    [-0.10801135783681295,
     0.046420458366832826,
     0.020558626367267345,
     2.6867338193441053,
     -17.766611228344583,
     3.8098652068064345,
     0.0006922246403880231,
     -1.4755668456006032,
     0.30604947898554247,
     -0.012334593916578101,
     -0.9527472317092022,
     0.009311683273791104,
     -0.5247583778555439]




```python
m = LinearRegression(fit_intercept=True)
m.fit(X, y)
m.coef_
```




    array([-1.08011358e-01,  4.64204584e-02,  2.05586264e-02,  2.68673382e+00,
           -1.77666112e+01,  3.80986521e+00,  6.92224640e-04, -1.47556685e+00,
            3.06049479e-01, -1.23345939e-02, -9.52747232e-01,  9.31168327e-03,
           -5.24758378e-01])



# Robust Regression

We saw in the class that both ridge and lasso regression were robust versions of linear regression. Both of these are provided by `sklearn`, but we need to know how to implement them if we want to extend regression ourselves


```python
def ridge_regression(X, y, rho):
    n, p = X.shape

    # Create model
    m = ConcreteModel()

    # Add variables
    m.beta = Var(range(p))

    # Add objective
    m.obj = Objective(sense=minimize, expr=sum(
        pow(y[i] - sum(X[i, j] * m.beta[j] for j in range(p)),2) 
        for i in range(n)) + rho * sum(pow(m.beta[j], 2) for j in range(p)))

    solver = SolverFactory('ipopt', executable=executable)
    
    ## tee=True enables solver output
    # results = solver.solve(m, tee=True)
    results = solver.solve(m, tee=False)
    return [m.beta[j].value for j in range(p)]
```


```python
ridge_regression(X, y, 100000)
```




    [-0.03349704413300387,
     0.09109374003810565,
     -0.020781437073126584,
     0.001953623650442121,
     0.0010799179606038737,
     0.036595936096463166,
     0.031147076775253392,
     0.008145310191304656,
     0.000355681037898492,
     0.0012341682146102984,
     0.025195318040087757,
     0.05360061512165024,
     -0.09887567363356603]




```python
def lasso(X, y, rho):
    n, p = X.shape

    # Create model
    m = ConcreteModel()

    # Add variables
    m.beta = Var(range(p))

    # Add objective
    m.obj = Objective(sense=minimize, expr=sum(
        pow(y[i] - sum(X[i, j] * m.beta[j] for j in range(p)),2) 
        for i in range(n)) + rho * sum(pow(m.beta[j], 2) for j in range(p)))

    solver = SolverFactory('ipopt', executable=executable)
    
    ## tee=True enables solver output
    # results = solver.solve(m, tee=True)
    results = solver.solve(m, tee=False)
    return [m.beta[j].value for j in range(p)]
```

### Exercise

Implement Lasso regression


```python
def lasso_regression(X, y, rho):
    n, p = X.shape

    # Create model
    m = ConcreteModel()

    # Add variables
    m.beta = Var(range(p))
    m.absb = Var(range(p))

    # Add constraints
    def absbeta1(m, j):
        return m.beta[j] <= m.absb[j]
    m.absb1 = Constraint(range(p), rule=absbeta1)
    def absbeta2(m, j):
        return -m.beta[j] <= m.absb[j]
    m.absb2 = Constraint(range(p), rule=absbeta2)
        

    # Add objective
    m.obj = Objective(sense=minimize, expr=sum(
        pow(y[i] - sum(X[i, j] * m.beta[j] for j in range(p)), 2) 
        for i in range(n)) + rho * sum(m.absb[j] for j in range(p)))

    solver = SolverFactory('ipopt', executable=executable)
    
    ## tee=True enables solver output
    # results = solver.solve(m, tee=True)
    results = solver.solve(m, tee=False)
    return [m.beta[j].value for j in range(p)]
```


```python
lasso_regression(X, y, 1000)
```

# Sparse Regression


```python
def sparse_regression(X, y, k):
    n, p = X.shape
    M = 1000

    # Create model
    m = ConcreteModel()

    # Add variables
    m.beta = Var(range(p))
    m.z = Var(range(p), within=Binary)

    # Add constraints
    def bigm1(m, j):
        return m.beta[j] <= M * m.z[j]
    m.bigm1 = Constraint(range(p), rule=bigm1)
    def bigm2(m, j):
        return m.beta[j] >= -M * m.z[j]
    m.bigm2 = Constraint(range(p), rule=bigm2)
        
    m.sparsity = Constraint(expr=sum(m.z[j] for j in range(p)) <= k)

    # Add objective
    m.obj = Objective(sense=minimize, expr=sum(
        pow(y[i] - sum(X[i, j] * m.beta[j] for j in range(p)), 2) 
        for i in range(n)))

    solver = SolverFactory('ipopt', executable=executable)
    
    ## tee=True enables solver output
    # results = solver.solve(m, tee=True)
    results = solver.solve(m, tee=False)
    return [m.beta[j].value for j in range(p)]
```


```python
sparse_regression(X, y, 10)
```




    [-0.09289651702716464,
     0.048714955183037804,
     -0.004059979575834942,
     2.8539988201207356,
     -2.868436370310866,
     5.9281477790418435,
     -0.0072693345761560306,
     -0.9685141573945727,
     0.1711511282944914,
     -0.009396215397248317,
     -0.39219092628560964,
     0.014905610227998044,
     -0.4163044707410663]




```python
import numpy as np
l = np.array([1,2,3,4])

print(l**2)
print([sqrt(i) for i in l])
```

    [ 1  4  9 16]
    [1.0, 1.4142135623730951, 1.7320508075688772, 2.0]


### Exercise

Try implementing the algorithmic framework for linear regression:
- sparsity constraints
- lasso regularization
- restrict highly correlated pairs of features
- nonlinear transformations (just $\sqrt(x)$ and $x^2$)


```python
import numpy as np
from sklearn.preprocessing import normalize

def all_regression(X_orig, y, k, rho):
    n, p_orig = X_orig.shape
    M = 10
    
    X = np.concatenate(
        [X_orig, np.sqrt(X_orig), np.square(X_orig)], axis=1
    )
    p = X.shape[1]
    
    # Normalize data
    X = normalize(X, axis=0)
    y = (y - np.mean(y)) / np.linalg.norm(y)

    # Create model
    m = ConcreteModel()

    # Add variables
    m.beta = Var(range(p))
    m.z = Var(range(p), within=Binary)
    m.absb = Var(range(p))

    # Sparsity constraints
    def bigm1(m, j):
        return m.beta[j] <= M * m.z[j]
    m.bigm1 = Constraint(range(p), rule=bigm1)
    def bigm2(m, j):
        return m.beta[j] >= -M * m.z[j]
    m.bigm2 = Constraint(range(p), rule=bigm2)
    m.sparsity = Constraint(expr=sum(m.z[j] for j in range(p)) <= k)
    
    # Lasso constraints
    def absbeta1(m, j):
        return m.beta[j] <= m.absb[j]
    m.absb1 = Constraint(range(p), rule=absbeta1)
    def absbeta2(m, j):
        return -m.beta[j] <= m.absb[j]
    m.absb2 = Constraint(range(p), rule=absbeta2)
    
    # Correlation constraints
    corX = np.corrcoef(np.transpose(X))
    def cor_rule(m, i, j):
        if i > j and abs(corX[i, j]) > 0.8:
            return (sum(m.z[k] for k in range(i, p, p_orig)) + 
                    sum(m.z[k] for k in range(j, p, p_orig)) <= 1)
        else:
            return Constraint.Skip
    m.cor = Constraint(range(p_orig), range(p_orig), rule=cor_rule)
    
    # Nonlinear constraints
    def nl_rule(m, i):
        return sum(m.z[k] for k in range(i, p, p_orig)) <= 1
    m.nl = Constraint(range(p_orig), rule=nl_rule)

    # Add objective
    m.obj = Objective(sense=minimize, expr=sum(
        pow(y[i] - sum(X[i, j] * m.beta[j] for j in range(p)), 2) 
        for i in range(n)) + rho * sum(m.absb[j] for j in range(p)))

    solver = SolverFactory('ipopt', executable=executable)
    
    ## tee=True enables solver output
#     results = solver.solve(m, tee=True)
    results = solver.solve(m, tee=False)

    return np.array([m.beta[j].value for j in range(p)]).reshape(-1, p_orig)
```


```python
all_regression(X, y, 6, 0)
```




    array([[-0.2436117 , -0.40635426,  1.287454  ,  0.00847825, -3.77070371,
            -5.52116145, -0.89579769,  1.8866262 , -1.2658388 , -0.27200984,
            -4.29661229,  1.08490846,  0.87517741],
           [ 0.08922823,  0.22757203, -1.40483302,  0.00847825,  6.06383002,
             1.71571313,  0.89614225, -3.03336942,  1.22670959, -0.27220395,
             5.06365681, -0.5261114 , -1.95285925],
           [ 0.1005534 ,  0.19449394, -0.33587296,  0.00847825,  0.1653508 ,
             2.76298931,  0.2188393 , -0.32862084,  0.51518994,  0.15346198,
             0.63958091, -0.5226175 , -0.10282404]])



# Logistic Regression

Like JuMP, we need to use a new solver for the nonlinear problem. We can use Ipopt as before, except we have to set it up manually. You'll need to download Ipopt and add it to the PATH. 

On Mac, you can do this with Homebrew if you have it:

The other way is to download a copy of ipopt and specify the path to it exactly when creating the solver. For example, I have a copy of Ipopt left over from JuMP, which I can use by modifying the SolverFactory line as indicated below:


```python
def logistic_regression(X, y):
    n, p = X.shape
    
    # Convert y to (-1, +1)
    assert np.min(y) == 0
    assert np.max(y) == 1
    Y = y * 2 - 1
    assert np.min(Y) == -1
    assert np.max(Y) == 1

    # Create the model
    m = ConcreteModel()

    # Add variables
    m.b = Var(range(p))
    m.b0 = Var()

    # Set nonlinear objective function
    m.obj = Objective(sense=maximize, expr=-sum(
        log(1 + exp(-Y[i] * (sum(X[i, j] * m.b[j] for j in range(p)) + m.b0)))
        for i in range(n)))

    # Solve the model and get the optimal solutions
    solver = SolverFactory('ipopt', executable=executable)
        
    solver.solve(m)
    return [m.b[j].value for j in range(p)], m.b0.value
```

Load up some data


```python
from sklearn.datasets import load_breast_cancer
data = load_breast_cancer()
X = data.data
y = data.target
```


```python
logistic_regression(X, y)
```




    ([4149.289184609701,
      -95.66597524418847,
      -122.72220946545622,
      -31.07342010773767,
      -30864.886098201634,
      36295.57939884905,
      -19052.20895802693,
      -19686.209843004974,
      14077.278909141973,
      -45229.07643132272,
      -2194.6637679242845,
      98.59470071343296,
      810.8129671962596,
      -71.48231452267014,
      65260.80657288916,
      -62374.925075090185,
      52121.749598051225,
      -203728.7743634409,
      62535.47114299024,
      488515.76125488814,
      -1086.5758594687723,
      -31.442744168114533,
      -43.120968967631356,
      7.303064300605229,
      3500.09658663806,
      5108.10478323704,
      -4412.61061910415,
      -4740.534608043277,
      -14164.859267037991,
      -35109.19922500868],
     -323.2327374749216)



### Exercise

Implement the regularized versions of logistic regression that scikit-learn provides:






```python
def logistic_regression_l1(X, y, C):
    n, p = X.shape
    
    # Convert y to (-1, +1)
    assert np.min(y) == 0
    assert np.max(y) == 1
    Y = y * 2 - 1
    assert np.min(Y) == -1
    assert np.max(Y) == 1

    # Create the model
    m = ConcreteModel()

    # Add variables
    m.b = Var(range(p))
    m.b0 = Var()
    
    # Lasso constraints
    m.absb = Var(range(p))
    def absbeta1(m, j):
        return m.b[j] <= m.absb[j]
    m.absb1 = Constraint(range(p), rule=absbeta1)
    def absbeta2(m, j):
        return -m.b[j] <= m.absb[j]
    m.absb2 = Constraint(range(p), rule=absbeta2)
    
    # Set nonlinear objective function
    m.obj = Objective(sense=minimize, expr=sum(m.absb[j] for j in range(p)) + C * sum(
        log(1 + exp(-Y[i] * (sum(X[i, j] * m.b[j] for j in range(p)) + m.b0)))
        for i in range(n)))

    # Solve the model and get the optimal solutions
    solver = SolverFactory('ipopt', executable=executable)
    
    solver.solve(m)
    return [m.b[j].value for j in range(p)], m.b0.value
```


```python
logistic_regression_l1(X, y, 100)
```


```python
def logistic_regression_l2(X, y, C):
    n, p = X.shape
    
    # Convert y to (-1, +1)
    assert np.min(y) == 0
    assert np.max(y) == 1
    Y = y * 2 - 1
    assert np.min(Y) == -1
    assert np.max(Y) == 1

    # Create the model
    m = ConcreteModel()

    # Add variables
    m.b = Var(range(p))
    m.b0 = Var()
    
    # Set nonlinear objective function
    m.obj = Objective(sense=minimize, expr=0.5 * sum(pow(m.b[j], 2) for j in range(p)) + C * sum(
        log(1 + exp(-Y[i] * (sum(X[i, j] * m.b[j] for j in range(p)) + m.b0)))
        for i in range(n)))

    # Solve the model and get the optimal solutions
    solver = SolverFactory('ipopt', executable=executable)
    
    solver.solve(m)
    return [m.b[j].value for j in range(p)], m.b0.value
```


```python
logistic_regression_l2(X, y, 1000)
```


```python

```


```python

```

816158f911b010a8630108c2c5478f9441365415
ipynb
Jupyter Notebook
ML3 - Optimization Modeling (Complete).ipynb
oskali/SoftwareTools_MBAN21_Python
308ef8b3bda980d92a14f946ed9e16030ea69072
MIT
ML3 - Optimization Modeling (Complete).ipynb
oskali/SoftwareTools_MBAN21_Python
308ef8b3bda980d92a14f946ed9e16030ea69072
MIT
ML3 - Optimization Modeling (Complete).ipynb
oskali/SoftwareTools_MBAN21_Python
308ef8b3bda980d92a14f946ed9e16030ea69072
MIT
Qwen/Qwen-72B
1. YES
2. YES