mardi 16 mars 2021

Using tidy models recipe for Random Forest models, how can I specify my training and test datasets (as opposed to using a split)

I'm working of this excellent tutorial on random Forrests in R using the tidy models library:

http://www.rebeccabarter.com/blog/2020-03-25_machine_learning/

I'll post a condensed version of her code here:

library(mlbench)
library(tidymodels)
library(tidyverse)
library(workflows)
library(tune)
data(PimaIndiansDiabetes)
diabetes_orig <- PimaIndiansDiabetes
diabetes_clean <- diabetes_orig %>%
  mutate_at(vars(triceps, glucose, pressure, insulin, mass), 
            function(.var) { 
              if_else(condition = (.var == 0), # if true (i.e. the entry is 0)
                      true = as.numeric(NA),  # replace the value with NA
                      false = .var # otherwise leave it as it is
              )
            })
diabetes_split <- initial_split(diabetes_clean, 
                                prop = 3/4)

# define the recipe
diabetes_recipe <- 
  # which consists of the formula (outcome ~ predictors)
  recipe(diabetes ~ pregnant + glucose + pressure + triceps + 
           insulin + mass + pedigree + age, 
         data = diabetes_clean) %>%
  # and some pre-processing steps
  step_normalize(all_numeric()) %>%
  step_knnimpute(all_predictors())

rf_model <- 
  # specify that the model is a random forest
  rand_forest() %>%
  # specify that the `mtry` parameter needs to be tuned
  #set_args(mtry = tune()) %>%
  # select the engine/package that underlies the model
  set_engine("ranger", importance = "impurity") %>%
  # choose either the continuous regression or binary classification mode
  set_mode("classification") 

# set the workflow
rf_workflow <- workflow() %>%
  # add the recipe
  add_recipe(diabetes_recipe) %>%
  # add the model
  add_model(rf_model)

rf_fit <- rf_workflow %>%
  # fit on the training set and evaluate on test set
  last_fit(diabetes_split)

In the last line of code, it seems like the "last_fit" function requires the use of a split object. But I would like to supply my own Training and Testing datasets. So if I were to supply a specific Training and Testing dataset like this:

TrainNums <- sample(nrow(diabetes_clean), 0.7*nrow(diabetes_clean), replace = FALSE)
TrainSet<-diabetes_clean[TrainNums,]
TestSet<-diabetes_clean[-TrainNums,]

How can I use these datasets as opposed to the split? Something like this for the last line of code:

rf_fit <- rf_workflow %>%
      Training<-TrainSet
      Testing<-TestSet

I realize in this example the split command and the sample command are basically doing the same thing. But I'd like to have the ability to fit custom Test and Training datasets into the tidy model workflow. I realize I can do this using the caret package (and others) but the tidy model library is much more efficient with larger datasets.




Aucun commentaire:

Enregistrer un commentaire