library(qgam); library(MASS)
###
# Single quantile fit
###
# Calibrate learning rate on a grid
set.seed(5235)
tun <- tuneLearnFast(form = accel~s(times,k=20,bs="ad"),
data = mcycle,
qu = 0.2)
# Fit for quantile 0.2 using the best sigma
fit <- qgam(accel~s(times, k=20, bs="ad"), data = mcycle, qu = 0.2, lsig = tun$lsig)
pred <- predict(fit, se=TRUE)
plot(mcycle$times, mcycle$accel, xlab = "Times", ylab = "Acceleration",
ylim = c(-150, 80))
lines(mcycle$times, pred$fit, lwd = 1)
lines(mcycle$times, pred$fit + 2*pred$se.fit, lwd = 1, col = 2)
lines(mcycle$times, pred$fit - 2*pred$se.fit, lwd = 1, col = 2)
###
# Multiple quantile fits
###
# Calibrate learning rate on a grid
quSeq <- c(0.25, 0.5, 0.75)
set.seed(5235)
tun <- tuneLearnFast(form = accel~s(times, k=20, bs="ad"),
data = mcycle,
qu = quSeq)
# Fit using estimated sigmas
fit <- mqgam(accel~s(times, k=20, bs="ad"), data = mcycle, qu = quSeq, lsig = tun$lsig)
# Plot fitted quantiles
plot(mcycle$times, mcycle$accel, xlab = "Times", ylab = "Acceleration",
ylim = c(-150, 80))
for(iq in quSeq){
pred <- qdo(fit, iq, predict)
lines(mcycle$times, pred, col = 2)
}
if (FALSE) {
# You can get a better fit by letting the learning rate change with "accel"
# For instance
tun <- tuneLearnFast(form = list(accel ~ s(times, k=20, bs="ad"), ~ s(times)),
data = mcycle,
qu = quSeq)
fit <- mqgam(list(accel ~ s(times, k=20, bs="ad"), ~ s(times)),
data = mcycle, qu = quSeq, lsig = tun$lsig)
# Plot fitted quantiles
plot(mcycle$times, mcycle$accel, xlab = "Times", ylab = "Acceleration",
ylim = c(-150, 80))
for(iq in quSeq){
pred <- qdo(fit, iq, predict)
lines(mcycle$times, pred, col = 2)
}
}
Run the code above in your browser using DataLab