Geospatial Supervised Learning using R

Preface

This web text can be viewed in a light mode or a dark mode. A toggle is provided in the sidebar.

License

CC BY-NC-SA 4.0 license badge.

Creative Commons BY-NC-SA 4.0 license badge

Copyright © 2026 Aaron Maxwell, Sarah Farhadpour, and Behnam Solouki.

Unless otherwise noted, Geospatial Supervised Learning using R by Aaron Maxwell, Sarah Farhadpour, and Behnam Solouki is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License (CC BY-NC-SA 4.0). You are free to share and adapt this material for non-commercial purposes, provided that you give appropriate credit to the original source, provide a link to the license, indicate if changes were made, and distribute any adapted material under the same license.

Goals of Text

Supervised learning, or learning from labeled data and predictor variables, has a variety of applications in remote sensing and geospatial science including image classification, land cover mapping, change detection, object detection, digital soil mapping, geohazard mapping and assessment, and habitat suitability modeling. The primary goal of this text is to provide practical examples and guidance on how to implement geospatial supervised learning in the R language and computational environment for the generation of spatial models and map products.

This text serves as a companion text to Supervised Learning in Remote Sensing and Geospatial Science: Theory and Practice by Maxwell, Ramezan, and He, which is published by Elsevier. During the production of that text, we purposely refrained from including specific code examples. Instead, author Maxwell, with assistance from his graduate students (Sarah Farhadpour and Behnam Solouki) generated this online text to accompany the book with a goal of making updates on a regular basis, which is much more difficult to undertake for a published and printed text. Supervised Learning in Remote Sensing and Geospatial Science: Theory and Practice provides a detailed coverage of the theory underpinning the topics presented in this online text, which instead focuses on implementing the techniques in the R language.

Companion text cover.

Supervised Learning in Remote Sensing and Geospatial Science: Theory and Practice cover

Use of AI Tools

Portions of this text were developed with the assistance of Claude, an AI model developed by Anthropic, used through the Claude Code tool in 2026. Claude drafted the initial versions of several chapters, including the chapters on interpretable models (GAMs and EBMs), presence-only modeling (MaxEnt), spatial resampling, model ensembles, and portions of the spatial statistics chapter. It also drafted several exercise sets, conceptual figures, and sections of other chapters (e.g., regular expressions), and it assisted with reorganizing and renumbering the text. All AI-generated content was reviewed, tested, revised, and approved by the authors, who designed the scope and structure of the text, selected the datasets and methods, executed and verified all code, and take full responsibility for the content, including any errors. Claude is not an author of this work.

Error Statement

The authors have tried their best to provide accurate and complete information. Any errors are unintentional. If you would like to comment on any material in this text, please feel free to contact the lead author, Aaron Maxwell, at Aaron.Maxwell@mail.wvu.edu.

Audience

This text was written for several key audiences.

  1. Geospatial professionals interested in developing or further developing their supervised learning skills and learning how to implement supervised learning workflows
  2. Researchers needing to apply geospatial supervised learning to problems that interest them
  3. General data scientists and analysts needing to learn more about supervised learning and working with geospatial data

The material covered in this text may be appropriate for an advanced undergraduate course or a graduate-level course. Since the focus is code implementation and practical considerations, a more theoretical companion text may be necessary.

The first three parts of the text, as described below, assume the user is familiar with the R language and the tidyverse. If you are new to R or need a refresher, the fourth part of the text, R for Geospatial Professionals, introduces R and the tidyverse and assumes no prior knowledge of the R language specifically or coding in general. That part also introduces reading, visualizing, and working with geospatial data in R.

Structure of Text

This text consists of 38 chapters organized into four parts: Geospatial Data Processing using R, Geospatial Machine Learning using R, Geospatial Deep Learning using R, and R for Geospatial Professionals. Each chapter consists of examples with associated code and explanations. The covered topics are listed at the beginning of each chapter in the Topics Covered section. At the end of most chapters, we provide review questions and exercise(s). Some of the short, more demo-focused chapters do not have associated questions and/or exercises. The data to complete the exercises have been provided or linked, which is described below.

The first part, Geospatial Data Processing using R, focuses on data preprocessing and feature engineering. Since input data for geospatial predictive modeling is primarily provided as raster grids, 1  Geospatial Raster Data Preprocessing (terra) discusses general raster data handling and processing using the terra package. Continuing the theme of 1  Geospatial Raster Data Preprocessing (terra), 2  Imagery and Digital Terrain Data explores processing multispectral imagery including creating normalized difference band ratios (e.g., the normalized difference vegetation index (NDVI)), performing a tasseled cap transformation, implementing principal component analysis (PCA) for feature reduction, and generating spatial enhancement using convolution filters or kernels. This chapter also discusses creating land surface parameters (LSPs) from digital terrain models (DTMs). 3  Downloading Remotely Sensed Data focuses on downloading Earth observation and digital terrain data stored within a SpatialTemporal Asset Catalog (STAC). 4  General Data Preprocessing discusses data preprocessing more generally with a focus on data visualization, exploratory data analysis, and creating preprocessing pipelines using the recipes package. 5  Lidar Processing (lidR) discusses the processing and rasterization of light detection and ranging (lidar) point cloud data using the lidR while 6  Individual Tree Analysis with arbor focuses, more specifically, on the processing of terrestrial laser scanning (TLS) and mobile laser scanning (MLS) data for forestry applications using the arbor package. Lastly, 7  Geographic Object-Based Image Analysis (GEOBIA) explores an implementation of geographic object-based image analysis (GEOBIA) in R.

The second part, Geospatial Machine Learning using R, focuses on model assessment, linear models, and machine learning methods. 8  Accuracy Assessment discusses model accuracy assessment methods and metrics with a specific focus on the yardstick package. These methods and metrics are used throughout this part and the next. 9  Linear Regression covers the process of training and evaluating linear models, including the interpretation of learned coefficients and ancillary output and testing model assumptions. 10  Random Forest explores the random forest algorithm, as implemented with the randomForest package, for probabilistic spatial predictive modeling. It also discusses means to assess the importance of predictor variables using random forest and Shapley additive explanations (SHAP) values, a model agnostic method. 11  Interpretable Models (GAMs and EBMs) explores models that are interpretable by design, generalized additive models (GAMs) and explainable boosting machines (EBMs), using the mgcv and interpret packages. 12  Presence-Only Modeling (MaxEnt) introduces presence-only modeling using maximum entropy (MaxEnt), as implemented with the maxnet package, including tuning, response curves, and variable importance estimation. 13  Introduction to Machine Learning (tidymodels) and 14  Machine Learning Workflows (tidymodels) explain the process of implementing machine learning using the tidymodels metapackage, which includes several key packages: parsnips, recipes, rsample, tune, dials, yardstick, and workflows. By presenting and implementing a series of workflows, we explain how to train, tune, validate, compare, and use models generated with the tidymodels workflow. 15  Spatial Resampling demonstrates spatial resampling methods for partitioning geospatial data using the spatialsample package, and 16  Model Ensembles explains how to combine multiple models into a stacked ensemble using the stacks package.

The third part, Geospatial Deep Learning using R, focuses on deep learning using the torch package, which provides a means to implement deep learning in R without connecting to a Python/PyTorch environment. Throughout this part, the training of deep learning algorithms is implemented using luz, which greatly simplifies the error prone training process. 17  Tensors explains the tensor data model used to represent data for deep learning as multidimensional arrays that can be processed on both a CPU and GPU and for which the operations performed to create them can be tracked as a computational graph, which is required for performing backpropagation during the training process. In 18  Fully Connected Neural Networks (Scene Classification), you learn to build, train, and evaluate a fully connected artificial neural network (ANN) architecture for a scene classification task (i.e., labeling an entire image to a single class) while 19  Convolutional Neural Network (Scene Classification) explores the same task but using convolutional neural network (CNN) architectures. 20  Improving Deep Learning Models explores a variety of methods to potentially improve deep learning models by augmenting the architecture and/or training process. The final five chapters of this part focus on geospatial semantic segmentation, or pixel-level labeling. In 21  UNet Archiecture (Semantic Segmentation) you learn to build the UNet architectures from scratch. 22  Geospatial Semantic Segmentation: Data Preparation (geodl) and 23  Geospatial Semantic Segmentation: Models and Assessment (geodl) introduce the geodl package, which builds on terra, torch, and luz. The first of these chapters focuses on data preparation and GPU-based calculation of land surface parameters (LSPs), while the second focuses on the available semantic segmentation architectures, loss functions, and assessment tools. 24  Geospatial Semantic Segmentation Workflows: Binary Classification and 25  Geospatial Semantic Segmentation Workflows: Multiclass Classification then demonstrate complete geospatial semantic segmentation workflows for binary and multiclass classification problems, respectively.

The fourth and final part, R for Geospatial Professionals, introduces using R for general data science tasks and for working with geospatial data. If you are already familiar with R, this part may not be useful or necessary. However, for those new to R, still learning the language, or looking for a refresher, this part, or some chapters from it, may be of interest. The goal of this part is to support users in learning R for general data science, GIS, and spatial mapping and modeling tasks. 26  Base R (Part I) covers the basics of the R language while 27  Data Wrangling with the tidyverse covers data manipulation, wrangling, and summarization using the tidyverse packages (e.g., readr, tibble, dplyr, stringr, and forcats). 28  Base R (Part II) further explores the R language and discusses functions, loops, and control flow. 29  Working with Dates and Times discusses working with dates, times, and time series data using base R and the lubridate package. 30  Graphing with ggplot2 (Part I) and 31  Graphing with ggplot2 (Part II) explore the use of ggplot2 for building data visualizations and graphs. 32  Producing Tables (gt) introduces the gt package for building and refining tables. 33  Statistical Inference provides a broad overview of how to implement statistical tests in R.

The final set of chapters focus on geospatial data specifically. 34  Static Maps (tmap) introduces mapping and spatial data visualization with tmap while 35  Vector Geoprocessing (sf) focuses on working with and analyzing vector geospatial data with the sf package. 36  Using WhiteboxTools in R offers a demo of how R can interface with other geospatial software tools using Whitebox Tools as an example. 37  Spatial Statistics introduces spatial statistics, including point pattern analysis, spatial autocorrelation, semivariograms, and hot spot analysis. The final chapter, 38  Interactive Web Maps (leaflet), introduces building interactive web maps using the leaflet package.

Data and Source Files

This books was written using Quarto. To learn more about Quarto, we recommend Quarto for Scientists by Nicholas Tierney, which was also written using Quarto and has been made available free-of-charge. All the Quarto (.qmd) files that constitute this book can be downloaded from the text’s landing page.

We have also provided the required source data and Quarto files to execute the provided code. These data can be downloaded using the download options in the sidebar. Separate downloads have been provided for each chapter. You will need to uncompress the data before use. If you open a Quarto file from the downloaded directory, the relative file paths used in the code should work so that the paths do not need to be updated. In some cases, the used files are large or already available on the web. In such cases, we note the source at the beginning of the chapter in which they are used. We have also provided trained models for use in the deep learning section if you would like to execute some of the example code but not the associated training loop, which can take hours in some cases.

All data are housed in the gslrData folder. Each chapter has an associated folder in this director (e.g., chpt1). Within each chapter directory, needed data to execute the chapter code are provided in the data folder while files for the associated exercise(s) are in the exercise folder. We also include initially empty output and scratch folders in each chapter folder for use when the code is executed.

We generally recommend using an integrated development environment (IDE). We suggest RStudio by Posit, which is freely available.

Installing R packages is generally easy. In code, this can be accomplished with installed.packages("INSERT PACKAGE NAME"). In RStudio, packages can be installed using Tools –> Install Packages. Setting up torch for deep learning in R can be tricky, especially if you plan to use a GPU. Use of a GPU is required to implement the CNNs and semantic segmentation architectures presented in the text. This page describes how to set up torch in R with and without GPU support.

Thanks

This online text was partially funded by AmericaView. AmericaView is a nationwide, university-based, and state-implemented network that advances Earth observation education through remote sensing science, applied research, workforce development, technology transfer, and community outreach. AmericaView is supported by the United States Geological Survey (USGS) under Grant/Cooperative Agreement No. G23AP00683. The views and conclusions contained in this text are those of the authors and should not be interpreted as representing the opinions or policies of the U.S. Geological Survey. Mention of trade names or commercial products does not constitute their endorsement by the U.S. Geological Survey.

Partial funding was also provided by the National Science Foundation (NSF) (Federal Award ID No. 2046059: “CAREER: Mapping Anthropocene Geomorphology with Deep Learning, Big Data Spatial Analytics, and LiDAR”). Any opinions, findings, and conclusions or recommendations expressed in this material are those of the author(s) and do not necessarily reflect the views of the National Science Foundation.

Nomenclature

We use the following type standards throughout the text:

  1. Bold text is used to highlight key or important terms at first use in each chapter (e.g., Landsat).
  2. Underlined text is used for R package or metapackage names (e.g., terra).
  3. Italic text is used for file names, folder paths/directories, and book or journal titles (e.g., rasterStack.tif).
  4. Table, data frame, or tibble column names are written in “quotes” and italicized (“Band1”).
  5. “Quotes” are placed around names of journal articles.
  6. In-text code snippets and variable names are written as fixed-width text (e.g., var1 = c(1,2,3,4)).
  7. Callout blocks are used to highlight key information, offers practical advice, or relate concepts across chapters.

This is an example callout block.

Concluding Remarks

We hope your are excited to start learning more about supervised learning as implemented in R. As noted above, we begin the discussion with processing raster geospatial data since this is how we commonly represent data for use in the modeling workflow.

Appendix: Package List

Below is a list of the key packages used in this text with a brief description of their use and links to their documentation.

Package Metapackage Description
Data prep and wrangling
readr (site) tidyverse Read tabulated data
tibble (site) tidyverse Define tibble data type
dplyr (site) tidyverse General data wrangling, filtering, query, and manipulation
stringr (site) tidyverse Work with string/character data
forcats (site) tidyverse Work with factor data
ggplot2 (site) tidyverse Data visualization and graphing
lubridate (site) tidyverse Date and time data handling
gt (site) - Create tables
Data prep and wrangline
purrr (site) tidyverse Functional programming in R
Accuracy assessment
yardstick (site) tidymodels Accuracy assessment
micer (site) - Map image classification efficacy (MICE) and related metrics
pROC (site) - Receiver operating characteristic (ROC) curves
Machine learning
infer (site) - Inference using tidyverse/tidymodels syntax
parsnips (site) tidymodels Implement a variety of ML algorithms using consistent syntax
recipes (site) tidymodels Preprocessing and feature engineering
rsample (site) tidymodels Data splitting and resampling
tune (site) tidymodels Model optimization and hyperparameter tuning
dials (site) tidymodels Define and manage hyperparameter settings to test
workflows (site) tidymodels Define and implement a unified workflow consisting of preprocessing, tuning, training, and post-processing components
workflowsets (site) tidymodels Combine multiple workflows
stacks (site) tidymodels Generate model ensembles
spatialsample (site) tidymodels Define data folds using spatial patterns
randomForest (site) - Random forest algorithm implementation
ranger (site) - Random forest algorihtm implementation (faster)
kernlab (site) - Support vector mahcine algorithm implementation
kknn (site) - k-nearest neighbors implementation
nnet (site) - Artificial neural networks implementation
mgcv (site) - Implment generalized additive models (GAMs)
gratia (site) - Visualize GAM results
interpret (site) - Implement Explainable boosting machines (EBMs)
maxnet (site) - Implement MaxEnt
permimp (site) - Variable importance estimation with random forest
Boruta (site) - Variable importance estimation with random forest
fastshap (site) - SHAP values
shapviz (site) - SHAP value visualization
Deep learning
torch (site) - Deep learning R/C++ implementation
luz (site) - Simplifies torch training loop
torchvision (site) - Adds more computer vision functionality to torch
geodl (site) - Geospatial semantic segmentation using torch, luz, and terra
Geospatial
terra (site) - Raster geospatial data reading and processing
sf (site) - Vector geospatial data reading and processing
tmap (site) - Thematic map creation
leaflet (site) - Interactive web map creation
lidR (site) - Lidar data processing and handling
arbor (site) - Terrestrial and mobile lidar data processing and handling for foresty
rstac (site) - Download geospatial and Earth observation data stored in a SpatioTemporal Asset Catalog (STAC)
supercells (site) - Create image objects for geographic object-based image analysis (GEOBIA)
exactextractr (site) - Summarize raster data relative to polygon areas
GLCMTextures (site) - Calculate textural measures using the gray-level co-occurrence matrix (GLCM)
spatialEco (site) - Additional functionality for processing geospatial data with a focus on spatial ecology applications
RSToobox (site) - Additonal tools for working with remotely sensed data
MultiscaleDTM (site) - Configure moving windows/kernels for digital terrain analysis
whitebox (site) - Interface to Whitebox Tools
spdep (site) - Spatial dependency and spatial statistics
gstat (site) - Spatial statistics
Geospatilal
spatstat (site) - Spatial statistics