This lecture gives an overview of some optimization tools in Julia.
1.1 Flowchart
Statisticians do optimizations in daily life: maximum likelihood estimation, machine learning, …
Category of optimization problems:
Problems with analytical solutions: least squares, principle component analysis, canonical correlation analysis, …
Problems subject to Disciplined Convex Programming (DCP): linear programming (LP), quadratic programming (QP), second-order cone programming (SOCP), semidefinite programming (SDP), and geometric programming (GP).
Nonlinear programming (NLP): Newton type algorithms, Fisher scoring algorithm, EM algorithm, MM algorithms.
Large scale optimization: ADMM, SGD, …
1.2 Modeling tools and solvers
Getting familiar with good optimization softwares broadens the scope and scale of problems we are able to solve in statistics. Following table lists some of the best optimization softwares.
LP
MILP
SOCP
MISOCP
SDP
GP
NLP
MINLP
R
Matlab
Julia
Python
Cost
modeling tools
cvx
x
x
x
x
x
x
x
x
x
A
Convex.jl
x
x
x
x
x
x
O
JuMP.jl
x
x
x
x
x
x
x
O
MathOptInterface.jl
x
x
x
x
x
x
x
O
convex solvers
Mosek
x
x
x
x
x
x
x
x
x
x
x
A
Gurobi
x
x
x
x
x
x
x
x
A
CPLEX
x
x
x
x
x
x
x
x
A
SCS
x
x
x
x
x
x
O
COSMO.jl
x
x
x
x
O
NLP solvers
NLopt
x
x
x
x
x
x
O
Ipopt
x
x
x
x
x
x
O
KNITRO
x
x
x
x
x
x
x
x
$
O: open source, A: free academic license, $: commercial
Modeling tools such as cvx (for Matlab) and Convex.jl (Julia analog of cvx) implement the disciplined convex programming (DCP) paradigm proposed by Grant and Boyd (2008) http://stanford.edu/~boyd/papers/disc_cvx_prog.html. DCP prescribes a set of simple rules from which users can construct convex optimization problems easily.
Solvers (Mosek, Gurobi, Cplex, SCS, COSMO, Hypatia, …) are concrete software implementation of optimization algorithms. My favorite ones are: Mosek/Gurobi/SCS for DCP and Ipopt/NLopt for nonlinear programming. Mosek and Gurobi are commercial software but free for academic use. SCS/Ipopt/NLopt are open source.
Modeling tools usually have the capability to use a variety of solvers. But modeling tools are solver agnostic so users do not have to worry about specific solver interface.
If you want to install the commercial solvers Gurobi or Mosek, instructions are below:
Gurobi: 1. Download Gurobi at link. 2. Request free academic license at link. 3. Run grbgetkey XXXXXXXXX command on terminal as suggested. It’ll retrieve a license file and put it under the home folder. 4. Set up the environmental variables. On my machine, I put following two lines in the ~/.julia/config/startup.jl file: ENV["GUROBI_HOME"] = "/Library/gurobi902/mac64" and ENV["GRB_LICENSE_FILE"] = "/Users/huazhou/Documents/Gurobi/gurobi.lic".
Mosek: 1. Request free academic license at link. The license file will be sent to your edu email within minutes. Check Spam folder if necessary. 2. Put the license file at the default location ~/mosek/.
Standard convex problem classes like LP (linear programming), QP (quadratic programming), SOCP (second-order cone programming), SDP (semidefinite programming), and GP (geometric programming), are becoming a technology.
1.3.1 Example: microbiome regression analysis
We illustrate optimization tools in Julia using microbiome analysis as an example.
16S microbiome sequencing techonology generates sequence counts of various organisms (OTUs, operational taxonomic units) in samples.
For statistical analysis, counts are normalized into proportions for each sample, resulting in a covariate matrix \(\mathbf{X}\) with all rows summing to 1. For identifiability, we need to add a sum-to-zero constraint to the regression cofficients. In other words, we need to solve a constrained least squares problem \[
\text{minimize} \frac{1}{2} \|\mathbf{y} - \mathbf{X} \beta\|_2^2
\] subject to the constraint \(\sum_{j=1}^p \beta_j = 0\). For simplicity we ignore intercept and non-OTU covariates in this presentation.
Let’s first generate an artifical data set.
usingRandom, LinearAlgebra, SparseArraysRandom.seed!(257) # seedn, p =100, 50X =rand(n, p)# scale each row of X sum to 1lmul!(Diagonal(1./vec(sum(X, dims=2))), X)# true β is a sparse vector with about 10% non-zero entriesβ =sprandn(p, 0.1) y = X * β +randn(n);
1.3.2 Sum-to-zero regression
The sum-to-zero contrained least squares is a standard quadratic programming (QP) problem so should be solved easily by any QP solver.
Suppose we want to know which organisms (OTU) are associated with the response. We can answer this question using a sum-to-zero contrained lasso \[
\text{minimize} \frac 12 \|\mathbf{y} - \mathbf{X} \beta\|_2^2 + \lambda \|\beta\|_1
\] subject to the constraint \(\sum_{j=1}^p \beta_j = 0\). Varying \(\lambda\) from small to large values will generate a solution path.
usingConvex# # Use Mosek solver# using Mosek# solver = Mosek.Optimizer()# MOI.set(solver, MOI.RawOptimizerAttribute("LOG"), 0)# # Use Gurobi solver# using Gurobi# solver = Gurobi.Optimizer(OutputFlag=0)# Use Cplex solver# using CPLEX# solver = CplexSolver(CPXPARAM_ScreenOutput=0)# # Use SCS solver# using SCS# solver = SCS.Optimizer(verbose=0)# Use Hypatia solverusingHypatiasolver = Hypatia.Optimizer()# solve at a grid of λλgrid =0:0.01:0.35# holder for solution pathβ̂path =zeros(length(λgrid), size(X, 2)) # each row is β̂ at a λ# optimization variableβ̂classo =Variable(size(X, 2))# obtain solution path using warm start@timefor i in1:length(λgrid) λ = λgrid[i]# define optimization problem# objective problem =minimize(0.5sumsquares(y - X * β̂classo) + λ *sum(abs, β̂classo))# constraint problem.constraints +=sum(β̂classo) ==0# constraint solver = Mosek.Optimizer() MOI.set(solver, MOI.RawOptimizerAttribute("LOG"), 0)solve!(problem, solver) β̂path[i, :] = β̂classo.valueend
0.196382 seconds (1.60 M allocations: 156.354 MiB, 10.36% gc time)
usingCairoMakief =Figure()Axis( f[1, 1], title ="Sum-to-Zero Lasso", xlabel = L"\lambda", ylabel = L"\beta_j")series!(λgrid, β̂path', color =:glasbey_category10_n256)f
1.3.4 Sum-to-zero group lasso
Suppose we want to do variable selection not at the OTU level, but at the Phylum level. OTUs are clustered into various Phyla. We can answer this question using a sum-to-zero contrained group lasso \[
\text{minimize} \frac 12 \|\mathbf{y} - \mathbf{X} \beta\|_2^2 + \lambda \sum_j \|\mathbf{\beta}_j\|_2
\] subject to the constraint \(\sum_{j=1}^p \beta_j = 0\), where \(\mathbf{\beta}_j\) are regression coefficients corresponding to the \(j\)-th phylum. This is a second-order cone programming (SOCP) problem readily modeled by Convex.jl.
Let’s assume each 10 contiguous OTUs belong to one Phylum.
# # Use Mosek solver# using MosekTools# # Use Gurobi solver# using Gurobi# # Use Cplex solver# using CPLEX# solver = CplexSolver(CPXPARAM_ScreenOutput=0)# # Use SCS solver# using SCS# solver = SCSSolver(verbose=0)# Use Hypatia solverusingHypatiasolver = Hypatia.Optimizer()# solve at a grid of λλgrid =0.0:0.005:0.5β̂pathgrp =zeros(length(λgrid), size(X, 2)) # each row is β̂ at a λβ̂classo =Variable(size(X, 2))@timefor i in1:length(λgrid) λ = λgrid[i]# loss obj =0.5sumsquares(y - X * β̂classo)# group lasso penalty termfor j in1:(size(X, 2)/10) βj = β̂classo[(10(j-1)+1):10j] obj = obj + λ *norm(βj)end problem =minimize(obj)# constraint problem.constraints +=sum(β̂classo) ==0# constraint solver = Mosek.Optimizer() MOI.set(solver, MOI.RawOptimizerAttribute("LOG"), 0)solve!(problem, solver) β̂pathgrp[i, :] = β̂classo.valueend
0.356510 seconds (735.37 k allocations: 196.149 MiB, 10.95% gc time)
We see it took Mosek <2 second to solve this seemingly hard optimization problem at 101 different \(\lambda\) values.
usingCairoMakief =Figure()Axis( f[1, 1], title ="Sum-to-Zero Group Lasso", xlabel = L"\lambda", ylabel = L"\beta_j")series!(λgrid, β̂pathgrp', color =:glasbey_category10_n256)f
1.3.5 Example: matrix completion
Load the \(128 \times 128\) Lena picture with missing pixels.
We fill out the missin pixels uisng a matrix completion technique developed by Candes and Tao \[
\text{minimize } \|\mathbf{X}\|_*
\]\[
\text{subject to } x_{ij} = y_{ij} \text{ for all observed entries } (i, j).
\] Here \(\|\mathbf{M}\|_* = \sum_i \sigma_i(\mathbf{M})\) is the nuclear norm. In words we seek the matrix with minimal nuclear norm that agrees with the observed entries. This is a semidefinite programming (SDP) problem readily modeled by Convex.jl.
This example takes longer because of high dimensionality. COSMO.jl seems to be the fastest solver for this problem. Other solvers take excessively long time.
# # Use COSMO solverusingCOSMOsolver = COSMO.Optimizer()# # Use Hypatia solver# using Hypatia# solver = Hypatia.Optimizer()# Linear indices of obs. entriesobsidx =findall(Y[:] .≠0.0)# Create optimization variablesX =Variable(size(Y))# Set up optmization problemproblem =minimize(nuclearnorm(X))problem.constraints += X[obsidx] == Y[obsidx]# Solve the problem by calling solve@timesolve!(problem, solver) # fast
------------------------------------------------------------------
COSMO v0.8.7 - A Quadratic Objective Conic Solver
Michael Garstka
University of Oxford, 2017 - 2022
------------------------------------------------------------------
Problem: x ∈ R^{49153},
constraints: A ∈ R^{73665x49153} (73793 nnz),
matrix size to factor: 122818x122818,
Floating-point precision: Float64
Sets: ZeroSet of dim: 40769
DensePsdConeTriangle of dim: 32896 (256x256)
Settings: ϵ_abs = 1.0e-05, ϵ_rel = 1.0e-05,
ϵ_prim_inf = 1.0e-04, ϵ_dual_inf = 1.0e-04,
ρ = 0.1, σ = 1e-06, α = 1.6,
max_iter = 5000,
scaling iter = 10 (on),
check termination every 25 iter,
check infeasibility every 40 iter,
KKT system solver: QDLDL
Acc: Anderson Type2{QRDecomp},
Memory size = 15, RestartedMemory,
Safeguarded: true, tol: 2.0
Setup Time: 19.96ms
Iter: Objective: Primal Res: Dual Res: Rho:
1 -1.4426e+03 1.1678e+01 5.9856e-01 1.0000e-01
25 1.4495e+02 5.5360e-02 1.1033e-03 1.0000e-01
50 1.4754e+02 1.2369e-02 1.6744e-03 7.4179e-01
75 1.4797e+02 4.9490e-04 5.5696e-05 7.4179e-01
100 1.4797e+02 1.4115e-05 1.3438e-06 7.4179e-01
------------------------------------------------------------------
>>> Results
Status: Solved
Iterations: 100
Optimal objective: 148
Runtime: 0.793s (792.95ms)
0.893204 seconds (778.20 k allocations: 611.945 MiB, 3.94% gc time, 3.15% compilation time: 100% of which was recompilation)
We use MLE of Gamma distribution to illustrate some rudiments of nonlinear programming (NLP) in Julia.
Let \(x_1,\ldots,x_m\) be a random sample from the gamma density \[
f(x) = \Gamma(\alpha)^{-1} \beta^{\alpha} x^{\alpha-1} e^{-\beta x}
\] on \((0,\infty)\). The loglikelihood function is \[
L(\alpha, \beta) = m [- \ln \Gamma(\alpha) + \alpha \ln \beta + (\alpha - 1)\overline{\ln x} - \beta \bar x],
\] where \(\overline{x} = \frac{1}{m} \sum_{i=1}^m x_i\) and \(\overline{\ln x} = \frac{1}{m} \sum_{i=1}^m \ln x_i\).
Many optimization algorithms involve taking derivatives of the objective function. The ForwardDiff.jl package implements automatic differentiation. For example, to compute the derivative and Hessian of the log-likelihood with data x at α=1.0 and β=1.0.
Total number of variables............................: 2
variables with only lower bounds: 2
variables with lower and upper bounds: 0
variables with only upper bounds: 0
Total number of equality constraints.................: 0
Total number of inequality constraints...............: 0
inequality constraints with only lower bounds: 0
inequality constraints with lower and upper bounds: 0
inequality constraints with only upper bounds: 0
Number of Iterations....: 18
(scaled) (unscaled)
Objective...............: 2.8242686979100025e-05 -2.8242686979100026e+03
Dual infeasibility......: 2.0271409244855300e-09 2.0271409244855301e-01
Constraint violation....: 0.0000000000000000e+00 0.0000000000000000e+00
Variable bound violation: 0.0000000000000000e+00 0.0000000000000000e+00
Complementarity.........: 5.0000201478351835e-13 5.0000201478351834e-05
Overall NLP error.......: 2.0271409244855300e-09 2.0271409244855301e-01
Number of objective function evaluations = 24
Number of objective gradient evaluations = 19
Number of equality constraint evaluations = 0
Number of inequality constraint evaluations = 0
Number of equality constraint Jacobian evaluations = 0
Number of inequality constraint Jacobian evaluations = 0
Number of Lagrangian Hessian evaluations = 0
Total seconds in IPOPT = 0.031
EXIT: Optimal Solution Found.
MLE (JuMP):
α = α, β = β
Objective value: -2824.2686979100026
α = 2.7440644044519273, β = 2.8109598545638588
MLE (Distribution package):
Gamma{Float64}(α=2.7442896626235687, θ=2.8108030427510164)