library(dslabs)
library(tidyverse)
library(caret)
library(rpart)
library(randomForest)
options(repr.plot.width=15, repr.plot.height=10)
We will work with the 2008 U.S. presidential elections polls data and apply machine learning techniques to fit the data.
data("polls_2008")
qplot(day, margin, data = polls_2008)
Our focus is to apply bin smoothers, in search for the best estimate, in presence of uncertainty.
We start with a box kernel, with span of 7 days.
span <- 7
fit_box <- with(polls_2008,ksmooth(day, margin, x.points = day, kernel="box", bandwidth =span))
polls_2008 %>% mutate(smooth = fit_box$y) %>%
ggplot(aes(day, margin)) +
geom_point(size = 2, alpha = .5) +
geom_line(aes(day, smooth), color="red")
When using a span of 7 days, for each point, we have 28% of the data changing, which makes the estimate too wiggly.
The Gaussian kernel applies the Gaussian distribution to the data.
span <- 7
fit_gauss <- with(polls_2008, ksmooth(day, margin, x.points = day, kernel="normal", bandwidth = span))
polls_2008 %>% mutate(smooth = fit_gauss$y) %>%
ggplot(aes(day, margin)) +
geom_point(size = 2, alpha = .5) +
geom_line(aes(day, smooth), color="red")