forked from tidyverse/datascience-box
-
Notifications
You must be signed in to change notification settings - Fork 0
/
u4-d01-language-of-models.html
668 lines (532 loc) · 19.8 KB
/
u4-d01-language-of-models.html
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
<!DOCTYPE html>
<html lang="" xml:lang="">
<head>
<title>The language of models</title>
<meta charset="utf-8" />
<script src="libs/header-attrs/header-attrs.js"></script>
<link href="libs/font-awesome/css/all.min.css" rel="stylesheet" />
<link href="libs/font-awesome/css/v4-shims.min.css" rel="stylesheet" />
<link href="libs/panelset/panelset.css" rel="stylesheet" />
<script src="libs/panelset/panelset.js"></script>
<link rel="stylesheet" href="../xaringan-themer.css" type="text/css" />
<link rel="stylesheet" href="../slides.css" type="text/css" />
</head>
<body>
<textarea id="source">
class: center, middle, inverse, title-slide
# The language of models
## <br><br> College of the Atlantic
---
class: middle
# What is a model?
---
## Modelling
- Use models to explain the relationship between variables and to make predictions
- For now we will focus on **linear** models (but remember there are *many* *many* other types of models too!)
.pull-left[
<img src="u4-d01-language-of-models_files/figure-html/unnamed-chunk-2-1.png" width="100%" style="display: block; margin: auto;" />
]
.pull-right[
<img src="u4-d01-language-of-models_files/figure-html/unnamed-chunk-3-1.png" width="100%" style="display: block; margin: auto;" />
]
---
class: middle
# Data: Paris Paintings
---
## Paris Paintings
```r
pp <- read_csv("data/paris-paintings.csv", na = c("n/a", "", "NA"))
```
- Source: Printed catalogues of 28 auction sales in Paris, 1764 - 1780
- Data curators Sandra van Ginhoven and Hilary Coe Cronheim (who were PhD students in the Duke Art, Law, and Markets Initiative at the time of putting together this dataset) translated and tabulated the catalogues
- 3393 paintings, their prices, and descriptive details from sales catalogues over 60 variables
---
## Auctions today
.center[
<iframe width="840" height="473" src="https://www.youtube.com/embed/apaE1Q7r4so" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
]
---
## Auctions back in the day
<img src="img/old-auction.png" width="65%" style="display: block; margin: auto;" />
.footnote[
.small[
Pierre-Antoine de Machy, Public Sale at the Hôtel Bullion, Musée Carnavalet, Paris (18th century)
]
]
---
## Paris auction market
<img src="img/auction-trend-paris.png" width="60%" style="display: block; margin: auto;" />
.footnote[
.small[
Plot credit: Sandra van Ginhoven
]
]
---
## Départ pour la chasse
<img src="img/depart-pour-la-chasse.png" width="65%" style="display: block; margin: auto;" />
---
## Auction catalog text
.pull-left[
<img src="img/auction-catalogue.png" width="60%" style="display: block; margin: auto;" />
]
.pull-right[
.small[
Two paintings very rich in composition, of a beautiful execution, and whose merit is very remarkable, each 17 inches 3 lines high, 23 inches wide; the first, painted on wood, comes from the Cabinet of Madame la Comtesse de Verrue; it represents a departure for the hunt: it shows in the front a child on a white horse, a man who gives the horn to gather the dogs, a falconer and other figures nicely distributed across the width of the painting; two horses drinking from a fountain; on the right in the corner a lovely country house topped by a terrace, on which people are at the table, others who play instruments; trees and fabriques pleasantly enrich the background.
]
]
---
<img src="img/painting1.png" width="60%" style="display: block; margin: auto;" /><img src="img/painting2.png" width="60%" style="display: block; margin: auto;" /><img src="img/painting3.png" width="60%" style="display: block; margin: auto;" />
---
```r
pp %>%
filter(name == "R1777-89a") %>%
glimpse()
```
.small[
.pull-left[
```
## Rows: 1
## Columns: 61
## $ name <chr> "R1777-89a"
## $ sale <chr> "R1777"
## $ lot <chr> "89"
## $ position <dbl> 0.3755274
## $ dealer <chr> "R"
## $ year <dbl> 1777
## $ origin_author <chr> "D/FL"
## $ origin_cat <chr> "D/FL"
## $ school_pntg <chr> "D/FL"
## $ diff_origin <dbl> 0
## $ logprice <dbl> 8.575462
## $ price <dbl> 5300
## $ count <dbl> 1
## $ subject <chr> "D\u008epart pour la chasse"
## $ authorstandard <chr> "Wouwerman, Philips"
## $ artistliving <dbl> 0
## $ authorstyle <chr> NA
## $ author <chr> "Philippe Wouwermans"
## $ winningbidder <chr> "Langlier, Jacques for Poullain, Anto~
## $ winningbiddertype <chr> "DC"
## $ endbuyer <chr> "C"
...
```
]
.pull-right[
```
...
## $ Interm <dbl> 1
## $ type_intermed <chr> "D"
## $ Height_in <dbl> 17.25
## $ Width_in <dbl> 23
## $ Surface_Rect <dbl> 396.75
## $ Diam_in <dbl> NA
## $ Surface_Rnd <dbl> NA
## $ Shape <chr> "squ_rect"
## $ Surface <dbl> 396.75
## $ material <chr> "bois"
## $ mat <chr> "b"
## $ materialCat <chr> "wood"
## $ quantity <dbl> 1
## $ nfigures <dbl> 0
## $ engraved <dbl> 0
## $ original <dbl> 0
## $ prevcoll <dbl> 1
## $ othartist <dbl> 0
## $ paired <dbl> 1
## $ figures <dbl> 0
## $ finished <dbl> 0
...
```
]
]
---
class: middle
# Modeling the relationship between variables
---
## Heights
.small[
```r
ggplot(data = pp, aes(x = Height_in)) +
geom_histogram(binwidth = 5) +
labs(x = "Height, in inches", y = NULL)
```
<img src="u4-d01-language-of-models_files/figure-html/height-dist-1.png" width="60%" style="display: block; margin: auto;" />
]
---
## Widths
.small[
```r
ggplot(data = pp, aes(x = Width_in)) +
geom_histogram(binwidth = 5) +
labs(x = "Width, in inches", y = NULL)
```
<img src="u4-d01-language-of-models_files/figure-html/width-dist-1.png" width="60%" style="display: block; margin: auto;" />
]
---
## Models as functions
- We can represent relationships between variables using **functions**
- A function is a mathematical concept: the relationship between an output and one or more inputs
- Plug in the inputs and receive back the output
- Example: The formula `\(y = 3x + 7\)` is a function with input `\(x\)` and output `\(y\)`. If `\(x\)` is `\(5\)`, `\(y\)` is `\(22\)`, `\(y = 3 \times 5 + 7 = 22\)`
---
## Height as a function of width
.panelset[
.panel[.panel-name[Plot]
<img src="u4-d01-language-of-models_files/figure-html/unnamed-chunk-13-1.png" width="60%" style="display: block; margin: auto;" />
]
.panel[.panel-name[Code]
```r
ggplot(data = pp, aes(x = Width_in, y = Height_in)) +
geom_point() +
geom_smooth(method = "lm") +
labs(
title = "Height vs. width of paintings",
subtitle = "Paris auctions, 1764 - 1780",
x = "Width (inches)",
y = "Height (inches)"
)
```
```
## Warning: Removed 258 rows containing non-finite values
## (`stat_smooth()`).
```
```
## Warning: Removed 258 rows containing missing values
## (`geom_point()`).
```
]
]
---
## ... without the measure of uncertainty
.panelset[
.panel[.panel-name[Plot]
<img src="u4-d01-language-of-models_files/figure-html/unnamed-chunk-14-1.png" width="60%" style="display: block; margin: auto;" />
]
.panel[.panel-name[Code]
```r
ggplot(data = pp, aes(x = Width_in, y = Height_in)) +
geom_point() +
geom_smooth(method = "lm",
* se = FALSE) +
labs(
title = "Height vs. width of paintings",
subtitle = "Paris auctions, 1764 - 1780",
x = "Width (inches)",
y = "Height (inches)"
)
```
]
]
---
## ... with different cosmetic choices
.panelset[
.panel[.panel-name[Plot]
<img src="u4-d01-language-of-models_files/figure-html/unnamed-chunk-15-1.png" width="60%" style="display: block; margin: auto;" />
]
.panel[.panel-name[Code]
```r
ggplot(data = pp, aes(x = Width_in, y = Height_in)) +
geom_point() +
geom_smooth(method = "lm", se = FALSE,
* color = "#8E2C90", linetype = "dashed", size = 3) +
labs(
title = "Height vs. width of paintings",
subtitle = "Paris auctions, 1764 - 1780",
x = "Width (inches)",
y = "Height (inches)"
)
```
]
]
---
## Other smoothing methods: gam
.panelset[
.panel[.panel-name[Plot]
<img src="u4-d01-language-of-models_files/figure-html/unnamed-chunk-16-1.png" width="60%" style="display: block; margin: auto;" />
]
.panel[.panel-name[Code]
```r
ggplot(data = pp, aes(x = Width_in, y = Height_in)) +
geom_point() +
* geom_smooth(method = "gam",
se = FALSE, color = "#8E2C90") +
labs(
title = "Height vs. width of paintings",
subtitle = "Paris auctions, 1764 - 1780",
x = "Width (inches)",
y = "Height (inches)"
)
```
]
]
---
## Other smoothing methods: loess
.panelset[
.panel[.panel-name[Plot]
<img src="u4-d01-language-of-models_files/figure-html/unnamed-chunk-17-1.png" width="60%" style="display: block; margin: auto;" />
]
.panel[.panel-name[Code]
```r
ggplot(data = pp, aes(x = Width_in, y = Height_in)) +
geom_point() +
* geom_smooth(method = "loess",
se = FALSE, color = "#8E2C90") +
labs(
title = "Height vs. width of paintings",
subtitle = "Paris auctions, 1764 - 1780",
x = "Width (inches)",
y = "Height (inches)"
)
```
]
]
---
## Vocabulary
- **Response variable:** Variable whose behavior or variation you are trying to understand, on the y-axis
--
- **Explanatory variables:** Other variables that you want to use to explain the variation in the response, on the x-axis
--
- **Predicted value:** Output of the **model function**
- The model function gives the typical (expected) value of the response variable *conditioning* on the explanatory variables
--
- **Residuals:** A measure of how far each case is from its predicted value (based on a particular model)
- Residual = Observed value - Predicted value
- Tells how far above/below the expected value each case is
---
## Residuals
.panelset[
.panel[.panel-name[Plot]
<img src="u4-d01-language-of-models_files/figure-html/unnamed-chunk-18-1.png" width="60%" style="display: block; margin: auto;" />
]
.panel[.panel-name[Code]
.small[
```r
ht_wt_fit <- linear_reg() %>%
set_engine("lm") %>%
fit(Height_in ~ Width_in, data = pp)
ht_wt_fit_tidy <- tidy(ht_wt_fit$fit)
ht_wt_fit_aug <- augment(ht_wt_fit$fit) %>%
mutate(res_cat = ifelse(.resid > 0, TRUE, FALSE))
ggplot(data = ht_wt_fit_aug) +
geom_point(aes(x = Width_in, y = Height_in, color = res_cat)) +
geom_line(aes(x = Width_in, y = .fitted), size = 0.75, color = "#8E2C90") +
labs(
title = "Height vs. width of paintings",
subtitle = "Paris auctions, 1764 - 1780",
x = "Width (inches)",
y = "Height (inches)"
) +
guides(color = FALSE) +
scale_color_manual(values = c("#260b27", "#e6b0e7")) +
geom_text(aes(x = 0, y = 150), label = "Positive residual", color = "#e6b0e7", hjust = 0, size = 8) +
geom_text(aes(x = 150, y = 25), label = "Negative residual", color = "#260b27", hjust = 0, size = 8)
```
]
]
]
---
.question[
The plot below displays the relationship between height and width of paintings. The only difference from the previous plots is that it uses a smaller alpha value, making the points somewhat transparent. What feature is apparent in this plot that was not (as) apparent in the previous plots? What might be the reason for this feature?
]
<img src="u4-d01-language-of-models_files/figure-html/height-width-plot-alpha-1.png" width="55%" style="display: block; margin: auto;" />
---
## Landscape paintings
- Landscape painting is the depiction in art of landscapes – natural scenery such as mountains, valleys, trees, rivers, and forests, especially where the main subject is a wide view – with its elements arranged into a coherent
composition.<sup>1</sup>
- Landscape paintings tend to be wider than they are long.
- Portrait painting is a genre in painting, where the intent is to depict a human subject.<sup>2</sup>
- Portrait paintings tend to be longer than they are wide.
.footnote[
[1] Source: Wikipedia, [Landscape painting](https://en.wikipedia.org/wiki/Landscape_painting)
[2] Source: Wikipedia, [Portait painting](https://en.wikipedia.org/wiki/Portrait_painting)
]
---
## Multiple explanatory variables
.panelset[
.panel[.panel-name[Plot]
.pull-left-narrow[
.question[
How, if at all, does the relationship between width and height of paintings vary by whether or not they have any landscape elements?
]
]
.pull-right-wide[
<img src="u4-d01-language-of-models_files/figure-html/unnamed-chunk-19-1.png" width="80%" style="display: block; margin: auto;" />
]
]
.panel[.panel-name[Code]
```r
ggplot(data = pp, aes(x = Width_in, y = Height_in, color = factor(landsALL))) +
geom_point(alpha = 0.4) +
geom_smooth(method = "lm", se = FALSE) +
labs(
title = "Height vs. width of paintings, by landscape features",
subtitle = "Paris auctions, 1764 - 1780",
x = "Width (inches)",
y = "Height (inches)",
color = "landscape"
) +
scale_color_manual(values = c("#E48957", "#071381"))
```
]
]
---
## Extending regression lines
.panelset[
.panel[.panel-name[Plot]
<img src="u4-d01-language-of-models_files/figure-html/unnamed-chunk-20-1.png" width="65%" style="display: block; margin: auto;" />
]
.panel[.panel-name[Code]
```r
ggplot(data = pp, aes(x = Width_in, y = Height_in, color = factor(landsALL))) +
geom_point(alpha = 0.4) +
geom_smooth(method = "lm", se = FALSE,
* fullrange = TRUE) +
labs(
title = "Height vs. width of paintings, by landscape features",
subtitle = "Paris auctions, 1764 - 1780",
x = "Width (inches)",
y = "Height (inches)",
color = "landscape"
) +
scale_color_manual(values = c("#E48957", "#071381"))
```
]
]
---
## Models - upsides and downsides
- Models can sometimes reveal patterns that are not evident in a graph of the data. This is a great advantage of modeling over simple visual inspection of data.
- There is a real risk, however, that a model is imposing structure that is not really there on the scatter of data, just as people imagine animal shapes in the stars. A skeptical approach is always warranted.
---
## Variation around the model...
is just as important as the model, if not more!
*Statistics is the explanation of variation in the context of what remains unexplained.*
- The scatter suggests that there might be other factors that account for large parts of painting-to-painting variability, or perhaps just that randomness plays a big role.
- Adding more explanatory variables to a model can sometimes usefully reduce the size of the scatter around the model. (We'll talk more about this later.)
---
## How do we use models?
- Explanation: Characterize the relationship between `\(y\)` and `\(x\)` via *slopes* for numerical explanatory variables or *differences* for categorical explanatory variables
- Prediction: Plug in `\(x\)`, get the predicted `\(y\)`
---
## Acknowledgements
* This course builds on the materials from [Data Science in a Box](https://datasciencebox.org/) developed by Mine Çetinkaya-Rundel and are adapted under the [Creative Commons Attribution Share Alike 4.0 International](https://github.com/rstudio-education/datascience-box/blob/master/LICENSE.md)
</textarea>
<style data-target="print-only">@media screen {.remark-slide-container{display:block;}.remark-slide-scaler{box-shadow:none;}}</style>
<script src="https://remarkjs.com/downloads/remark-latest.min.js"></script>
<script>var slideshow = remark.create({
"ratio": "16:9",
"highlightLines": true,
"highlightStyle": "solarized-light",
"countIncrementalSlides": false
});
if (window.HTMLWidgets) slideshow.on('afterShowSlide', function (slide) {
window.dispatchEvent(new Event('resize'));
});
(function(d) {
var s = d.createElement("style"), r = d.querySelector(".remark-slide-scaler");
if (!r) return;
s.type = "text/css"; s.innerHTML = "@page {size: " + r.style.width + " " + r.style.height +"; }";
d.head.appendChild(s);
})(document);
(function(d) {
var el = d.getElementsByClassName("remark-slides-area");
if (!el) return;
var slide, slides = slideshow.getSlides(), els = el[0].children;
for (var i = 1; i < slides.length; i++) {
slide = slides[i];
if (slide.properties.continued === "true" || slide.properties.count === "false") {
els[i - 1].className += ' has-continuation';
}
}
var s = d.createElement("style");
s.type = "text/css"; s.innerHTML = "@media print { .has-continuation { display: none; } }";
d.head.appendChild(s);
})(document);
// delete the temporary CSS (for displaying all slides initially) when the user
// starts to view slides
(function() {
var deleted = false;
slideshow.on('beforeShowSlide', function(slide) {
if (deleted) return;
var sheets = document.styleSheets, node;
for (var i = 0; i < sheets.length; i++) {
node = sheets[i].ownerNode;
if (node.dataset["target"] !== "print-only") continue;
node.parentNode.removeChild(node);
}
deleted = true;
});
})();
(function() {
"use strict"
// Replace <script> tags in slides area to make them executable
var scripts = document.querySelectorAll(
'.remark-slides-area .remark-slide-container script'
);
if (!scripts.length) return;
for (var i = 0; i < scripts.length; i++) {
var s = document.createElement('script');
var code = document.createTextNode(scripts[i].textContent);
s.appendChild(code);
var scriptAttrs = scripts[i].attributes;
for (var j = 0; j < scriptAttrs.length; j++) {
s.setAttribute(scriptAttrs[j].name, scriptAttrs[j].value);
}
scripts[i].parentElement.replaceChild(s, scripts[i]);
}
})();
(function() {
var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
if (/^(https?:)?\/\//.test(links[i].getAttribute('href'))) {
links[i].target = '_blank';
}
}
})();
// adds .remark-code-has-line-highlighted class to <pre> parent elements
// of code chunks containing highlighted lines with class .remark-code-line-highlighted
(function(d) {
const hlines = d.querySelectorAll('.remark-code-line-highlighted');
const preParents = [];
const findPreParent = function(line, p = 0) {
if (p > 1) return null; // traverse up no further than grandparent
const el = line.parentElement;
return el.tagName === "PRE" ? el : findPreParent(el, ++p);
};
for (let line of hlines) {
let pre = findPreParent(line);
if (pre && !preParents.includes(pre)) preParents.push(pre);
}
preParents.forEach(p => p.classList.add("remark-code-has-line-highlighted"));
})(document);</script>
<script>
slideshow._releaseMath = function(el) {
var i, text, code, codes = el.getElementsByTagName('code');
for (i = 0; i < codes.length;) {
code = codes[i];
if (code.parentNode.tagName !== 'PRE' && code.childElementCount === 0) {
text = code.textContent;
if (/^\\\((.|\s)+\\\)$/.test(text) || /^\\\[(.|\s)+\\\]$/.test(text) ||
/^\$\$(.|\s)+\$\$$/.test(text) ||
/^\\begin\{([^}]+)\}(.|\s)+\\end\{[^}]+\}$/.test(text)) {
code.outerHTML = code.innerHTML; // remove <code></code>
continue;
}
}
i++;
}
};
slideshow._releaseMath(document);
</script>
<!-- dynamically load mathjax for compatibility with self-contained -->
<script>
(function () {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-MML-AM_CHTML';
if (location.protocol !== 'file:' && /^https?:/.test(script.src))
script.src = script.src.replace(/^https?:/, '');
document.getElementsByTagName('head')[0].appendChild(script);
})();
</script>
</body>
</html>