-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathSupervised.Rmd
1922 lines (1706 loc) · 73.3 KB
/
Supervised.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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "Introduction to supervised changepoint detection"
author: Toby Dylan Hocking, McGill University, Montreal, Canada
output:
html_document:
toc: true
toc_depth: 2
---
See the GitHub repository for links to source code and exercises:
https://github.com/tdhock/change-tutorial
Before executing the code in this tutorial Rmd, make sure to install
the required packages:
```{r packages}
packages.R <- if(file.exists("packages.R")){
"packages.R"
}else{
"https://raw.githubusercontent.com/tdhock/change-tutorial/master/packages.R"
}
source(packages.R)
options(width=100)
```
# What is the difference between unsupervised and supervised changepoint detection?
There are two features of a data set that make it possible to do a
supervised changepoint analysis:
* The data consist of **several sequences** with similar signal/noise
patterns, which are treated as separate changepoint detection
problems.
* Some data sequences have **labels** which indicate specific regions
where the model should predict presence or absence of changepoints.
The goal of the supervised analysis is to find a model that learns
from the limited labeled data, and provides accurate changepoint
predictions for all of the data (a different number of changepoints
for each separate data sequence).
## Neuroblastoma data set
We will use the neuroblastoma data set to explore supervised
changepoint detection.
```{r neuroblastoma}
data(neuroblastoma, package="neuroblastoma")
str(neuroblastoma)
lapply(neuroblastoma, head, 10)
```
The neuroblastoma data set consists of two data.frames:
* profiles contains the noisy data (logratio), which is approximate
DNA copy number (measured at chromosome, position), for a particular
patient (profile.id). Every unique combination of (profile.id,
chromosome) defines a separate multiple changepoint detection
problem. The logratio measures how many copies of each part of the
human genome are present in the patient's tumor. Normally there are
two copies of each chromosome (logratio=0), but in cancer samples
there can be gains (changes up) and losses (changes down) of
specific regions or entire chromosomes.
* annotations contains the labels, which indicate presence
(breakpoint) or absence (normal) of changepoints in specific regions
(profile.id, chromosome, min, max) of the data.
These data come from children who were treated at the Institut Curie
(Paris, France). For six children we also have follow-up data on
whether they recovered (ok) or had a relapse, several years after
treatment:
```{r clinical}
followup <- data.frame(
profile.id=paste(c(10, 8, 4, 6, 11, 1)),
status=c("ok", "relapse", "relapse", "ok", "ok", "relapse"))
followup
```
## Unsupervised: no labels, model selection via theory
When there are no labels, the input for a changepoint analysis just
uses the noisy DNA copy number data in
`neuroblastoma$profiles$logratio`. We begin by selecting the profiles
of the six patients for which we have follow-up data.
```{r six}
rownames(followup) <- followup$profile.id
followup$status.profile <- with(followup, paste(status, profile.id))
some.ids <- rownames(followup)
library(data.table)
someProfiles <- function(all.profiles){
some <- subset(all.profiles, paste(profile.id) %in% some.ids)
status.profile <- followup[paste(some$profile.id), "status.profile"]
some$status.profile <- ifelse(
is.na(status.profile), paste(some$profile.id), status.profile)
data.table(some)
}
neuroblastoma.dt <- data.table(neuroblastoma$profiles)
## neuroblastoma.dt[, logratio.norm := logratio/mad(logratio), by=list(
## profile.id, chromosome)]
neuroblastoma.dt[, logratio.norm := logratio]
six.profiles <- someProfiles(neuroblastoma.dt)
```
For these six patients, the total number of separate changepoint
detection problems is 24 chromosomes x 6 patients = 144 problems. We
plot each problem below in a separate facet (panel).
```{r plotProfiles, fig.width=10}
library(ggplot2)
gg.unsupervised <- ggplot()+
ggtitle("unsupervised changepoint detection = only noisy data sequences")+
theme(
panel.spacing=grid::unit(0, "lines"),
panel.border=element_rect(fill=NA, color="grey50")
)+
facet_grid(status.profile ~ chromosome, scales="free", space="free_x")+
geom_point(aes(position/1e6, logratio),
data=six.profiles,
shape=1)+
scale_x_continuous(
"position on chromosome (mega bases)",
breaks=c(100, 200))+
scale_y_continuous(
"logratio (approximate DNA copy number)",
limits=c(-1,1)*1.1)
print(gg.unsupervised)
```
Note the facet titles on the right:
* The top three profiles are "ok" because those children
completely recovered.
* The bottom three profiles are "relapse" because the
neuroblastoma cancer came back, and required another treatment at
the hospital.
**Question:** can you visually identify any differences between the
"ok" and "relapse" profiles?
How to choose the number of changepoints? In the unsupervised setting,
our only option is to use theoretical/statistical arguments, which
give information criteria such as Aikaike Information Criterion (AIC,
penalty=2) or Bayesian/Schwarz Information Criterion (BIC/SIC,
penalty=log n). More on this later.
## Supervised: learn a penalty function with minimal incorrect labels
In supervised changepoint detection, there are labels which indicate
presence and absence of changepoints in particular data subsets. For
the same set of 6 profiles, we superimpose the labels in the plot
below.
```{r plotLabels, fig.width=10}
six.labels <- someProfiles(neuroblastoma$annotations)
change.colors <- c(
"1change"="#ff7d7d",
breakpoint="#a445ee",
normal="#f6c48f"
)
gg.supervised <- gg.unsupervised+
ggtitle(paste(
"supervised changepoint detection = data + labels",
"that indicate specific regions with or without changepoints"))+
penaltyLearning::geom_tallrect(aes(
xmin=min/1e6, xmax=max/1e6, fill=annotation),
alpha=0.5,
color=NA,
data=six.labels)+
scale_fill_manual("label", values=change.colors)+
theme(legend.position="bottom")
print(gg.supervised)
```
**New function:** `geom_tallrect` is like `geom_rect` but the ymin is
always the bottom of the panel and the ymax is always the top of the
panel. These are useful for drawing labeled intervals of x values.
It is clear from this plot that the neuroblastoma data satisfy the two
criteria which are necessary for a supervised changepoint analysis:
* The data consist of **several sequences** with similar signal/noise
patterns, which are treated as separate changepoint detection
problems.
* Some data sequences have **labels** which indicate specific regions
where the model should predict presence or absence of changepoints.
As we will see later in the tutorial, the labels can be used for
choosing the best model and parameters. The main idea is that the
changepoint model should be consistent with the labels:
* Every breakpoint/positive label is a region where the model should
predict at least one changepoint. If the model predicts no
changepoints in a region with a breakpoint label, that is considered
a false negative.
* Every normal/negative label is a region where the model should
predict no changepoints. If the model predicts one or more
changepoints in a region with a normal label, that is considered a
false positive.
* The overall goal is find a changepoint model that minimizes the
number of incorrectly predicted labels, which is defined as the sum
of false positives and false negatives.
## Label error of an unsupervised changepoint model
In this section we show that typical unsupervised changepoint models
result in prediction errors with respect to the labels in the
neuroblastoma data. We begin by using the `changepoint::cpt.mean`
function to compute an unsupervised changepoint model for each data
sequence. To compute the number of incorrect labels later, make sure
to save a description of the model in a "tidy" data.frame
(observations on rows and variables on columns). In the code below we
* fit the model inside `by=list(status.profile, chromosome)` which adds
those two columns to the resulting `data.table`.
* add the `pen.name` column to identify the model.
* use the `changes` list column to save the changepoint positions (in
the same units as the label positions: bases on the chromosome).
```{r unsupervised-models}
pen.name <- "SIC0"
(unsupervised.models <- six.profiles[, {
fit.pelt <- changepoint::cpt.mean(
logratio.norm, penalty=pen.name, method="PELT")
end <- fit.pelt@cpts
before.change <- end[-length(end)]
after.change <- before.change+1L
data.table(
pen.name,
pen.value=fit.pelt@pen.value,
changes=list(
as.integer((position[before.change]+position[after.change])/2)
))
}, by=list(profile.id, status.profile, chromosome)])
```
Next, we convert the list column `changes` to tall format (one row for
each changepoint).
```{r unsupervised-changes}
(unsupervised.changes <- unsupervised.models[, data.table(
change=changes[[1]]
), by=list(profile.id, status.profile, chromosome, pen.name)])
```
**New function:** we now introduce the `penaltyLearning::labelError`
function, which computes the number of incorrect labels for a set of
predicted changepoints. Its inputs are 3 data.frames:
* `models` one row per changepoint model.
* `labels` one row for each label, with columns for label location and
type.
* `changes` one row for each predicted changepoint, with a column for
the predicted changepoint position.
```{r unsupervised-error-list}
unsupervised.error.list <- penaltyLearning::labelError(
unsupervised.models, six.labels, unsupervised.changes,
problem.vars=c("status.profile", "chromosome"),
model.vars="pen.name",
change.var="change")
```
The result of `labelError` is a list of two data tables:
* `model.errors` has one row per (sequence,model), with the total
number of incorrect labels. We use these totals in the `ggtitle` of
the plot below.
* `label.errors` has one row per (sequence,model,label), with the
fp/fn status of each label. We use these to visualize false negative
and false positive predictions using the `geom_tallrect` with
`aes(linetype=status)` below.
```{r gg-unsupervised-bic, fig.width=10}
gg.supervised+
theme(legend.box="horizontal")+
unsupervised.error.list$model.errors[, ggtitle(paste0(
"Unsupervised ", pen.name, " penalty has ",
sum(errors),
" incorrect labels: ",
sum(fp), " FP + ",
sum(fn), " FN"))]+
geom_vline(aes(
xintercept=change/1e6),
color="green",
size=1,
linetype="dashed",
data=unsupervised.changes)+
geom_tallrect(aes(
xmin=min/1e6, xmax=max/1e6, linetype=status),
fill=NA,
data=unsupervised.error.list$label.errors)+
scale_linetype_manual("error type", values=c(
correct=0,
"false negative"=3,
"false positive"=1))
```
Note that in the plot above we also plotted the predicted changepoints
using a green dashed `geom_vline`. Labels with inconsistent
changepoints are shown with a black border in the `geom_tallrect`,
with `scale_linetype_manual` to show the type of prediction error:
* **False positives** are labels with too many predicted changepoints,
drawn with a solid black border (none here but we will see some
later).
* **False negatives** are labels with too few predicted changepoints,
drawn with a dotted black border.
* **Correct** labels with no border have an acceptable number of
predicted changepoints.
**Remark:** the result above (BIC/SIC predicts too few changepoints,
resulting in false negatives) is specific to the neuroblastoma data
set. However, in general you can expect that unsupervised penalty
functions will commit changepoint detection errors which are visually
obvious. This is the main motivation of supervised changepoint
analysis: we can use labels to learn a penalty function with improved
changepoint detection accuracy.
**Exercise 1 during class:** try changing the `pen.name` variable
to another theretically-motivated unsupervised penalty. Other options
from `help(cpt.mean)` are SIC (without a zero), MBIC, AIC, and
Hannan-Quinn. Can you find a penalty with improved changepoint
detection accuracy? Also try changing the `some.ids` variable (to some
profile IDs from 1 to 603) to see the changepoints and label errors
for another set of profiles.
## Creating labels via visual inspection
To quickly create labels for many data sequences, I recommend using a
GUI in which you can use the mouse to draw label rectangles on the
scatterplots. I wrote
[annotate_regions.py](https://pypi.python.org/pypi/annotate_regions/1.0)
for labeling the neuroblastoma data set, and
[SegAnnDB](https://github.com/tdhock/SegAnnDB) for labeling general
DNA copy number profile data. You may want to write another GUI for
your particular data -- make sure it supports visualizing the data
sets and interactive labeling.
Even if you don't have GUI software, you can always just plot the data
in R, and then write the labels in the R code. Begin by plotting one
data set by itself to see the details of the signal and noise.
```{r zoom}
zoom.profile <- 4 #Exercise: change this value!
zoom.chromosome <- 14 #Exercise: change this value!
zoom.pro <- neuroblastoma.dt[
profile.id==zoom.profile & chromosome==zoom.chromosome]
zoom.gg <- ggplot()+
geom_point(aes(position/1e6, logratio),
data=zoom.pro,
shape=1)+
scale_y_continuous(
"logratio (approximate DNA copy number)")
print(zoom.gg)
```
Based on your visual interpretation of the plot above, you can create
a set of labels.
* For each region that contains at least one changepoint, create a
"breakpoint" label (no predicted changes inside is a false
negative).
* For each region that contains no changepoints, create a "normal"
label (one or more predicted changes inside is a false positive).
* For each region that contains exactly one changepoint, create a
"1change" label (no predicted changes inside is a false negative,
and two or more is a false positive).
The region for each label can be as small or as large as you want.
Because the goal of learning is to minimize the number of incorrectly
predicted labels, it is important to make sure that each label is a
correct representation of the changepoint model you want. Avoid
labeling any regions for which you are not sure about the label. Save
your labels to a data.frame with the label type and positions, as
below.
```{r manual-label-fun}
label <- function(min, max, annotation){
data.frame(
profile.id=paste(zoom.profile),
chromosome=paste(zoom.chromosome),
min, max, annotation)
}
zoom.labels <- rbind(# Exercise: change these values!
label(70e6, 90e6, "1change"),
label(20e6, 60e6, "normal"))
zoom.gg.lab <- zoom.gg+
penaltyLearning::geom_tallrect(aes(
xmin=min/1e6, xmax=max/1e6, fill=annotation),
alpha=0.5,
color=NA,
data=zoom.labels)+
scale_fill_manual("label", values=change.colors)
print(zoom.gg.lab)
```
The plot above shows the noisy data along with the labels. Note that
it is possible to have multiple labels per data sequence, even though
that is not the case for the neuroblastoma data set.
# A typical supervised changepoint analysis
In this section we explain how to perform a supervised changepoint
analysis on a labeled data set.
## Overview of supervised changepoint computations
A typical supervised changepoint analysis consists of the
following computations:
* [Changepoint models of increasing complexity](#changepoint-models-of-increasing-complexity).
For each of several labeled segmentation problems (data sequences
that are separate but have a similar signal/noise pattern), use your
favorite changepoint detection package to compute a *sequence* of
models of increasing complexity (say from 0 to 20 changepoints).
* [Label error](#label-error). Use `penaltyLearning::labelError` to
compute the number of incorrect labels for each labeled segmentation
problem and each changepoint model. The goal of learning is to
minimize the number of incorrectly predicted labels.
* [Model selection](#model-selection). Use
`penaltyLearning::modelSelection` to compute the exact path of
models that will be selected for every possible non-negative penalty
value.
* [Outputs](#outputs). Use `penaltyLearning::targetIntervals` to
compute a target interval of log(penalty) values that predicts the
minimum number of incorrect labels for each segmentation
problem. Create a target interval matrix (one row for each
segmentation problems, 2 columns) which can be used as the output in
the supervised machine learning problem.
* [Inputs](#inputs). Compute a feature matrix (segmentation problems x
features) using `penaltyLearning::featureMatrix`. Or do it yourself
using simple statistics of each segmentation problem (quantiles,
mean, number of data points, estimated variance, etc).
* [Learning and prediction](#learning-and-prediction). Use
`survival::survreg` or `penaltyLearning::IntervalRegressionCV` to
learn a penalty function.
* [Evaluation](#evaluation). use `penaltyLearning::ROChange` to
compute ROC curves using labels in a test set (that were not used
for training). The AUC (area under the ROC curve) and the percent
incorrect labels in the test set can be used to evaluate the
prediction accuracy of your model.
The mathematical details are described in
[our ICML'13 paper, Learning Sparse Penalties for Change-point Detection using Max Margin Interval Regression](http://proceedings.mlr.press/v28/hocking13.html).
## Changepoint models of increasing complexity
To begin we will perform the supervised changepoint computations on
just one of the labeled neuroblastoma data sequences,
```{r zoom-gg-lab}
zoom.gg.lab <- ggplot()+
geom_point(aes(position/1e6, logratio),
data=zoom.pro,
shape=1)+
scale_y_continuous(
"logratio (approximate DNA copy number)")+
penaltyLearning::geom_tallrect(aes(
xmin=min/1e6, xmax=max/1e6, fill=annotation),
alpha=0.5,
color=NA,
data=zoom.labels)+
scale_fill_manual("label", values=change.colors)
print(zoom.gg.lab)
```
We use the code below to compute a sequence of maximum likelihood
Gaussian models with $s\in\{1,\dots,7\}$ segments. In contrast, a
typical unsupervised analysis will include computation of *one*
changepoint model. In supervised analysis we need to compute *a
sequence of changepoint models of increasing complexity* in order to
determine which are consistent and inconsistent with the
labels. Remember the goal of the machine learning is to predict a
model with complexity consistent with the labels (minimize the number
of incorrectly predicted labels).
**New function:** `Segmentor3IsBack::Segmentor` computes maximum
likelihood segmentations from 1 to Kmax segments. Inputs are the data
sequence to segment, the likelihood (model=2 means normal/Gaussian),
and the maximum number of segments (Kmax). For a supervised
changepoint analysis, Kmax should be rather large, but how do you know
if it is large enough? You should check to make sure there is at least
one model with a false positive (a labeled region with too many
predicted changepoints), if that is possible (not possible for data
sequences with only breakpoint labels). These false positives in the
training labels/models are used to learn a penalty function that avoids
predicting too many changepoints. More details below in the
[Outputs](#outputs) section.
```{r zoomSegmentor}
max.segments <- 7
(fit <- Segmentor3IsBack::Segmentor(
zoom.pro$logratio.norm, model=2, Kmax=max.segments))
```
The Segmentor `fit` object is an S4 class with slots
* `breaks` an integer matrix of end position of each segment.
* `parameters` a numeric matrix of the mean of each segment.
Next, we convert the model to tidy format (a `data.frame` with one row
per segment). The code below is specific to the `Segmentor` function;
if you use a different changepoint detection package/function, you
will have to write some other code to tidy the data.
```{r zoom-segs}
zoom.segs.list <- list()
zoom.loss.vec <- rep(NA, max.segments)
for(n.segments in 1:max.segments){
end <- fit@breaks[n.segments, 1:n.segments]
data.before.change <- end[-n.segments]
data.after.change <- data.before.change+1
pos.before.change <- as.integer(
(zoom.pro$position[data.before.change]+
zoom.pro$position[data.after.change])/2)
start <- c(1, data.after.change)
chromStart <- c(zoom.pro$position[1], pos.before.change)
chromEnd <- c(pos.before.change, max(zoom.pro$position))
seg.mean.vec <- fit@parameters[n.segments, 1:n.segments]
zoom.segs.list[[n.segments]] <- data.table(
profile.id=paste(zoom.profile),
chromosome=paste(zoom.chromosome),
n.segments, # model complexity.
start, # in data points.
end,
chromStart, # in bases on chromosome.
chromEnd,
mean=seg.mean.vec)
data.mean.vec <- rep(seg.mean.vec, end-start+1)
stopifnot(length(data.mean.vec)==nrow(zoom.pro))
zoom.loss.vec[n.segments] <- sum((zoom.pro$logratio.norm-data.mean.vec)^2)
}
(zoom.segs <- do.call(rbind, zoom.segs.list))
```
Above we show the data.table of optimal segment means. Below we
compute the data.table of predicted changepoint positions, then plot
the models.
```{r zoom-changes}
(zoom.changes <- zoom.segs[1 < start, data.table(
profile.id, chromosome, n.segments,
changepoint=chromStart)])
zoom.gg.models <- zoom.gg.lab+
theme(
panel.spacing=grid::unit(0, "lines"),
panel.border=element_rect(fill=NA, color="grey50")
)+
facet_grid(n.segments ~ .)+
geom_vline(aes(
xintercept=changepoint/1e6),
data=zoom.changes,
color="green",
size=1,
linetype="dashed")
print(zoom.gg.models)
```
The plot above shows a panel for each model from 1 to 7 segments (0 to
6 changepoints). Each changepoint is drawn using a green dashed
`geom_vline`.
For more details about the `Segmentor` function, read the references
below. To save time during class we will skip to the next section,
"Label error."
* Let there be $n$ separate data sequences to segment. For example in
the previous section we plotted $n=144$ data sequences, each a
separate changepoint detection problem.
* For any data sequence $i\in\{1,\dots,n\}$, let $d_i$ be the number
of data points in data sequence $i$, and let $\mathbf z_i\in\mathbb
R^{d_i}$ be the vector of data points to segment for that sequence.
* The Segment Neighborhood problem with $s$ segments for data sequence
$i$ is to find the most likely $s-1$ changepoints:
$$
\operatorname{minimize}_{\mathbf m\in\mathbb R^{d_i}}
\sum_{j=1}^{d_i} \ell(z_{ij}, m_j)
\text{ subject to}
\sum_{j=1}^{d_i-1} I(m_{j} \neq m_{j+1})=s-1.
$$
For the Normal homoscedastic model we have
* the optimization variable $\mathbf m = (m_1 \cdots m_{d_i})$ is a
vector of $d_i$ real-valued segment mean variables.
* the loss function $\ell$ is the square loss $\ell(z,m)=(z-m)^2$.
* the indicator function $I$ is 1 for every change-point where
$m_{j} \neq m_{j+1}$, and 0 otherwise.
* $\lambda>0$ is a non-negative penalty constant.
* the objective function is the total loss over all $d_i$ data points,
which is convex.
* the constraint is that the mean $\mathbf m$ must have exactly $s-1$
changes, which is non-convex.
* overall the optimization problem is non-convex, which means that
gradient-based algorithms are not guaranteed to compute the global
minimum. However the dynamic programming algorithms discussed below
can be used to compute the global minimum in a reasonable amount of
time.
A few references about the algorithm implemented in the `Segmentor` function:
* the "Segment Neighborhood" problem was originally described by
[Auger and Lawrence (1989)](https://www.ncbi.nlm.nih.gov/pubmed/2706400). They
proposed an $O(S_{\text{max}} d^2)$ algorithm for computing the most
likely models with $s\in\{1,\dots,S_{\text{max}}\}$ segments, for
$d$ data points. An R implementation of their algorithm is available
as `changepoint::cpt.mean(method="SegNeigh")` but it is very slow
for large $d$, due to the quadratic time complexity.
* [Rigaill (2010) discovered a Pruned Dynamic Programming Algorithm (PDPA)](https://arxiv.org/abs/1004.0887)
which solves the same "Segment Neighborhood" problem. Its
$O(S_{\text{max}}d\log d)$ time complexity makes it much faster for
larger data sets. The original R implementation `cghseg:::segmeanCO`
only works for the Gaussian/normal likelihood.
* [Cleynen et al (2014) generalized the PDPA to other loss/likelihood models](https://almob.biomedcentral.com/articles/10.1186/1748-7188-9-6). Their
R function `Segmentor3IsBack::Segmentor` implements the
$O(S_{\text{max}}d\log d)$ PDPA for Poisson, Normal homoscedastic
(uniform variance -- change in mean), Negative Binomial, Normal
Heteroscedastic (uniform mean -- change in variance), and
Exponential likelihood models.
**Exercise after class:** instead of using `Segmentor` to compute a
sequence of models, try using
`changepoint::cpt.mean(penalty="CROPS")`,
[arXiv:1412.3617](https://arxiv.org/abs/1412.3617). Then re-do the
rest of the analyses below. Another option is
`cghseg:::segmeanCO`. Using any of these three packages you should be
able to get the same results.
## Label error
Next, we compute the number of incorrect labels for each model, using
the `penaltyLearning::labelError` function that we saw above. We then
plot the label errors.
```{r zoomlabelerror}
zoom.models <- data.table(
profile.id=paste(zoom.profile),
chromosome=paste(zoom.chromosome),
loss=zoom.loss.vec,
n.segments=as.numeric(1:max.segments))
zoom.error.list <- penaltyLearning::labelError(
zoom.models,
zoom.labels,
zoom.changes,
change.var="changepoint",
problem.vars=c("profile.id", "chromosome"))
zoom.gg.models+
penaltyLearning::geom_tallrect(aes(
xmin=min/1e6,
xmax=max/1e6,
linetype=status),
data=zoom.error.list$label.errors,
fill=NA)+
scale_linetype_manual("error type", values=c(
correct=0,
"false negative"=3,
"false positive"=1))
```
It is clear from the plot above that each model has a different number
of labels which are correctly predicted. Models with too few
changepoints cause false negatives, and models with too many
changepoints cause false positives. However there is a subset of
models with minimal incorrect labels. The goal of a supervised
changepoint detection algorithm is to predict one of those models.
## Model selection
Rather than using a regression model to directly predict the
integer-valued number of segments/changepoints, we will instead learn
a regression model that predicts the real-valued log(penalty). The
model selection function is a mapping from penalty values to model
size (in segments/changepoints).
Notice that `zoom.models` contains a `loss` column, which is the sum
of squared residuals of each model. Below we use that to compute the
models that will be selected for every possible penalty
value.
**New function:** In the code below we use the
`penaltyLearning::modelSelection` function, which takes as input a
`data.frame` with one row per changepoint model. There should be at
least the following columns (but there can be others):
* IDs for the data sequence (here, `profile.id` and `chromosome`).
* complexity, such as number of changepoints/segments. This column
name can be specified via the `complexity` argument, as below.
* loss, such as the residual sum of squares or negative log
likelihood. This should decrease as model complexity increases, and
the column name can be specified via the `loss` argument (default is
`"loss"` which is present in `zoom.models` so no need to specify in
the code below).
The output is a data.frame with one row per model that is selected for
at least one penalty value. There are columns for the min/max penalty
that will select each model, as shown below.
```{r zoomSelection}
print(zoom.models)
(zoom.selection <- penaltyLearning::modelSelection(
zoom.models, complexity="n.segments"))
ggplot()+
geom_segment(aes(
min.log.lambda, n.segments,
xend=max.log.lambda, yend=n.segments),
size=1,
data=zoom.selection)+
xlab("log(penalty) = log(lambda)")+
scale_y_continuous(breaks=zoom.selection$n.segments)
```
We plot the model selection function in the figure above, which shows
that it is a piecewise constant non-increasing function. Intuitively,
the larger the penalty, the fewer the number of changepoints/segments (and vice
versa). More concretely, let $L_{i,s}$ be the loss (sum of squared
residuals) of the model with $s\in\{1,\dots,s_{\text{max}}\}$ segments
for data sequence $i$. The model selection function is defined for
every non-negative penalty $\lambda\geq 0$ as
$$
s_i^*(\lambda) = \text{arg min}_s L_{i,s} + \lambda s
$$
## Outputs
The output in the machine learning problem is an interval of
log(penalty) values that achieves minimum incorrect labels. Remember that
we have computed `zoom.error.list$model.errors` which contains the
number of incorrect labels $e_i(s)\in\{0,1,2,\dots\}$ for this data
sequence $i$ and every number of segments $s$. We can thus compute the
label error as function of the penalty,
$$
E_i(\lambda) = e_i[s^*_i(\lambda)].
$$
In R this computation amounts to a join with `zoom.selection` (which
came from `penaltyLearning::modelSelection`).
```{r zoomploterrors}
zoom.error.join <- zoom.error.list$model.errors[J(zoom.selection), on=list(
profile.id, chromosome, n.segments, loss)]
zoom.errors.tall <- data.table::melt(
zoom.error.join,
measure.vars=c("n.segments", "errors"))
zoom.gg.errors <- ggplot()+
geom_segment(aes(
min.log.lambda, value,
xend=max.log.lambda, yend=value),
size=1,
data=zoom.errors.tall)+
theme_bw()+
theme(panel.spacing=grid::unit(0, "lines"))+
facet_grid(variable ~ ., scales="free")+
scale_y_continuous("", breaks=0:max.segments)+
xlab("log(penalty) = log(lambda)")
print(zoom.gg.errors)
```
The code above plots the number of incorrect labels $E_i(\lambda)$,
clearly showing that it is a piecewise constant function that takes
integer values (like the 01 loss in binary classification). The goal
of the machine learning algorithm is to provide predictions that
minimize this function (on test data).
Below we compute the output for the machine learning problem, a target
interval of penalty values that yield changepoint models with minimal
incorrect labels.
**New function:** the `penaltyLearning::targetIntervals` function
computes the upper and lower limits of the target interval, which is
the largest range of log(penalty) values that results in minimum
incorrectly predicted labels. Its input parameter is a data.frame with
one row per model (from `penaltyLearning::modelSelection`), with an
additional column `errors` for the number of incorrect labels. The
`problem.vars` argument indicates the data sequence ID columns.
The function returns a data.table with one row per labeled data sequence,
with columns for the lower and upper bounds of the target interval
(`min.log.lambda`, `max.log.lambda`).
```{r zoomplottargets}
print(zoom.error.join)
(zoom.target <- penaltyLearning::targetIntervals(
zoom.error.join,
problem.vars=c("profile.id", "chromosome")))
zoom.target.tall <- data.table::melt(
zoom.target,
measure.vars=c("min.log.lambda", "max.log.lambda"),
variable.name="limit")[is.finite(value)]
zoom.gg.errors+
geom_text(aes(
ifelse(limit=="min.log.lambda", value-1, value+1),
errors+1,
label=paste(
"false",
ifelse(limit=="min.log.lambda", "positives", "negatives"),
"\ntoo",
ifelse(limit=="min.log.lambda", "many", "few"),
"changes"),
hjust=ifelse(
limit=="min.log.lambda", 0, 1)),
data=data.frame(zoom.target.tall, variable="errors"),
vjust=-1)+
geom_point(aes(
value,
errors,
fill=limit),
shape=21,
size=4,
data=data.frame(zoom.target.tall, variable="errors"))+
scale_fill_manual("limit", values=c(
min.log.lambda="black",
max.log.lambda="white"))+
theme(
legend.position="bottom",
legend.box="horizontal")
```
The plot above emphasizes the target interval, which is used as the
output in the machine learning problem:
* the black dot shows the lower limit of the target interval. If a
smaller log(penalty) is predicted, then there are too many changepoints (false
positives).
* the white dot shows the upper limit of the target interval. If a
larger log(penalty) is predicted, then there are too few
changepoints (false negatives).
The target interval is different for each labeled data sequence, as we
show below. We will compute the target interval for each of the
labeled data sequences in the six profiles from the beginning of the
tutorial. The first step is to compute changepoints and model
selection functions, which we do via a for loop over each data
sequence below.
```{r sixSegmentor}
six.problems.dt <- unique(six.profiles[, list(
profile.id, chromosome, status.profile)])
setkey(six.profiles, profile.id, chromosome)
six.segs.list <- list()
six.selection.list <- list()
for(problem.i in 1:nrow(six.problems.dt)){
meta <- six.problems.dt[problem.i,]
pro <- six.profiles[meta]
max.segments <- min(nrow(pro), 10)
fit <- Segmentor3IsBack::Segmentor(
pro$logratio.norm, model=2, Kmax=max.segments)
rss.vec <- rep(NA, max.segments)
for(n.segments in 1:max.segments){
end <- fit@breaks[n.segments, 1:n.segments]
seg.mean.vec <- fit@parameters[n.segments, 1:n.segments]
data.before.change <- end[-n.segments]
data.after.change <- data.before.change+1
pos.before.change <- as.integer(
(pro$position[data.before.change]+pro$position[data.after.change])/2)
start <- c(1, data.after.change)
chromStart <- c(pro$position[1], pos.before.change)
chromEnd <- c(pos.before.change, max(pro$position))
data.mean.vec <- rep(seg.mean.vec, end-start+1)
rss.vec[n.segments] <- sum((pro$logratio.norm-data.mean.vec)^2)
six.segs.list[[paste(problem.i, n.segments)]] <- data.table(
meta,
n.segments,
start,
end,
chromStart,
chromEnd,
mean=seg.mean.vec)
}
loss.dt <- data.table(
meta,
n.segments=1:max.segments,
loss=rss.vec)
six.selection.list[[problem.i]] <- penaltyLearning::modelSelection(
loss.dt, complexity="n.segments")
}
six.selection <- do.call(rbind, six.selection.list)
six.segs <- do.call(rbind, six.segs.list)
six.changes <- six.segs[1 < start]
```
Inside of each iteration of the loop above, we used
* `Segmentor3IsBack::Segmentor` to compute the optimal changepoint
models, saving the tidy result data.frame of segments to an element
of `six.segs.list`.
* `penaltyLearning::modelSelection` to compute the model selection
functions, saving the result to an element of `six.selection.list`.
Below, we use
* `penaltyLearning::labelError` to compute the number of incorrect
labels for each segmentation model.
* `penaltyLearning::targetIntervals` to compute the target interval
of penalty values for each labeled data sequence.
```{r sixPlotErrors}
six.error.list <- penaltyLearning::labelError(
six.selection, six.labels, six.changes,
problem.vars=c("profile.id", "chromosome"))
six.targets <- penaltyLearning::targetIntervals(
six.error.list$model.errors,
problem.vars=c("profile.id", "chromosome"))
ymax.err <- 1.2
six.targets.tall <- data.table::melt(
six.targets,
measure.vars=c("min.log.lambda", "max.log.lambda"),
variable.name="limit",
value.name="log.lambda")[is.finite(log.lambda)]
six.gg.errors <- ggplot()+
theme_bw()+
theme(panel.spacing=grid::unit(0, "lines"))+
facet_grid(profile.id ~ chromosome, labeller=function(df){
if("chromosome" %in% names(df))
df$chromosome <- paste0("chr", df$chromosome)
if("profile.id" %in% names(df))
df$profile.id <- paste("profile", df$profile.id)
df
})+
geom_segment(aes(
min.log.lambda, errors,
xend=max.log.lambda, yend=errors),
size=1,
data=six.error.list$model.errors)+
geom_point(aes(
log.lambda,
errors,
fill=limit),
shape=21,
size=3,
alpha=0.5,
data=six.targets.tall)+
scale_fill_manual("limit", values=c(
min.log.lambda="black",
max.log.lambda="white"))+
theme(
legend.position="bottom",
legend.box="horizontal")+
scale_y_continuous(
"incorrectly predicted labels",
limits=c(0,ymax.err),
breaks=c(0,1))+
scale_x_continuous(
"predicted log(penalty) = log(lambda)")
print(six.gg.errors)
```
The plot above shows the error function and target intervals for each
labeled data sequence. Each column of panels/facets represents a
different chromosome, and each row represents a different
profile/patient. It is clear from the plot above that a model with
minimal incorrect labels will predict a different penalty for each
data sequence.
**Question:** discuss with your neighbor for 1 minute, why is there
only one limit per data sequence? (only one target limit point per
panel in the plot above)
**Exercise 2 during class:** create a set of labels via visual
inspection, and visualize how changing the labels affects the
computation of the target interval.
## Inputs
To train a machine learning model, we first need to compute a vector
$\mathbf x_i\in\mathbb R^p$ of exactly $p$ features for each data sequence
$i$.
We then learn a function $f(\mathbf x_i)=\log\lambda_i\in\mathbb R$.
To compute a feature matrix, use the code below.
**New function:** the `penaltyLearning::featureMatrix` function
computes a feature matrix for some data sequences. Inputs are a
data.frame of data sequences (`six.profiles` below), along with column
names of IDs (`problem.vars`) and data (`data.var`). Output is a
numeric matrix with one row per data sequence and one column per
feature.
```{r sixFeatureMatrix}
print(six.profiles)
feature.mat <- penaltyLearning::featureMatrix(
six.profiles,
problem.vars=c("profile.id", "chromosome"),
data.var="logratio")
str(feature.mat)
```
The feature matrix is 144 rows (one for each data sequence) by 365
columns/features. Which features should we use to predict log(penalty)
values? If you have a lot of labels, you can use
`penaltyLearning::IntervalRegressionCV` which uses L1-regularization
to automatically select relevant features -- more details in the next
section.
For now we will discuss the simpler unsupervised BIC/SIC
model, which corresponds to solving the following changepoint optimization problem.
$$
\operatorname{minimize}_{\mathbf m\in\mathbb R^{d_i}}
\sum_{j=1}^{d_i}
\ell(z_{ij}, m_j) +