Using spatial resamples for analysis

knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
library(ggplot2)
theme_set(theme_minimal())

The resampled objects created by spatialsample can be used in many of the same ways that those created by rsample can, from making comparisons to evaluating models. These objects can be used together with other parts of the tidymodels framework, but let's walk through a more basic example using linear modeling of housing data from Ames, IA.

data("ames", package = "modeldata")

Let's say that the sale price of these houses depends on the year they were built, their living area (size), and the type of house they are (duplex vs. townhouse vs. single family), along with perhaps interactions between type and house size.

log10(Sale_Price) ~ Year_Built + Gr_Liv_Area +  Bldg_Type

This relationship may exhibit spatial autocorrelation across the city of Ames, and we can use a spatial resampling strategy to evaluate such a model. We can create v = 15 spatial cross-validation folds with spatial_clustering_cv(), which uses k-means clustering to identify the sets:

library(spatialsample)

set.seed(123)
folds <- spatial_clustering_cv(ames, coords = c("Latitude", "Longitude"), v = 15)
folds

The folds object is an rset object that contains many resamples or rsplit objects in the splits column. The resulting partitions do not necessarily contain an equal number of observations.

Now let's write a function that will, for each resample:

# `splits` will be the `rsplit` object
compute_preds <- function(splits) {
  # fit the model to the analysis set
  mod <- lm(log10(Sale_Price) ~ Year_Built + Bldg_Type * log10(Gr_Liv_Area), 
            data = analysis(splits))
  # identify the assessment set
  holdout <- assessment(splits)
  # return the assessment set, with true and predicted price
  tibble::tibble(Longitude = holdout$Longitude, 
                 Latitude = holdout$Latitude,
                 Sale_Price = log10(holdout$Sale_Price), 
                 .pred = predict(mod, holdout))
}

We can apply this function to just one of the splits.

compute_preds(folds$splits[[7]]) 

Or we can apply this function to all of the splits, using purrr::map().

library(purrr)
library(dplyr)

cv_res <- folds %>%
  mutate(.preds = map(splits, compute_preds))

cv_res

We can unnest() these results and use yardstick to compute any regression metrics appropriate to this modeling analysis, such as yardstick::rmse():

library(tidyr)
library(yardstick)

cv_rmse <- cv_res %>%
  unnest(.preds) %>%
  group_by(id) %>%
  rmse(Sale_Price, .pred)

cv_rmse

It looks like the RMSE may vary across the city, so we can join the metrics back up to our results and plot them.

library(ggplot2)

cv_res %>%
  unnest(.preds) %>%
  left_join(cv_rmse) %>%
  ggplot(aes(Longitude, Latitude, color = .estimate)) + 
  geom_point(alpha = 0.5) +
  labs(color = "RMSE") +
  scale_color_viridis_c()

The area of highest RMSE is close to a more industrial area of Ames, by a large Department of Transportation complex.



Try the spatialsample package in your browser

Any scripts or data that you put into this service are public.

spatialsample documentation built on March 4, 2021, 5:06 p.m.