predict.twdtw_knn1: Predict using the twdtw_knn1 model

View source: R/predict.R

predict.twdtw_knn1R Documentation

Predict using the twdtw_knn1 model

Description

This function predicts the classes of new data using the Time Warped Dynamic Time Warping (TWDTW) method with a 1-nearest neighbor approach. The prediction is based on the minimum TWDTW distance to the known patterns stored in the twdtw_knn1 model.

Usage

## S3 method for class 'twdtw_knn1'
predict(object, newdata, ...)

Arguments

object

A twdtw_knn1 model object generated by the twdtw_knn1 function.

newdata

A data frame or similar object containing the new observations (time series data) to be predicted.

...

Additional arguments passed to the twdtw function. If provided, they will overwrite twdtw arguments previously passed to twdtw_knn1.

Value

A vector of predicted classes for the newdata.

See Also

twdtw_knn1

Examples

## Not run: 

# Read training samples
samples_path <-

samples <- st_read(samples_path, quiet = TRUE)

# Get satellite image time sereis files
tif_path <- system.file("mato_grosso_brazil", package = "dtwSat")
tif_files <- dir(tif_path, pattern = "\\.tif$", full.names = TRUE)

# Get acquisition dates
acquisition_date <- regmatches(tif_files, regexpr("[0-9]{8}", tif_files))
acquisition_date <- as.Date(acquisition_date, format = "%Y%m%d")

# Create a 3D datacube
dc <- read_stars(tif_files,
                 proxy = FALSE,
                 along = list(time = acquisition_date),
                 RasterIO = list(bands = 1:6))
dc <- st_set_dimensions(dc, 3, c("EVI", "NDVI", "RED", "BLUE", "NIR", "MIR"))
dc <- split(dc, c("band"))

# Create a knn1-twdtw model
m <- twdtw_knn1(
 x = dc,
 y = samples,
 resampling_fun = function(data) mgcv::gam(y ~ s(x), data = data),
 cycle_length = 'year',
 time_scale = 'day',
 time_weight = c(steepness = 0.1, midpoint = 50))

print(m)

# Visualize model patterns
plot(m)

# Classify satellite images
system.time(lu <- predict(dc, model = m))

# Visualise land use classification
ggplot() +
  geom_stars(data = lu) +
  theme_minimal()


# Create a knn1-twdtw model with custom smoothing function

m <- twdtw_knn1(x = dc,
 y = samples,
 resampling_fun = function(data) lm(y ~ factor(x), data = data),
 cycle_length = 'year',
 time_scale = 'day',
 time_weight = c(steepness = 0.1, midpoint = 50))

plot(m)


## End(Not run)

vwmaus/dtwSat documentation built on Jan. 28, 2024, 9 a.m.