Lab Worksheet 7

In 1898, Hermon Bumpus, an American biologist working at Brown University, collected data on one of the first examples of natural selection directly observed in nature. Immediately following a bad winter storm, he collected 136 English house sparrows, Passer domesticus, and brought them indoors. Of these birds, 64 had died during the storm, but 72 recovered and survived. By comparing measurements of physical traits, Bumpus demonstrated physical differences between the dead and living birds. He interpreted this finding as evidence for natural selection as a result of this storm:

bumpus <- read.csv("http://wilkelab.org/classes/SDS348/data_sets/bumpus_full.csv")
head(bumpus)
##    Sex   Age Survival Length Wingspread Weight Skull_Length Humerus_Length
## 1 Male Adult    Alive    154        241   24.5         31.2           17.4
## 2 Male Adult    Alive    160        252   26.9         30.8           18.7
## 3 Male Adult    Alive    155        243   26.9         30.6           18.6
## 4 Male Adult    Alive    154        245   24.3         31.7           18.8
## 5 Male Adult    Alive    156        247   24.1         31.5           18.2
## 6 Male Adult    Alive    161        253   26.5         31.8           19.8
##   Femur_Length Tarsus_Length Sternum_Length Skull_Width
## 1         17.0          26.0           21.1        14.9
## 2         18.0          30.0           21.4        15.3
## 3         17.9          29.2           21.5        15.3
## 4         17.5          29.1           21.3        14.8
## 5         17.9          28.7           20.9        14.6
## 6         18.9          29.1           22.7        15.4

The data set has three categorical variables (Sex, with levels Male and Female, Age, with levels Adult and Young, and Survival, with levels Alive and Dead) and nine numerical variables that hold various aspects of the birds’ anatomy, such as wingspread, weight, etc.

We will need this function from the last class, which calculates ROC curves:

calc_ROC <- function(probabilities, known_truth, model.name=NULL)
  {
  outcome <- as.numeric(factor(known_truth))-1
  pos <- sum(outcome) # total known positives
  neg <- sum(1-outcome) # total known negatives
  pos_probs <- outcome*probabilities # probabilities for known positives
  neg_probs <- (1-outcome)*probabilities # probabilities for known negatives
  true_pos <- sapply(probabilities,
                     function(x) sum(pos_probs>=x)/pos) # true pos. rate
  false_pos <- sapply(probabilities,
                     function(x) sum(neg_probs>=x)/neg)
  if (is.null(model.name))
    result <- data.frame(true_pos, false_pos)
  else
    result <- data.frame(true_pos, false_pos, model.name)
  result %>% arrange(false_pos, true_pos)
  }

Split the bumpus data set into a random training and test set. Use 70% of the data as a training set.

train_fraction <- 0.7 # fraction of data for training purposes
set.seed(123)  # set the seed to make your partition reproductible
train_size <- floor(train_fraction * nrow(bumpus)) # number of observations in training set
train_indices <- sample(1:nrow(bumpus), size = train_size)

train_data <- bumpus[train_indices, ] # get training data
test_data <- bumpus[-train_indices, ] # get test data

Fit a logistic regression model on the training data set, then predict the survival on the test data set, and plot the resulting ROC curves.

# model to use: 
# Survival ~ Sex + Length + Weight + Humerus_Length + Sternum_Length

glm.out.train <- glm(Survival ~ Sex + Length + Weight + Humerus_Length + Sternum_Length,
                data=train_data,
                family=binomial)
test_pred <- predict(glm.out.train, test_data, type='response')
ROC.train <- calc_ROC(probabilities=glm.out.train$fitted.values, 
                 known_truth=train_data$Survival,
                 model.name="train")
ROC.test <- calc_ROC(probabilities=test_pred, 
                 known_truth=test_data$Survival,
                 model.name="test")
ROCs <- rbind(ROC.train, ROC.test)
ggplot(ROCs, aes(x=false_pos, y=true_pos, color=model.name)) +
  geom_line() 

2. Area under the ROC curves

The following code (commented out) calculates the area under multiple ROC curves:

#ROCs %>% group_by(model.name) %>% 
#  mutate(delta=false_pos-lag(false_pos)) %>%
#  summarize(AUC=sum(delta*true_pos, na.rm=T)) %>%
#  arrange(desc(AUC))

Use this code to calculate the area under the training and test curve for this following model.

# model to use:
# Survival ~ Weight + Humerus_Length

train_fraction <- 0.6 # fraction of data for training purposes
set.seed(101)  # set the seed to make your partition reproductible
n_obs <- nrow(bumpus) # number of observations in bumpus data set
train_size <- floor(train_fraction * nrow(bumpus)) # number of observations in training set
train_indices <- sample(1:n_obs, size = train_size)

train_data <- bumpus[train_indices, ] # get training data
test_data <- bumpus[-train_indices, ] # get test data

glm.out.train <- glm(Survival ~ Weight + Humerus_Length, 
                data=train_data,
                family=binomial)
test_pred <- predict(glm.out.train, test_data, type='response')
ROC.train <- calc_ROC(probabilities=glm.out.train$fitted.values, 
                 known_truth=train_data$Survival,
                 model.name="train")
ROC.test <- calc_ROC(probabilities=test_pred, 
                 known_truth=test_data$Survival,
                 model.name="test")
ROCs <- rbind(ROC.train, ROC.test)
ROCs %>% group_by(model.name) %>% 
  mutate(delta=false_pos-lag(false_pos)) %>%
  summarize(AUC=sum(delta*true_pos, na.rm=T)) %>%
  arrange(desc(AUC))
## # A tibble: 2 × 2
##   model.name       AUC
##       <fctr>     <dbl>
## 1       test 0.7674731
## 2      train 0.6969512

3. If this was easy

Write code that generates an arbitrary number of random subdivisions of the data into training and test sets, fits a given model, calculates the area under the curve for each test data set, and then calculates the average and standard deviation of these values.

# function that does the heavy lifting
calc_AUC <- function(data, model, train_fraction)
{
  n_obs <- nrow(data) # number of observations in data set
  train_size <- floor(train_fraction * nrow(data)) # number of observations in training set
  train_indices <- sample(1:n_obs, size = train_size)

  train_data <- data[train_indices, ] # get training data
  test_data <- data[-train_indices, ] # get test data
  glm.out.train <- glm(model, data=train_data, family=binomial)
  test_pred <- predict(glm.out.train, test_data, type='response')
  ROC.train <- calc_ROC(probabilities=glm.out.train$fitted.values, 
                 known_truth=train_data$Survival,
                 model.name="training.AUC")
  ROC.test <- calc_ROC(probabilities=test_pred, 
                 known_truth=test_data$Survival,
                 model.name="test.AUC")
  ROCs <- rbind(ROC.train, ROC.test)
  # calculate AUCs
  ROCs %>% group_by(model.name) %>% 
    mutate(delta=false_pos-lag(false_pos)) %>%
    summarize(AUC=sum(delta*true_pos, na.rm=T)) %>%
    mutate(row=1) %>%
    spread(model.name, AUC) %>%
    select(-row)
}

# function that does repeated random subsampling validation
subsample_validate <- function(data, model, train_fraction, replicates)
{
  reps <- data.frame(rep=1:replicates) # dummy data frame to iterate over
  reps %>% group_by(rep) %>% # iterate over all replicates
    do(calc_AUC(data, model, train_fraction)) %>% # run calc_AUC for each replicate
    ungroup() %>%     # ungroup so we can summarize
    summarize(mean.train.AUC=mean(training.AUC),        # summarize
              sd.train.AUC=sd(training.AUC),
              mean.test.AUC=mean(test.AUC),
              sd.test.AUC=sd(test.AUC)) %>%
    mutate(train_fraction=train_fraction, replicates=replicates) # add columns containing meta data
}

Now that we have these two functions, we can use them to complete the exercise:

train_fraction <- 0.2 # fraction of data for training purposes
replicates <- 20 # how many times do we want to randomly sample
set.seed(116) # random seed
model <- Survival ~ Length + Humerus_Length # the model we want to fit
subsample_validate(bumpus, model, train_fraction, replicates)
## # A tibble: 1 × 6
##   mean.train.AUC sd.train.AUC mean.test.AUC sd.test.AUC train_fraction
##            <dbl>        <dbl>         <dbl>       <dbl>          <dbl>
## 1      0.7486415   0.07437168     0.7137714  0.03752105            0.2
## # ... with 1 more variables: replicates <dbl>
# redo with a different model
model2 <- Survival ~ Sex + Length + Weight + Humerus_Length + Sternum_Length
subsample_validate(bumpus, model2, train_fraction, replicates)
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## # A tibble: 1 × 6
##   mean.train.AUC sd.train.AUC mean.test.AUC sd.test.AUC train_fraction
##            <dbl>        <dbl>         <dbl>       <dbl>          <dbl>
## 1       0.879534   0.07398794     0.7511727  0.06619733            0.2
## # ... with 1 more variables: replicates <dbl>