/
testing-dd-ffs.Rmd
363 lines (282 loc) · 13.8 KB
/
testing-dd-ffs.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
---
title: "Testing different distance decay functions on real-world data"
author: "Robin Lovelace"
output:
pdf_document:
fig_caption: yes
toc: yes
bibliography: ~/Documents/Transport.bib
---
```{r, echo=FALSE, include=FALSE}
pkgs <- c("dplyr", "gdata", "tidyr", "ggmap", "grid", "png", "knitr")
lapply(pkgs, library, character.only = TRUE)
opts_knit$set(root.dir = "../")
```
# Introduction
The aim of this document is to test various distance decay functions against
real data in order to select the most appropriate for modelling modal shift:
the process by which people shift their travel habits from one mode of transport
to another.
# Data
We use a variety of datasets for this study. Primarily, we use data on distance
vs *clc* (current level of cycling) derived from the census (Fig. 1).
```{r, fig.cap="The relationship between distance and current level of cycling amongst 8 different groups."}
f <- "/home/robin/Dropbox/DfT bid/Data analysis/Test_DD/TestPlanck_150303/150304_SegmentationCompare_8cat.xlsx"
nts_seg <- read.xls(f, sheet = 2) # load in the .xlsx file with dist:pcycle values
nts_seg <- rename(nts_seg, dist = X) # rename the "X" column as dist (miles)
ntss <- gather(nts_seg, segment, clc, -dist)
(p1 <- ggplot(aes(x = dist), data = ntss) + geom_line(aes(y = clc)) +
facet_wrap(~ segment))
```
# Polynomial functions
## A linear model
The simplest model to fit to the data is a linear model. For illustrative
purposes we will fit a linear model to the data presented in Fig. 1,
with different intercepts and gradients for each of the groups (Fig. 2):
```{r, fig.cap="Linear model (red lines) fitted to the data, with intercept and gradient parameters estimated for each group."}
# nb: the '*' means estimate all par
m1 <- lm(clc ~ dist * segment, data = ntss)
ntss$m1 <- m1$fitted.values
p1 + geom_line(aes(y = m1$fitted.values), color = "red")
```
The intercepts and gradients for each group are as follows:
```{r}
summary(m1)
```
The above numbers are equations that describe the relationship between
distance and *clc* for each group. In the `Mal_Young_NC` group, for example,
$$
clc ~ (0.0941 - 0.0682) + (-0.00377 + 0.00301) * dist
$$
Let's double-check this makes sense:
```{r, fig.cap="Demonstration of the meaning of the parameters produced by the 'summary()' function for the linear model (m1) for the group 'Mal_Young_NC'.", fig.height=3, fig.width=4}
mync <- filter(ntss, segment == "Mal_Young_NC")
mync$m1 <- (0.0941 - 0.0682) + (-0.00377 + 0.00301) * mync$dist
plot(mync$dist, mync$clc)
lines(mync$dist, mync$m1)
```
Considering the linear model is so simple, an adjusted R squared value of
0.58 is not bad!
Now we will progress to fit slightly more complicated polynomial models.
## Cubic polynomial models
The results of the cubic models are displayed in Fig. 4.
```{r, fig.cap="Different versions of the cubic polynomial distance decay function fitted to the data with per-covariate parameters estimated for linear, square, cubic and all power terms (red, green, blue and yellow lines respectively)."}
m2 <- lm(clc ~ dist * segment + I(dist^2) + I(dist^3), data = ntss)
m3 <- lm(clc ~ dist + I(dist^2) * segment + I(dist^3), data = ntss)
m4 <- lm(clc ~ dist + I(dist^2) + I(dist^3) * segment, data = ntss)
m5 <- lm(clc ~ dist * segment + I(dist^2) * segment + I(dist^3) *
segment, data = ntss)
p1 + geom_line(aes(y = m2$fitted.values), color = "red") +
geom_line(aes(y = m3$fitted.values), color = "green") +
geom_line(aes(y = m4$fitted.values), color = "blue") +
geom_line(aes(y = m5$fitted.values), color = "yellow", size = 3, alpha = 0.5)
```
Note that there are different ways to fit parameters to the model: we can change
one parameter value for every group, or we can change many. In the finat model
presented in yellow if Fig. 4, we changed all 4 parameters in response to every
group. Thus we have calculated 32 parameter values! This is not a problem: we
can extract each formula from the coefficients. Lets extract them for the
`Fem_Old_NC` group, for example:
```{r}
c5 <- coefficients(m5)
c5[grep("Fem_Old_NC", names(c5))]
```
```{r, echo=FALSE, eval=FALSE}
# Which model fits best
summary(m1)
summary(m2)
summary(m3)
summary(m4)
summary(m5)
```
Of the cubic models fitted, the one with 32 parameters (8 for each parameter in
the general model) fits by far the best with the data, with an adjusted R-squared
value of 0.89.
From the preceeding analysis, it is clear that a 4 parameter polynomial model
fits sufficiently well for modelling: after all, we are interested in a simple
way to increase the update of cycling not *fit curves to the current rate of cycling*.
However, let's exploring how much better the curve can fit our data,
which are admitedly noisy for the small groups.
## Cubic polynomial with cube and square root terms
The model fit (in terms of adjusted R-squared) is improved slightly by adding
sqare-root, cubic-root and square- cubic-root terms, from 0.89 to 0.91 (0.914,
0.913, and 0.917 respectively). Interestingly,
the model fit barely changes between square-root, cube-root or cube- and square-root
versions of the model and introduces some
unexpected inflection points (wiggles in the red line) in the fitted
curve (Fig. 5). This implies that a 6 parameter model is overkill
and unnecessarily complex. Can the problems of overfitting and overcomplexity
be resolved by using a different distance decay function?
That is the subject of the next section.
```{r, fig.cap="6 parameter cubic polynomial model with cube and square root terms", fig.height=3, fig.width=4}
m6 <- lm(clc ~ dist * segment + I(dist^2) * segment + I(dist^3) *
segment + I(dist^0.333) * segment, data = ntss)
m7 <- lm(clc ~ dist * segment + I(dist^2) * segment + I(dist^3) *
segment + I(dist^0.5) * segment, data = ntss)
m8 <- lm(clc ~ dist * segment + I(dist^2) * segment + I(dist^3) *
segment + I(dist^0.5) * segment + I(dist^0.333) + segment, data = ntss)
p1 + geom_line(aes(y = m8$fitted.values), color = "red")
# summary(m6) ; summary(m7); summary(m8)
length(coefficients(m6))
```
# Fitting to the log of clc
Because of the non-linearity evident in distance decay, fitting to the log
of the cycling level may be appropriate. A problem with this approach is that
it fails to capture the fact that the rate of cycling can peak with a distance
above 0. This could be problematic with respect to cycling's interaction with
walking but, as long there is a sufficient number of short trips in the
"training" data, this should not be a serious problem. A potential solution
would be to cap the probability of cycling at a specific level. Using
the log-square root function in a logit model could also solve this issue.
```{r, echo=FALSE}
# TODO: fit to clc = log(d)
# pcycle = a * exp(-k * d)
```
$$
clc = \alpha e^{\beta d}
$$
$$
log(clc) = log(\alpha) + \beta d
$$
This fits reasonably well with the data...
$$
clc = \alpha e^{\beta d + \gamma d^{1/2}}
$$
$$
log(clc) = log(\alpha) + \beta d + \gamma d^{1/2}
$$
```{r, fig.cap="Log-linear approaches to distance decay with 2 and 3 parameter models (red and green lines respectively)."}
ntss$clc[ntss$clc == 0] <- 0.0001
m11 <- lm(log(clc) ~ dist * segment, data = ntss)
m12 <- lm(log(clc) ~ dist * segment + I(dist^2) * segment, data = ntss, )
p1 + geom_line(aes(y = exp(m11$fitted.values)), color = "red") +
geom_line(aes(y = exp(m12$fitted.values)), color = "green") + ylim(c(0,0.15))
```
```{r, echo=FALSE}
# Testing what happens when the distance goes very high
xtest <- mutate(ntss, dist = dist^2)
predm12 <- predict(object = m12, newdata = xtest)
pred12 <- lm(log(clc) ~ dist * segment + I(dist^0.5) * segment, data = xtest)
p12 <- glm(log(clc) ~ dist * segment + I(dist^0.5) * segment, data = ntss)
p1 + geom_line(aes(y = exp(m11$fitted.values)), color = "red") +
geom_line(aes(y = exp(predm12)), color = "green") + ylim(c(0,0.15))
p1 + geom_line(aes(y = exp(m11$fitted.values)), color = "red") +
geom_line(aes(x = dist^2, y = exp(p12$fitted.values)), color = "green") + ylim(c(0,0.15))
```
As can be seen from the output of the log-linear-square-root model,
the parameters change in a predictable way to changes in the shape of the distance
decay curve:
```{r}
summary(m12)
```
```{r, echo=FALSE, eval=FALSE}
summary(m11) # model fit - not shown
summary(m12) # model fit - not shown
summary(m13) # model fit - not shown
# m14 <- lm(log(clc) ~ dist + I(dist^2) * segment, data = ntss)
# summary(m14) # model fit - not shown
# geom_line(aes(y = m13$m$fitted()), color = "blue")
# Models not understood
# m12 <- lm(clc ~ -1 + dist / I(exp(dist)) * segment, data = ntss)
# m11 <- lm(clc ~ dist / I(exp(dist)) * segment, data = ntss)
# m12 <- lm(log(clc) ~ dist + I(exp(dist)) * segment, data = ntss)
# m13 <- lm(log(clc) ~ dist + I(log(dist)) * segment, data = ntss)
```
As shown in Fig. 7, the parameters of the 'log linear square-root' are meaningful.
The intercept, log-lin and log-sqrt terms affect the intercept, short-term distance
decay and longer-term distance decay respectively. The function fits the census flow data quite well.
```{r, fig.cap="Impacts of changing the parameters of the 'log-linear-square-root' function. The green lines represent increases of 0.25 times the the original values derived from the Leeds dataset and the red lines represent -0.1 times the original value.", echo=FALSE}
grid.raster(readPNG("figures/log-sqrt-params.png"))
```
## Simple exponential decay
A feature present in all relationships between frequency and distance
of trip is decay to zero as distance increases to infinity. This is especially
the case with active travel modes such as cycling. Therefore some kind of
exponential decay function may be suitable. This section fits various
functions that have an exponential decay term to the data to see which perform
well.
The simplest type of exponential decay model is one in which a linear
term (dominant in over short distances) is combined with an exponential decay:
$$
clc = \frac{\beta_1 dist}{exp(\beta_2)}
$$
Where each $\beta$ term is estimated for each group, as with the twin parameter
linear model illustrated Fig. 1. We can fit this to the data using
*non-linear regression* (e.g. by using `nls()` in R) but this seems likely to
make parameter estimation more complicated.
```{r, echo=FALSE}
# `nls()` can also be used...
# m13 <- nls(clc ~ a * dist / exp(I(dist) * b), data = ntss,
# start = list(a = 1, b = 1))
# m14 <- gnls(clc ~ a * dist / exp(I(dist) * b) * segment, data = ntss,
# start = list(a = 1, b = 1))
```
# Fitting the distance decay functions to binary data with logit models
Using the functional forms for distance decay as an input to
predict binary outcomes is relatively simple.
"We can transform the output of a linear regression to be
suitable for probabilities by using a logit link
function" [@Manning2007]:
$$
logit(p) = ln \left( \frac{p}{1 - p} \right)
$$
We can use this knowledge to fit the aformentioned models to raw NTS
data, with "Cycle trip" as a binary variable, for example using
`family = "binomial"` in R's `glm()` function.
# References
```{r, eval=FALSE, echo=FALSE}
trips <- read.csv("~/Dropbox/DfT bid/Data analysis/Test_DD/150303_TestPlanck_Data.csv")
head(trips)
summary(trips$distance)
trips <- trips[trips$distance < 20.5, ]
plot(trips$distance, trips$meancycle) #
mod_logcub <- lm(log(meancycle) ~ distance + I(distance^2) + I(distance^3), data = trips)
x <- 0:20
dfx <- data.frame(distance = x)
y1 <- exp(predict(mod_logcub, dfx))
summary(mod_logcub)
lines(0:20, y1)
dd_planck <- function(x, a, b, k){
(a * (b + x)) / (exp(k * (b + x)))
}
mod_plank1 <- nls(meancycle ~ dd_planck(distance, a, b, k), control = list(minFactor = 0.000001, warnOnly = TRUE),
data = trips, start = list(a = 0.1, b = 0.1, k = 0.1), )
y2 <- predict(mod_plank1, dfx) # not fitting correctly
lines(x, y2)
# The Planck function does not fit the data well - seemingly because we are not
# using binned data.
# The relationship between $logit(clc)$ and $clc$ is displayed in Fig. 7.
# Because we can bin the data directly
#
# ```{r, fig.cap="The logit function illustrated with clc values."}
# plot(ntss$clc, log(ntss$clc/ (1 - ntss$clc)))
## Binning the data
# There are different ways of binning the data. This may affect model fit.
```
```{r, eval=FALSE, echo=FALSE}
brks <- c(0, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 9.5, 12.5, 15.5, 20.5)
binned_dist <- cut(trips$distance, breaks = brks, include.lowest = T)
gflow <- data.frame(interval = levels(binned_dist))
gflow$dist <- aggregate(distance ~ binned_dist, mean, data = trips)[[2]]
gflow$mbike <- aggregate(meancycle ~ binned_dist, mean, data = trips)[[2]]
gflow$total <- aggregate(meancycle ~ binned_dist, length, data = trips)[[2]]
modw2_logcub <- lm(log(mbike) ~ dist + I(dist^2) + I(dist^3),
weights = total, data = gflow)
plot(gflow$dist, gflow$mbike)
summary(modw2_logcub)
plot(gflow$dist, gflow$mbike, ylim = c(0, 0.03))
lines(gflow$dist, exp(modw2_logcub$fitted.values))
# write.csv(gflow, "/tmp/binned-results.csv")
mod_plank1 <- nls(mbike ~ dd_planck(dist, a, b = 0, k), weights = total,
data = gflow, start = list(a = 0.01, k = 0.1), control = list(minFactor = 0.000001, warnOnly = T))
mod_plank2 <- nls(mbike ~ dd_planck(dist, a, b = 3, k), weights = total,
data = gflow, start = list(a = 0.01, k = 0.1), control = list(minFactor = 0.000001, warnOnly = T))
mod_plank3 <- nls(mbike ~ dd_planck(dist, a, b = 0, k) + b, weights = total,
data = gflow, start = list(a = 0.01, k = 0.1, b = 0), control = list(minFactor = 0.000001, warnOnly = T))
# mod_plank4 <- nls(mbike ~ dd_planck(dist, a, b, k) + c, weights = total,
# data = gflow, start = list(a = 0.01, k = 0.1, b = 0, c = 0.01), control = list(minFactor = 0.000001, warnOnly = T))
lines(gflow$dist, mod_plank1$m$fitted(), col = "blue")
lines(gflow$dist, mod_plank2$m$fitted(), col = "green")
lines(gflow$dist, mod_plank3$m$fitted(), col = "red")
# lines(gflow$dist, mod_plank4$m$fitted(), col = "orange")
```