mlr3 - k-nearest Neighbours

library('vivid')
library("mlr3")
library("mlr3learners")

This guide is designed as a quick-stop reference of how to use some of the more popular machine learning R packages with vivid. In the following examples, we use the air quality data for regression.

mlr3 - k-nearest Neighbours

The mlr3 package in R offers a modern, object-oriented framework for machine learning tasks in R, providing tools for data preprocessing, model training, evaluation, and tuning. Here, we fit a k-nearest neighbours model to the data.

Regression

# load data
aq <- na.omit(airquality)

# Define a regression task
task <- TaskRegr$new(id = "airquality", backend = aq, target = "Ozone")


# Train a k-nearest neighbours model using mlr3
learner <- lrn("regr.kknn")
m3 <- learner$train(task)

# vivid
vi <- vivi(data = aq, fit = m3, response = 'Ozone')

Heatmap

viviHeatmap(mat = vi)
Figure 1: Heatmap of a mlr KNN regression fit displaying 2-way interaction strength on the off diagonal and individual variable importance on the diagonal.

PDP

pdpPairs(data = aq, 
         fit =  m3, 
         response = "Ozone", 
         nmax = 50, 
         gridSize = 4,         
         nIce = 10)
Figure 2: Generalized pairs partial dependence plot for a mlr KNN regression fit.