-
Notifications
You must be signed in to change notification settings - Fork 2
/
sf-arrests-predict.Rmd
536 lines (379 loc) · 18.3 KB
/
sf-arrests-predict.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
---
title: "Predicting And Mapping Arrest Types in San Francisco with LightGBM, R, ggplot2"
author: "Max Woolf (@minimaxir)"
date: "2017-02-08"
output:
html_notebook:
highlight: tango
mathjax: null
number_sections: yes
theme: spacelab
toc: yes
toc_float: yes
---
This R Notebook is the complement to my blog post [Predicting And Mapping Arrest Types in San Francisco with LightGBM, R, ggplot2](http://minimaxir.com/2017/02/predicting-arrests/).
This notebook is licensed under the MIT License. If you use the code or data visualization designs contained within this notebook, it would be greatly appreciated if proper attribution is given back to this notebook and/or myself. Thanks! :)
# Setup
Setup the R packages.
```{r setup}
library(lightgbm)
library(Matrix)
library(caret)
library(viridis)
library(ggmap)
library(randomcoloR)
source("Rstart.R")
```
```{r}
sessionInfo()
```
Import data, and only keep relevant columns. Filter on Arrests only.
The data must be randomized for `lightgbm` to give unbiased scores. Can do with dplyr's `sample_frac`.
```{r, include=FALSE}
# Converts "LARCENY/THEFT" to "Larceny/Theft", etc.
proper_case <- function(x) {
return (gsub("\\b([A-Z])([A-Z]+)", "\\U\\1\\L\\2" , x, perl = TRUE))
}
file_path <- "~/Downloads/SFPD_Incidents_-_from_1_January_2003.csv"
df <- read_csv(file_path, col_types="_c_ccc_c_nn__") %>%
filter(grepl("ARREST", Resolution)) %>%
mutate(Category = proper_case(Category))
```
```{r}
# seed for sample_frac()
set.seed(123)
df <- df %>% sample_frac()
df %>% head()
```
There are **`r df %>% nrow() %>% format(big.mark=',')`** arrests in this dataset.
# Feature Engineering
Engineer features for `lightgbm`.
## Month, Hour, Year
Year is # years since the lowest year (in this case, 2003, as noted in the dataset title)
```{r}
df <- df %>%
mutate(month = factor(substring(Date, 1, 2)),
hour = factor(substring(Time, 1, 2)),
year = as.numeric(substring(Date, 7, 10)))
df %>% select(month, hour, year) %>% head()
```
## Existing DayOfWeek to Factor
Change DayOfWeek to Factor.
Since column become encoded as numeric instead of categorical, encode order of numerals such that Saturday and Sunday are adjacent for proper `lte`/`gte` behavior.
```{r}
dow_order <- c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
df <- df %>%
mutate(DayOfWeek = factor(DayOfWeek, levels=dow_order))
df %>% select(DayOfWeek) %>% head()
```
## Category Indices
Map the category to an index. Labels must be zero-indexed.
```{r}
df <- df %>%
mutate(category_index = as.numeric(factor(Category)) - 1)
df %>% select(category_index, Category) %>% head()
```
# lightgbm Training
Use LightGBM's categorical data feature for optimial performance.
Use `caret` for train/test splitting since `createDataPartition` ensures balanced distribution of categories between train and test.
```{r}
# declare categorical feature names, if any
categoricals <- NULL
# proportion of data to train on
split <- 0.7
set.seed(123)
trainIndex <- createDataPartition(df$category_index, p = split, list = FALSE, times = 1)
dtrain <- lgb.Dataset((df %>% select(X, Y, hour, month, year, DayOfWeek) %>% data.matrix())[trainIndex,],
colnames = c("X", "Y", "hour", "month", "year", "DayOfWeek"),
categorical_feature = categoricals,
label = df$category_index[trainIndex], free_raw_data=T)
dtest <- lgb.Dataset.create.valid(dtrain,
(df %>% select(X, Y, hour, month, year, DayOfWeek) %>% data.matrix())[-trainIndex,],
label = df$category_index[-trainIndex])
params <- list(objective = "multiclass", metric = "multi_logloss")
valids <- list(test=dtest)
num_classes <- length(unique(df$category_index))
# preformat sizes for use in data visualizations later
train_size_format <- length(trainIndex) %>% format(big.mark=",")
test_size_format <- (df %>% nrow() - length(trainIndex)) %>% format(big.mark=",")
```
The size of the training set is **`r train_size_format`** and the size of the test set is **`r test_size_format`**.
```{r}
# determine elapsed runtime
system.time(
# training output not printed to notebook since spammy. (verbose = 0 + record = T)
bst <- lgb.train(params,
dtrain,
nrounds = 500,
valids,
num_threads = 4,
num_class = num_classes,
verbose = 0,
record = T,
early_stopping_rounds = 5,
categorical_feature = categoricals
)
)[3]
# multilogloss of final iteration on test set
paste("# Rounds:", bst$current_iter())
paste("Multilogloss of best model:", bst$record_evals$test$multi_logloss$eval %>% unlist() %>% tail(1))
```
Calculate variable importance. (note: takes awhile since single-threaded)
```{r}
df_imp <- tbl_df(lgb.importance(bst, percentage = TRUE))
df_imp
```
`preds` is a 1D vector of probabilities for each vector, of nrows x nclasses. Reshape accordingly and iterate through for the predicted label (label with the largest probability) and the corresponding probability.
```{r}
test <- (df %>% select(X, Y, hour, month, year, DayOfWeek) %>% data.matrix())[-trainIndex,]
preds_matrix <- predict(bst, test, reshape=T)
preds_cor <- cor(preds_matrix)
preds_matrix[1:2,]
# likely not most efficient method
results <- t(apply(preds_matrix, 1, function (x) {
max_index = which(x==max(x))
return (c(max_index-1, x[max_index]))
}))
```
```{r}
df_results <- data.frame(results, label_act = df$category_index[-trainIndex]) %>%
tbl_df() %>%
transmute(label_pred = X1, prod_pred = X2, label_act)
df_results %>% arrange(desc(prod_pred)) %>% head(20)
rm(preds_matrix)
```
Confusion matrix:
```{r}
cm <- confusionMatrix(df_results$label_pred, df_results$label_act)
data.frame(cm$overall)
```
# Visualizations
## Importance Bar Chart
```{r}
df_imp$Feature <- factor(df_imp$Feature, levels=rev(df_imp$Feature))
```
```{r}
plot <- ggplot(df_imp, aes(x=Feature, y=Gain)) +
geom_bar(stat="identity", fill="#34495e", alpha=0.9) +
geom_text(aes(label=sprintf("%0.1f%%", Gain*100)), color="#34495e", hjust=-0.25, family="Open Sans Condensed Bold", size=2.5) +
fte_theme() +
coord_flip() +
scale_y_continuous(limits = c(0, 0.4), labels=percent) +
theme(plot.title=element_text(hjust=0.5), axis.title.y=element_blank()) +
labs(title="Feature Importance for SF Arrest Type Model", y="% of Total Gain in LightGBM Model")
max_save(plot, "imp", "SF Open Data", h=2)
```
![](imp.png)
## Confusion Matrix
Plot the confusion matrix. Fortunately, matrix is already in long format.
```{r}
df_cm <- tbl_df(data.frame(cm$table))
df_cm %>% head(100)
```
Map the labels to the indices.
```{r}
# create mapping df
df_labels <- df %>%
select(category_index, Category) %>%
group_by(category_index, Category) %>%
summarize() %>%
ungroup() %>%
mutate(category_index = factor(category_index))
df_cm <- df_cm %>%
left_join(df_labels, by = c("Prediction" = "category_index")) %>%
left_join(df_labels, by = c("Reference" = "category_index")) %>%
rename(label_pred = Category.x, label_act = Category.y)
df_cm %>% head(100)
```
Plot the confusion matrix. Since 39 labels, confusion matrix will be large to fit all labels. Will also need to log-scale.
```{r}
# create a data frame of "correct values" to annotate
df_correct <- df_cm %>% filter(label_pred == label_act)
plot <- ggplot(df_cm, aes(x=label_act, y=label_pred, fill = Freq)) +
geom_tile() +
geom_point(data=df_correct, color="white", size=0.8) +
fte_theme() +
coord_equal() +
scale_x_discrete() +
scale_y_discrete() +
theme(legend.title = element_text(size=7, family="Open Sans Condensed Bold"), legend.position="top", legend.direction="horizontal", legend.key.width=unit(1.25, "cm"), legend.key.height=unit(0.25, "cm"), legend.margin=unit(0,"cm"), axis.text.x=element_text(angle=-90, size=6, vjust=0.5, hjust=0), axis.text.y=element_text(size=6), plot.title = element_text(hjust=1)) +
scale_fill_viridis(name="# of Preds", labels=comma, breaks=10^(0:4), trans="log10") +
labs(title = sprintf("Confusion Matrix between %s Predicted SFPD Arrest Labels and Actual", test_size_format),
x = "Actual Label of Arrest",
y = "Predicted Label of Arrest")
max_save(plot, "confusionMatrix", "SF Open Data", h=6, w=5, tall=T)
```
![](confusionMatrix.png)
## Correlations
Covert the `preds_cor` matrix into long (adapted from http://stackoverflow.com/a/26838774)
Requires reordering correlations for cleaner chart: http://www.sthda.com/english/wiki/ggplot2-quick-correlation-matrix-heatmap-r-software-and-data-visualization)
```{r}
dd <- as.dist((1-preds_cor)/2) # need to look into why this is necessary
hc <- hclust(dd, "centroid")
label_order <- hc$order
preds_cor_reorder <- preds_cor[label_order, label_order]
df_corr <- tbl_df(data.frame(Var1=c(row(preds_cor_reorder))-1, Var2=c(col(preds_cor_reorder))-1, value = c(preds_cor_reorder))) %>%
filter(Var1 <= Var2) %>%
mutate(Var1 = factor(Var1), Var2=factor(Var2))
df_corr %>% head(100)
```
Plot similar chart to confusion matrix.
```{r}
df_corr <- df_corr %>%
left_join(df_labels, by = c("Var1" = "category_index")) %>%
left_join(df_labels, by = c("Var2" = "category_index")) %>%
mutate(label1 = factor(Category.x), label2 = factor(Category.y))
# fix the label order to the reordered order from the hclust
levels(df_corr$label1) <- levels(df_corr$label1)[label_order]
levels(df_corr$label2) <- levels(df_corr$label2)[label_order]
plot <- ggplot(df_corr, aes(x=label1, y=label2, fill=value)) +
geom_tile() +
fte_theme() +
scale_x_discrete() +
scale_y_discrete() +
coord_fixed() +
theme(legend.title = element_text(size=7, family="Open Sans Condensed Bold"), legend.position="top", legend.direction="horizontal", legend.key.width=unit(1.25, "cm"), legend.key.height=unit(0.25, "cm"), legend.margin=unit(0,"cm"), panel.margin=element_blank(), axis.text.x=element_text(angle=-90, vjust=0.5, hjust=0), axis.title.y=element_blank(), axis.title.x=element_blank(), plot.title=element_text(hjust=1, size=6)) +
scale_fill_gradient2(high = "#2ecc71", low = "#e74c3c", mid = "white",
midpoint = 0, limit = c(-0.5,0.5),
name="Pearson\nCorrelation", breaks=pretty_breaks(8)) +
labs(title = sprintf("Correlations between Predicted Multiclass Probabilities of %s SFPD Arrest Category Labels", test_size_format))
max_save(plot, "correlationMatrix", "SF Open Data", h=6, w=5, tall=T)
```
![](correlationMatrix.png)
# Mapping Arrests
Reusing my mapping previous SF code: https://github.com/minimaxir/sf-arrests-when-where/blob/master/crime_data_sf.ipynb
```{r}
bbox = c(-122.516441,37.702072,-122.37276,37.811818)
map <- get_map(location = bbox, source = "stamen", maptype = "toner-lite")
```
Create 40000 million latitude/longitude points in SF to simulate locations (200 points on x axis, 2000 points on y axis)
```{r}
grid_size <- 200
df_points <- data.frame(expand.grid(X=seq(bbox[1], bbox[3], length.out=grid_size),
Y=seq(bbox[2], bbox[4], length.out=grid_size)
)
)
df_points %>% head()
df_points %>% nrow()
```
Predict arrest types at each point on April 15th, 2017, at 8 PM.
Populate data with same format of data (i.e. add month, hour, year, DayOfWeek). Does not require much customization. (DayOfWeek is a Factor, however)
```{r}
date_target <- as.POSIXct("2017-04-15 20:00:00")
df_points <- df_points %>%
mutate(hour = format(date_target, "%H"),
month = format(date_target, "%m"),
year = format(date_target, "%Y"),
DayOfWeek = which(levels(df$DayOfWeek) == format(date_target, "%A"))) %>%
data.matrix()
df_points %>% head()
```
```{r}
preds_matrix <- matrix(predict(bst, df_points), byrow=T, nrow(df_points), num_classes)
results <- t(apply(preds_matrix, 1, function (x) {
max_index = which(x==max(x))
return (c(max_index-1, x[max_index]))
}))
rm(preds_matrix)
```
```{r}
df_results <- data.frame(X=df_points[,1], Y=df_points[,2], label=factor(results[,1]), prob=results[,2]) %>%
tbl_df() %>%
left_join(df_labels, by=c("label" = "category_index")) %>%
mutate(Category = factor(Category))
df_results %>% head(20)
```
```{r}
plot <- ggmap(map) +
geom_raster(data = df_results %>% filter(Category != "Other Offenses"), aes(x=X, y=Y, fill=Category), alpha=0.8, size=0) +
coord_cartesian() +
fte_theme() +
scale_fill_brewer(palette = "Dark2") +
theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.title.x = element_blank(), axis.title.y = element_blank()) +
theme(legend.title = element_text(size=7, family="Open Sans Condensed Bold"), legend.position="right", legend.key.width=unit(0.5, "cm"), legend.key.height=unit(2, "cm"), legend.margin=margin(1,0,1,0), plot.title=element_text(hjust=0, size=11)) +
labs(title = sprintf("Locations of Predicted Types of Arrests in San Francisco on %s",
format(date_target, '%B %d, %Y at%l %p')))
max_save(plot, sprintf("crime-%s", format(date_target, '%Y-%m-%d-%H')), "SF Open Data", w = 6, h = 6, tall=T)
```
![](crime-2017-04-15-20.png)
## Map Animation
Set each label such that is has a consistent color.
```{r}
set.seed(123)
cols <- distinctColorPalette(num_classes)
names(cols) <- df_labels$Category
cols
```
Plot the map for 24 hours (convert to a GIF using external tools). Reuse code above to generate a map for given date/time + hour delta.
```{r}
system("mkdir -p map_ani")
create_arrest_map <- function(hour_delta, date) {
date_target <- date + hour_delta*60*60
grid_size <- 200
df_points <- data.frame(expand.grid(X=seq(bbox[1], bbox[3], length.out=grid_size),
Y=seq(bbox[2], bbox[4], length.out=grid_size)
)
)
df_points <- df_points %>%
mutate(hour = format(date_target, "%H"),
month = format(date_target, "%m"),
year = format(date_target, "%Y"),
DayOfWeek = which(levels(df$DayOfWeek) == format(date_target, "%A"))) %>%
data.matrix()
preds_matrix <- matrix(predict(bst, df_points), byrow=T, nrow(df_points), num_classes)
results <- t(apply(preds_matrix, 1, function (x) {
max_index = which(x==max(x))
return (c(max_index-1, x[max_index]))
}))
rm(preds_matrix)
df_results <- data.frame(X=df_points[,1], Y=df_points[,2], label=factor(results[,1]), prob=results[,2]) %>%
tbl_df() %>%
left_join(df_labels, by=c("label" = "category_index")) %>%
mutate(Category = factor(Category))
plot <- ggmap(map) +
geom_raster(data = df_results %>% filter(Category != "Other Offenses"), aes(x=X, y=Y, fill=Category), alpha=0.9, size=0) +
coord_cartesian() +
fte_theme() +
scale_fill_manual(values=cols) +
theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.title.x = element_blank(), axis.title.y = element_blank()) +
theme(legend.title = element_text(family="Open Sans Condensed Bold"), legend.position="right", legend.key.width=unit(0.5, "cm"), legend.margin=margin(0,0,0,0, "cm"), legend.key.height=unit(1, "cm"), plot.title=element_text(hjust=0, size=11), legend.text.align=0) +
labs(title = sprintf("Locations of Predicted Types of Arrests in San Francisco on %s",
format(date_target, '%B %d, %Y at %l %p')))
max_save(plot, sprintf("map_ani/crime-%s", format(date_target, '%Y-%m-%d-%H')), "SF Open Data", w = 6, h = 6, tall=T)
}
```
```{r}
base_date <- as.POSIXct("2017-03-14 06:00:00")
hour_deltas <- 0:23
x <- lapply(hour_deltas, create_arrest_map, base_date)
```
![](map_ani.gif)
# Code Which Did Not Work Out (One-Hot Encoding)
The categorical approach using LightGBM is better. Here is the former code using OHE.
Categorical Features must be factors for one-hot encoding.
Convert the factor variables into dummy variables: `model.matrix()` can do this in R natively. (via [Stack Overflow](http://stackoverflow.com/a/5048727))
```{r}
# model.matrix() adds an Intercept column: the "-1" removes it.
# Matrix converts the dense matrix to sparse (reduces memory footprint to 25%).
train <- Matrix(model.matrix(~ X + Y + hour + month + year + DayOfWeek - 1, df))
num_classes <- length(unique(df$category_index))
num_rows <- nrow(train)
train[1:10,]
```
The objective is `multi_logloss` since there are many classes. The `multiclass` objective returns a probability for each class.
Demo: https://github.com/Microsoft/LightGBM/blob/master/R-package/tests/testthat/test_basic.R#L29
```{r, include=FALSE}
set.seed(123)
bst <- lightgbm(data = train, label = df$category_index, nrounds = 200, nthreads=8, objective = "multiclass", metric="multi_logloss", num_class=num_classes, early_stopping_rounds = 3, nfolds=5, verbose = 0)
```
```{r}
preds <- predict(bst, train[1:2,])
preds
length(preds)
```
# LICENSE
The MIT License (MIT)
Copyright (c) 2017 Max Woolf
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.