/
intro.Rmd
275 lines (207 loc) · 7.1 KB
/
intro.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
---
title: Introduction
author: Anqi Fu and Balasubramanian Narasimhan
date: '2017-10-29'
categories:
- Simple Least Squares
slug: cvxr_intro
---
Consider a simple linear regression problem where it is desired to
estimate a set of parameters using a least squares criterion.
We generate some synthetic data where we know the model completely,
that is
$$ Y = X\beta + \epsilon $$
where $Y$ is a $100\times 1$ vector, $X$ is a $100\times 10$ matrix,
$\beta = [-4,\ldots ,-1, 0, 1, \ldots, 5]$ is a $10\times 1$ vector, and
$\epsilon \sim N(0, 1)$.
```{r}
set.seed(123)
n <- 100
p <- 10
beta <- -4:5 # beta is just -4 through 5.
X <- matrix(rnorm(n * p), nrow=n)
colnames(X) <- paste0("beta_", beta)
Y <- X %*% beta + rnorm(n)
```
Given the data $X$ and $Y$, we can estimate the $\beta$ vector using
`lm` function in R that fits a standard regression model.
```{r}
ls.model <- lm(Y ~ 0 + X) # There is no intercept in our model above
m <- matrix(coef(ls.model), ncol = 1)
rownames(m) <- paste0("$\\beta_{", 1:p, "}$")
library(kableExtra)
knitr::kable(m, format = "html") %>%
kable_styling("striped") %>%
column_spec(1:2, background = "#ececec")
```
These are the least-squares estimates and can be seen to be reasonably
close to the original $\beta$ values -4 through 5.
## The `CVXR` formulation
The `CVXR` formulation states the above as an optimization problem:
$$
\begin{array}{ll}
\underset{\beta}{\mbox{minimize}} & \|y - X\beta\|_2^2,
\end{array}
$$
which directly translates into a problem that `CVXR` can solve as shown
in the steps below.
- Step 0. Load the `CVXR` library
```{r}
suppressWarnings(library(CVXR, warn.conflicts=FALSE))
```
- Step 1. Define the variable to be estimated
```{r}
betaHat <- Variable(p)
```
- Step 2. Define the objective to be optimized
```{r}
objective <- Minimize(sum((Y - X %*% betaHat)^2))
```
Notice how the objective is specified using functions such as `sum`,
`*%*` and `^`, that are familiar to R users despite that fact that
`betaHat` is no ordinary R expression but a `CVXR` expression.
- Step 3. Create a problem to solve
```{r}
problem <- Problem(objective)
```
- Step 4. Solve it!
```{r}
result <- solve(problem)
```
- Step 5. Extract solution and objective value
```{r, echo = FALSE}
solution <- result$getValue(betaHat)
cat(sprintf("Objective value: %f\n", result$value))
```
We can indeed satisfy ourselves that the results we get matches that
from `lm`.
```{r}
m <- cbind(result$getValue(betaHat), coef(ls.model))
colnames(m) <- c("CVXR est.", "lm est.")
rownames(m) <- paste0("$\\beta_{", 1:p, "}$")
knitr::kable(m, format = "html") %>%
kable_styling("striped") %>%
column_spec(1:3, background = "#ececec")
```
## Wait a minute! What have we gained?
On the surface, it appears that we have replaced one call to `lm` with
at least five or six lines of new R code. On top of that, the code
actually runs slower, and so it is not clear what was really achieved.
So suppose we knew that the $\beta$s were nonnegative and we wish to
take this fact into account. This
is
[nonnegative least squares regression](https://en.wikipedia.org/wiki/Non-negative_least_squares) and
`lm` would no longer do the job.
In `CVXR`, the modified problem merely requires the addition of a constraint to the
problem definition.
```{r}
problem <- Problem(objective, constraints = list(betaHat >= 0))
result <- solve(problem)
m <- matrix(result$getValue(betaHat), ncol = 1)
rownames(m) <- paste0("$\\beta_{", 1:p, "}$")
knitr::kable(m, format = "html") %>%
kable_styling("striped") %>%
column_spec(1:2, background = "#ececec")
```
We can verify once again that these values are comparable to those
obtained from another R package,
say [nnls]( https://CRAN.R-project.org/package=nnls).
```{r}
library(nnls)
nnls.fit <- nnls(X, Y)$x
```
```{r}
m <- cbind(result$getValue(betaHat), nnls.fit)
colnames(m) <- c("CVXR est.", "nnls est.")
rownames(m) <- paste0("$\\beta_{", 1:p, "}$")
knitr::kable(m, format = "html") %>%
kable_styling("striped") %>%
column_spec(1:3, background = "#ececec")
```
## Okay that was cool, but...
As you no doubt noticed, we have done nothing that other R packages
could not do.
So now suppose further, for some extraneous reason, that the sum of
$\beta_2$ and $\beta_3$ is known to be negative and but all other
$\beta$s are positive.
It is clear that this problem would not fit into any standard
package. But in `CVXR`, this is easily done by adding a few
constraints.
To express the fact that $\beta_2 + \beta_3$ is negative, we construct
a row matrix with zeros everywhere, except in positions 2 and 3 (for
$\beta_2$ and $\beta_3$ respectively).
```{r}
A <- matrix(c(0, 1, 1, rep(0, 7)), nrow = 1)
colnames(A) <- paste0("$\\beta_{", 1:p, "}$")
knitr::kable(A, format = "html") %>%
kable_styling("striped") %>%
column_spec(1:10, background = "#ececec")
```
The sum constraint is nothing but
$$
A\beta < 0
$$
which we express in R as
```{r}
constraint1 <- A %*% betaHat < 0
```
_NOTE_: The above constraint can also be expressed simply as
```{r, eval = FALSE}
constraint1 <- betaHat[2] + betaHat[3] < 0
```
but it is easier working with matrices in general with `CVXR`.
For the positivity for rest of the variables, we construct a $10\times
10$ matrix $A$ to have 1's along the diagonal everywhere except rows 2
and 3 and zeros everywhere.
```{r}
B <- diag(c(1, 0, 0, rep(1, 7)))
colnames(B) <- rownames(B) <- paste0("$\\beta_{", 1:p, "}$")
knitr::kable(B, format = "html") %>%
kable_styling("striped") %>%
column_spec(1:11, background = "#ececec")
```
The constraint for positivity is
$$
B\beta > 0
$$
which we express in R as
```{r}
constraint2 <- B %*% betaHat > 0
```
Now we are ready to solve the problem just as before.
```{r}
problem <- Problem(objective, constraints = list(constraint1, constraint2))
result <- solve(problem)
```
And we can get the estimates of $\beta$.
```{r}
m <- matrix(result$getValue(betaHat), ncol = 1)
rownames(m) <- paste0("$\\beta_{", 1:p, "}$")
knitr::kable(m, format = "html") %>%
kable_styling("striped") %>%
column_spec(1:2, background = "#ececec")
```
This demonstrates the chief advantage of `CVXR`: _flexibility_. Users
can quickly modify and re-solve a problem, making our package ideal
for prototyping new statistical methods. Its syntax is simple and
mathematically intuitive. Furthermore, `CVXR` combines seamlessly with
native R code as well as several popular packages, allowing it to be
incorporated easily into a larger analytical framework. The user is
free to construct statistical estimators that are solutions to a
convex optimization problem where there may not be a closed form
solution or even an implementation. Such solutions can then be
combined with resampling techniques like the bootstrap to estimate
variability.
## Further Reading
We hope we have whet your appetite. You may wish to
read [a longer introduction](/cvxr_examples/gentle-intro/)
with more examples.
We also have a number of [tutorial examples](/examples/)
available to study and mimic.
## Session Info
```{r}
sessionInfo()
```
## Source
[R Markdown](https://github.com/bnaras/cvxr_docs/blob/master/content/cvxr_examples/intro.Rmd)
## References