├── .gitignore ├── 01_build_a_model.Rmd ├── 02_preprocess_with_recipes.Rmd ├── 03_evaluate_with_resampling.Rmd ├── 04_tune_model_parameters.Rmd ├── 05_case_study.Rmd ├── LICENSE.md ├── README.md └── cloudstart.Rproj /.gitignore: -------------------------------------------------------------------------------- 1 | .Rproj.user 2 | .Rhistory 3 | .RData 4 | .Ruserdata 5 | -------------------------------------------------------------------------------- /01_build_a_model.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Build a model" 3 | output: 4 | html_document: 5 | toc: true 6 | --- 7 | 8 | ```{r setup, include=FALSE} 9 | knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE) 10 | options(tibble.print_min = 5) 11 | ``` 12 | 13 | Get started with building a model in this R Markdown document that accompanies [Build a model](https://www.tidymodels.org/start/models/) tidymodels start article. 14 | 15 | If you ever get lost, you can visit the links provided next to section headers to see the accompanying section in the online article. 16 | 17 | Take advantage of the RStudio IDE and use "Run All Chunks Above" or "Run Current Chunk" buttons to easily execute code chunks. If you have been running other tidymodels articles in this project, restart R before working on this article so you don't run out of memory on RStudio Cloud. 18 | 19 | 20 | ## [Introduction](https://www.tidymodels.org/start/models/#intro) 21 | 22 | Load necessary packages: 23 | 24 | ```{r} 25 | library(tidymodels) # for the parsnip package, along with the rest of tidymodels 26 | 27 | # Helper packages 28 | library(readr) # for importing data 29 | library(broom.mixed) # for converting bayesian models to tidy tibbles 30 | ``` 31 | 32 | 33 | ## [The Sea Urchins Data](https://www.tidymodels.org/start/models/#data) 34 | 35 | 36 | ```{r} 37 | urchins <- 38 | # Data were assembled for a tutorial 39 | # at https://www.flutterbys.com.au/stats/tut/tut7.5a.html 40 | read_csv("https://tidymodels.org/start/models/urchins.csv") %>% 41 | # Change the names to be a little more verbose 42 | setNames(c("food_regime", "initial_volume", "width")) %>% 43 | # Factors are very helpful for modeling, so we convert one column 44 | mutate(food_regime = factor(food_regime, levels = c("Initial", "Low", "High"))) 45 | ``` 46 | 47 | Look at the data: 48 | 49 | ```{r} 50 | urchins 51 | ``` 52 | 53 | Plot the data: 54 | 55 | ```{r} 56 | ggplot(urchins, 57 | aes(x = initial_volume, 58 | y = width, 59 | group = food_regime, 60 | col = food_regime)) + 61 | geom_point() + 62 | geom_smooth(method = lm, se = FALSE) + 63 | scale_color_viridis_d(option = "plasma", end = .7) 64 | ``` 65 | 66 | ## [Build and fit a model](https://www.tidymodels.org/start/models/#build-model) 67 | 68 | ```{r} 69 | linear_reg() %>% 70 | set_engine("lm") 71 | 72 | ``` 73 | 74 | Try typing `?linear_reg()` in the console to see all available engines and other details about this model type. 75 | 76 | Create model specification: 77 | 78 | ```{r} 79 | lm_mod <- 80 | linear_reg() %>% 81 | set_engine("lm") 82 | ``` 83 | 84 | Fit model: 85 | 86 | ```{r} 87 | lm_fit <- 88 | lm_mod %>% 89 | fit(width ~ initial_volume * food_regime, data = urchins) 90 | lm_fit 91 | ``` 92 | 93 | Present model results in a tidyverse friendly way with `tidy()` from `broom` package. 94 | 95 | ```{r} 96 | tidy(lm_fit) 97 | ``` 98 | 99 | ## [Use a model to predict](https://www.tidymodels.org/start/models/#predict-model) 100 | 101 | New example data to predict: 102 | 103 | ```{r} 104 | new_points <- expand.grid(initial_volume = 20, 105 | food_regime = c("Initial", "Low", "High")) 106 | new_points 107 | ``` 108 | 109 | Generate the mean body width values: 110 | 111 | ```{r} 112 | mean_pred <- predict(lm_fit, new_data = new_points) 113 | mean_pred 114 | ``` 115 | 116 | Get confidence intervals and plot: 117 | 118 | ```{r} 119 | conf_int_pred <- predict(lm_fit, 120 | new_data = new_points, 121 | type = "conf_int") 122 | conf_int_pred 123 | 124 | # Now combine: 125 | plot_data <- 126 | new_points %>% 127 | bind_cols(mean_pred) %>% 128 | bind_cols(conf_int_pred) 129 | 130 | # and plot: 131 | ggplot(plot_data, aes(x = food_regime)) + 132 | geom_point(aes(y = .pred)) + 133 | geom_errorbar(aes(ymin = .pred_lower, 134 | ymax = .pred_upper), 135 | width = .2) + 136 | labs(y = "urchin size") 137 | ``` 138 | 139 | ## [Model with a different engine](https://www.tidymodels.org/start/models/#new-engine) 140 | 141 | Switch to Bayesian approach by simply changing your engine to **stan**: 142 | 143 | ```{r} 144 | # set the prior distribution 145 | prior_dist <- rstanarm::student_t(df = 1) 146 | 147 | set.seed(123) 148 | 149 | # make the parsnip model 150 | bayes_mod <- 151 | linear_reg() %>% 152 | set_engine("stan", 153 | prior_intercept = prior_dist, 154 | prior = prior_dist) 155 | 156 | # train the model 157 | bayes_fit <- 158 | bayes_mod %>% 159 | fit(width ~ initial_volume * food_regime, data = urchins) 160 | 161 | print(bayes_fit, digits = 5) 162 | ``` 163 | 164 | To update the parameter table, the `tidy()` method is once again used: 165 | 166 | ```{r} 167 | tidy(bayes_fit, intervals = TRUE) 168 | ``` 169 | 170 | Get your predictions without changing the syntax you used earlier: 171 | 172 | ```{r} 173 | bayes_plot_data <- 174 | new_points %>% 175 | bind_cols(predict(bayes_fit, new_data = new_points)) %>% 176 | bind_cols(predict(bayes_fit, new_data = new_points, type = "conf_int")) 177 | 178 | ggplot(bayes_plot_data, aes(x = food_regime)) + 179 | geom_point(aes(y = .pred)) + 180 | geom_errorbar(aes(ymin = .pred_lower, ymax = .pred_upper), width = .2) + 181 | labs(y = "urchin size") + 182 | ggtitle("Bayesian model with t(1) prior distribution") 183 | ``` 184 | 185 | 186 | Think about how we are using the pipe (`%>%`): 187 | 188 | + Use the pipe to pass around the _data_ in the **tidyverse** 189 | + Use the pipe to pass around the _model object_ with **tidymodels** 190 | -------------------------------------------------------------------------------- /02_preprocess_with_recipes.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Preprocess your data with recipes" 3 | output: 4 | html_document: 5 | toc: true 6 | --- 7 | 8 | ```{r setup, include=FALSE} 9 | knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE) 10 | options(tibble.print_min = 5) 11 | ``` 12 | 13 | Get started with building a model in this R Markdown document that accompanies [Preprocess your data with recipes](https://www.tidymodels.org/start/recipes) tidymodels start article. 14 | 15 | If you ever get lost, you can visit the links provided next to section headers to see the accompanying section in the online article. 16 | 17 | Take advantage of the RStudio IDE and use "Run All Chunks Above" or "Run Current Chunk" buttons to easily execute code chunks. If you have been running other tidymodels articles in this project, restart R before working on this article so you don't run out of memory on RStudio Cloud. 18 | 19 | 20 | ## [Introduction](https://www.tidymodels.org/start/recipes/#intro) 21 | 22 | Load necessary packages: 23 | 24 | ```{r} 25 | library(tidymodels) # for the recipes package, along with the rest of tidymodels 26 | 27 | # Helper packages 28 | library(nycflights13) # for flight data 29 | library(skimr) # for variable summaries 30 | ``` 31 | 32 | Load and wrangle data: 33 | 34 | ```{r} 35 | flight_data <- 36 | flights %>% 37 | mutate( 38 | # Convert the arrival delay to a factor 39 | arr_delay = ifelse(arr_delay >= 30, "late", "on_time"), 40 | arr_delay = factor(arr_delay), 41 | # We will use the date (not date-time) in the recipe below 42 | date = as.Date(time_hour) 43 | ) %>% 44 | # Include the weather data 45 | inner_join(weather, by = c("origin", "time_hour")) %>% 46 | # Only retain the specific columns we will use 47 | select(dep_time, flight, origin, dest, air_time, distance, 48 | carrier, date, arr_delay, time_hour) %>% 49 | # Exclude missing data 50 | na.omit() %>% 51 | # For creating models, it is better to have qualitative columns 52 | # encoded as factors (instead of character strings) 53 | mutate_if(is.character, as.factor) 54 | ``` 55 | 56 | Before moving forward, let's reduce the size of our data so we can run these analyses with the default computational resources on RStudio Cloud. By doing so we will avoid aborting our session. 57 | 58 | Let's sample 20% of the rows and assign it as our data: 59 | 60 | ```{r} 61 | # Fix the random numbers by setting the seed 62 | # This enables the analysis to be reproducible when random numbers are used 63 | set.seed(3) 64 | 65 | flight_data <- flight_data %>% 66 | slice_sample(prop = 0.2) 67 | 68 | nrow(flight_data) 69 | ``` 70 | 71 | Note that since we are using a subset of the original data set, the results you generate here will be slightly different than the *Preprocess your data with recipes* article. 72 | 73 | Check the number of delayed flights: 74 | 75 | ```{r} 76 | flight_data %>% 77 | count(arr_delay) %>% 78 | mutate(prop = n/sum(n)) 79 | ``` 80 | 81 | For example, the number of `late` and `on_time` flights you get here are less than the number of flights you see in the article. The proportions are very close, though, suggesting that our random sampling was indeed random and did not over- or under-sample one category vs. the other. 82 | 83 | Take a look at data types and data points: 84 | 85 | ```{r} 86 | glimpse(flight_data) 87 | ``` 88 | 89 | Summarise the dataset: 90 | 91 | ```{r} 92 | flight_data %>% 93 | skimr::skim(dest, carrier) 94 | ``` 95 | 96 | ## [Data splitting](https://www.tidymodels.org/start/recipes/#data-split) 97 | 98 | Create training and test sets: 99 | 100 | ```{r} 101 | # Put 3/4 of the data into the training set 102 | data_split <- initial_split(flight_data, prop = 3/4) 103 | 104 | # Create data frames for the two sets: 105 | train_data <- training(data_split) 106 | test_data <- testing(data_split) 107 | ``` 108 | 109 | Try typing `?initial_split` in the console to get more details about the splitting function from `rsample` package. 110 | 111 | ## [Create recipe and roles](https://www.tidymodels.org/start/recipes/#recipe) 112 | 113 | Let's initiate a new recipe: 114 | 115 | ```{r} 116 | flights_rec <- 117 | recipe(arr_delay ~ ., data = train_data) 118 | ``` 119 | 120 | You can see more details about how to create **recipes** by typing `?recipe` in the console. 121 | 122 | 123 | Update variable roles of a recipe with `update_role`: 124 | 125 | ```{r} 126 | flights_rec <- 127 | recipe(arr_delay ~ ., data = train_data) %>% 128 | update_role(flight, time_hour, new_role = "ID") 129 | ``` 130 | 131 | You can also read more about adding/updating/removing roles with `?roles`. 132 | 133 | 134 | To get the current set of variables and roles, use the `summary()` function: 135 | 136 | ```{r} 137 | summary(flights_rec) 138 | ``` 139 | 140 | 141 | ## [Create features](https://www.tidymodels.org/start/recipes/#features) 142 | 143 | What happens if we transform `date` column to `numeric`? 144 | 145 | ```{r} 146 | flight_data %>% 147 | distinct(date) %>% 148 | mutate(numeric_date = as.numeric(date)) 149 | ``` 150 | 151 | From `date` we can derive more meaningful features such as: 152 | 153 | * the day of the week, 154 | * the month, and 155 | * whether or not the date corresponds to a holiday. 156 | 157 | Add **steps** to your recipe to generate these features: 158 | 159 | ```{r} 160 | flights_rec <- 161 | recipe(arr_delay ~ ., data = train_data) %>% 162 | update_role(flight, time_hour, new_role = "ID") %>% 163 | step_date(date, features = c("dow", "month")) %>% 164 | step_holiday(date, holidays = timeDate::listHolidays("US")) %>% 165 | step_rm(date) 166 | ``` 167 | 168 | Check out help documents for these step functions with `?step_date`, `?step_holiday`, `?step_rm`. 169 | 170 | Create dummy variables using `step_dummy()`: 171 | 172 | ```{r} 173 | flights_rec <- 174 | recipe(arr_delay ~ ., data = train_data) %>% 175 | update_role(flight, time_hour, new_role = "ID") %>% 176 | step_date(date, features = c("dow", "month")) %>% 177 | step_holiday(date, holidays = timeDate::listHolidays("US")) %>% 178 | step_rm(date) %>% 179 | step_dummy(all_nominal(), -all_outcomes()) 180 | ``` 181 | 182 | Check if some destinations present in test set are not included in the training set: 183 | 184 | ```{r} 185 | test_data %>% 186 | distinct(dest) %>% 187 | anti_join(train_data) 188 | ``` 189 | 190 | Remove variables that contain only a single value with `step_zv()`: 191 | 192 | ```{r} 193 | flights_rec <- 194 | recipe(arr_delay ~ ., data = train_data) %>% 195 | update_role(flight, time_hour, new_role = "ID") %>% 196 | step_date(date, features = c("dow", "month")) %>% 197 | step_holiday(date, holidays = timeDate::listHolidays("US")) %>% 198 | step_rm(date) %>% 199 | step_dummy(all_nominal(), -all_outcomes()) %>% 200 | step_zv(all_predictors()) 201 | ``` 202 | 203 | 204 | ## [Fit a model with a recipe](https://www.tidymodels.org/start/recipes/#fit-workflow) 205 | 206 | Recall the [Build a model](https://www.tidymodels.org/start/models/) article. 207 | 208 | This time we build a model specification for logistic regression using the `glm` engine: 209 | 210 | ```{r} 211 | lr_mod <- 212 | logistic_reg() %>% 213 | set_engine("glm") 214 | ``` 215 | 216 | For more details try typing `?set_engine` and `?glm` in the console. 217 | 218 | Bundle the model specification (`lr_mod`) with the recipe (`flights_rec`) to create a *model workflow*: 219 | 220 | ```{r} 221 | flights_wflow <- 222 | workflow() %>% 223 | add_model(lr_mod) %>% 224 | add_recipe(flights_rec) 225 | flights_wflow 226 | ``` 227 | 228 | Prepare the recipe and train the model: 229 | 230 | Be patient; this step will take a little time to compute. 231 | 232 | ```{r} 233 | flights_fit <- 234 | flights_wflow %>% 235 | fit(data = train_data) 236 | ``` 237 | 238 | Pull the fitted model object then use the `broom::tidy()` function to get a tidy tibble of model coefficients: 239 | 240 | ```{r} 241 | flights_fit %>% 242 | pull_workflow_fit() %>% 243 | tidy() 244 | ``` 245 | 246 | ## [Use a trained workflow to predict](https://www.tidymodels.org/start/recipes/#predict-workflow) 247 | 248 | Simply apply fitted model to `test_data` and predict outcomes. 249 | 250 | ```{r} 251 | predict(flights_fit, test_data) 252 | ``` 253 | 254 | Get predicted class probabilities and bind them with some variables from the test data: 255 | 256 | ```{r} 257 | flights_pred <- 258 | predict(flights_fit, test_data, type = "prob") %>% 259 | bind_cols(test_data %>% select(arr_delay, time_hour, flight)) 260 | 261 | # The data look like: 262 | flights_pred 263 | ``` 264 | 265 | Note that the result you get here will be different than the online article since we only fitted the model to the subset of the actual data set. 266 | 267 | Let's look at model performance with ROC curve (`roc_curve()`) and plot by piping it to the `autoplot()`. 268 | 269 | ```{r} 270 | flights_pred %>% 271 | roc_curve(truth = arr_delay, .pred_late) %>% 272 | autoplot() 273 | ``` 274 | 275 | Similarly, `roc_auc()` estimates the area under the curve: 276 | 277 | ```{r} 278 | flights_pred %>% 279 | roc_auc(truth = arr_delay, .pred_late) 280 | ``` 281 | 282 | Good job! 283 | 284 | Now it's your turn to test out this workflow [*without*](https://tidymodels.github.io/workflows/reference/add_formula.html) this recipe! 285 | 286 | In the [Build a model](https://www.tidymodels.org/start/models/) article, we did not use a recipe but used a **formula** instead. 287 | 288 | You can use `workflows::add_formula(arr_delay ~ .)` instead of `add_recipe()` (remember to remove the identification variables first!), and see whether our recipe improved our model's ability to predict late arrivals. 289 | -------------------------------------------------------------------------------- /03_evaluate_with_resampling.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Evaluate your model with resampling" 3 | output: 4 | html_document: 5 | toc: true 6 | --- 7 | 8 | ```{r setup, include=FALSE} 9 | knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE) 10 | options(tibble.print_min = 5) 11 | ``` 12 | 13 | Get started with building a model in this R Markdown document that accompanies [Evaluate your model with resampling](https://www.tidymodels.org/start/resampling) tidymodels start article. 14 | 15 | If you ever get lost, you can visit the links provided next to section headers to see the accompanying section in the online article. 16 | 17 | Take advantage of the RStudio IDE and use "Run All Chunks Above" or "Run Current Chunk" buttons to easily execute code chunks. If you have been running other tidymodels articles in this project, restart R before working on this article so you don't run out of memory on RStudio Cloud. 18 | 19 | ## [Introduction](https://www.tidymodels.org/start/resampling/#intro) 20 | 21 | Load necessary packages: 22 | 23 | ```{r} 24 | library(tidymodels) # for the rsample package, along with the rest of tidymodels 25 | 26 | # Helper packages 27 | library(modeldata) # for the cells data 28 | ``` 29 | 30 | ## [The cell image data](https://www.tidymodels.org/start/resampling/#data) 31 | 32 | Load cell image data (it has a lot of columns!): 33 | 34 | ```{r} 35 | data(cells, package = "modeldata") 36 | cells 37 | ``` 38 | 39 | Look at proportion of classes: 40 | 41 | ```{r} 42 | cells %>% 43 | count(class) %>% 44 | mutate(prop = n/sum(n)) 45 | ``` 46 | 47 | 48 | ## [Data splitting](https://www.tidymodels.org/start/resampling/#data-split) 49 | 50 | Define a split object stratified by `class` column: 51 | 52 | ```{r} 53 | set.seed(123) 54 | cell_split <- initial_split(cells %>% select(-case), 55 | strata = class) 56 | ``` 57 | 58 | Apply the split to obtain training (`cell_train`) and test (`cell_test`) sets. 59 | 60 | ```{r} 61 | cell_train <- training(cell_split) 62 | cell_test <- testing(cell_split) 63 | 64 | nrow(cell_train) 65 | nrow(cell_train)/nrow(cells) 66 | 67 | # training set proportions by class 68 | cell_train %>% 69 | count(class) %>% 70 | mutate(prop = n/sum(n)) 71 | 72 | # test set proportions by class 73 | cell_test %>% 74 | count(class) %>% 75 | mutate(prop = n/sum(n)) 76 | ``` 77 | 78 | We will work with the training set data for the majority of the modeling steps. 79 | 80 | ## [Modeling](https://www.tidymodels.org/start/resampling/#modeling) 81 | 82 | This time we don't need to preprocess the data as much, so we will not use a **recipe**. 83 | Let's create the model specification for a random forest model, using the `ranger` engine and setting the mode to `classification`. 84 | 85 | ```{r} 86 | rf_mod <- 87 | rand_forest(trees = 1000) %>% 88 | set_engine("ranger") %>% 89 | set_mode("classification") 90 | ``` 91 | 92 | See `?rand_forest` for possibile engines, modes, and further details. 93 | 94 | Now let's fit the model on our training dataset using the *formula*: 95 | 96 | ```{r} 97 | set.seed(234) 98 | rf_fit <- 99 | rf_mod %>% 100 | fit(class ~ ., data = cell_train) 101 | rf_fit 102 | ``` 103 | 104 | ## [Estimating performance](https://www.tidymodels.org/start/resampling/#performance) 105 | 106 | What happens if we evaluate model performance with the _training_ data? 107 | 108 | Predict the same fitted model with training dataset: 109 | 110 | ```{r} 111 | rf_training_pred <- 112 | predict(rf_fit, cell_train) %>% 113 | bind_cols(predict(rf_fit, cell_train, type = "prob")) %>% 114 | # Add the true outcome data back in 115 | bind_cols(cell_train %>% 116 | select(class)) 117 | ``` 118 | 119 | Look at the performance results: 120 | 121 | ```{r} 122 | rf_training_pred %>% # training set predictions 123 | roc_auc(truth = class, .pred_PS) 124 | rf_training_pred %>% # training set predictions 125 | accuracy(truth = class, .pred_class) 126 | ``` 127 | 128 | Now proceed to the test set: 129 | 130 | ```{r} 131 | rf_testing_pred <- 132 | predict(rf_fit, cell_test) %>% 133 | bind_cols(predict(rf_fit, cell_test, type = "prob")) %>% 134 | bind_cols(cell_test %>% select(class)) 135 | ``` 136 | 137 | And look at performance results from prediction with the test set: 138 | 139 | ```{r} 140 | rf_testing_pred %>% # test set predictions 141 | roc_auc(truth = class, .pred_PS) 142 | rf_testing_pred %>% # test set predictions 143 | accuracy(truth = class, .pred_class) 144 | ``` 145 | 146 | Whoops! Our performance results with the training set were a little too good to be true! 147 | 148 | ## [Fit a model with resampling](https://www.tidymodels.org/start/resampling/#fit-resamples) 149 | 150 | Create cross-validation (CV) folds (for 10-fold CV) using `vfold_cv()` from the **rsample** package: 151 | 152 | ```{r} 153 | set.seed(345) 154 | folds <- vfold_cv(cell_train, v = 10) 155 | folds 156 | ``` 157 | 158 | Do you recall working with `workflow()` from the second article, [Preprocess your data with recipes](https://www.tidymodels.org/start/recipes)? 159 | 160 | Use a `workflow()` that bundles together the random forest model and a formula. 161 | 162 | ```{r} 163 | rf_wf <- 164 | workflow() %>% 165 | add_model(rf_mod) %>% 166 | add_formula(class ~ .) 167 | ``` 168 | 169 | Now apply the workflow and fit the model with each fold: 170 | 171 | (This computation will take a bit, so be patient.) 172 | ```{r} 173 | set.seed(456) 174 | rf_fit_rs <- 175 | rf_wf %>% 176 | fit_resamples(folds, 177 | control = control_resamples(verbose = TRUE)) 178 | 179 | rf_fit_rs 180 | ``` 181 | 182 | Do you see the added columns `.metrics` and `.notes`? 183 | 184 | Collect and summarize performance metrics from all 10 folds: 185 | 186 | ```{r} 187 | collect_metrics(rf_fit_rs) 188 | ``` 189 | 190 | Now these are more realistic results! 191 | -------------------------------------------------------------------------------- /04_tune_model_parameters.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Tune model parameters" 3 | output: 4 | html_document: 5 | toc: true 6 | --- 7 | 8 | ```{r setup, include=FALSE} 9 | knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE) 10 | options(tibble.print_min = 5) 11 | ``` 12 | 13 | Get started with building a model in this R Markdown document that accompanies [Tune model parameters](https://www.tidymodels.org/start/tuning/) tidymodels start article. 14 | 15 | If you ever get lost, you can visit the links provided next to section headers to see the accompanying section in the online article. 16 | 17 | Take advantage of the RStudio IDE and use "Run All Chunks Above" or "Run Current Chunk" buttons to easily execute code chunks. If you have been running other tidymodels articles in this project, restart R before working on this article so you don't run out of memory on RStudio Cloud. 18 | 19 | ## [Introduction](https://www.tidymodels.org/start/tuning/#intro) 20 | 21 | Load necessary packages: 22 | 23 | ```{r} 24 | library(tidymodels) # for the tune package, along with the rest of tidymodels 25 | 26 | # Helper packages 27 | library(modeldata) # for the cells data 28 | library(vip) # for variable importance plots 29 | ``` 30 | 31 | ## [The cell image data, revisited](https://www.tidymodels.org/start/tuning/#data) 32 | 33 | Let's revisit the `cells` dataset, which we also used in the previous article [Evaluate your model with resampling](https://www.tidymodels.org/start/resampling). 34 | 35 | Import the same `cells` dataset: 36 | 37 | ```{r} 38 | data(cells, package = "modeldata") 39 | cells 40 | ``` 41 | 42 | 43 | ## [Predicting image segmentation, but better](https://www.tidymodels.org/start/tuning/#why-tune) 44 | 45 | We'll try to predict well-segmented (`WS`) or poorly segmented (`PS`) cells again. (See previous article [Evaluate your model with resampling](https://www.tidymodels.org/start/resampling)). 46 | 47 | This time we'll use a different model and put a bit more effort into improving our model performance. 48 | 49 | Again we start by splitting the data: 50 | 51 | ```{r} 52 | set.seed(123) 53 | cell_split <- initial_split(cells %>% select(-case), 54 | strata = class) 55 | cell_train <- training(cell_split) 56 | cell_test <- testing(cell_split) 57 | ``` 58 | 59 | ## [Tuning hyperparameters](https://www.tidymodels.org/start/tuning/#tuning) 60 | 61 | Let's start by building our model specification with the `decision_tree()` model type, while setting the engine to `rpart` and mode to `classification`. See `?decision_tree()` for possible engines and further details. 62 | 63 | Notice how we define the decision tree hyperparameters `cost_complexity` and `tree_depth` using `tune()`. This way we are letting the model specification know that we would like to tune these hyperparameters in the next steps. 64 | 65 | ```{r} 66 | tune_spec <- 67 | decision_tree( 68 | cost_complexity = tune(), 69 | tree_depth = tune() 70 | ) %>% 71 | set_engine("rpart") %>% 72 | set_mode("classification") 73 | 74 | tune_spec 75 | ``` 76 | 77 | Let's also create a regular grid of values to be used during our tuning process. 78 | This can be easily defined with `grid_regular()`, and helper parameter functions (`cost_complexity()` and `tree_depth()`), that return sensible values for the hyperparameters we would like to tune. 79 | 80 | ```{r} 81 | tree_grid <- grid_regular(cost_complexity(), 82 | tree_depth(), 83 | levels = 5) 84 | tree_grid 85 | 86 | tree_grid %>% 87 | count(tree_depth) 88 | ``` 89 | 90 | See `?trees` for a list of parameter functions related to tree- and rule-based models. 91 | 92 | Let's create the folds we will use for tuning: 93 | 94 | ```{r} 95 | set.seed(234) 96 | cell_folds <- vfold_cv(cell_train) 97 | ``` 98 | 99 | 100 | ## [Model tuning with a grid](https://www.tidymodels.org/start/tuning/#tune-grid) 101 | 102 | 103 | Create a `workflow()` with our model specification `tune_spec` and add a straightforward formula. 104 | 105 | ```{r} 106 | set.seed(345) 107 | 108 | tree_wf <- workflow() %>% 109 | add_model(tune_spec) %>% 110 | add_formula(class ~ .) 111 | ``` 112 | 113 | Finally, let's put the pieces together. 114 | 115 | Apply the workflow and tuning grid across folds: 116 | 117 | (Be patient; with RStudio Cloud Basic settings, this computation may take several minutes.) 118 | ```{r} 119 | tree_res <- 120 | tree_wf %>% 121 | tune_grid( 122 | resamples = cell_folds, 123 | grid = tree_grid, 124 | control = control_grid(verbose = TRUE) 125 | ) 126 | 127 | tree_res 128 | ``` 129 | 130 | Recall how we collected model performance metrics in the previous article? 131 | Similarly we can collect and summarize them here with `collect_metrics()`. 132 | 133 | ```{r} 134 | tree_res %>% 135 | collect_metrics() 136 | ``` 137 | 138 | Too many results to look at! 139 | It would be easier if we plotted them: 140 | 141 | ```{r} 142 | tree_res %>% 143 | collect_metrics() %>% 144 | mutate(tree_depth = factor(tree_depth)) %>% 145 | ggplot(aes(cost_complexity, mean, color = tree_depth)) + 146 | geom_line(size = 1.5, alpha = 0.6) + 147 | geom_point(size = 2) + 148 | facet_wrap(~ .metric, scales = "free", nrow = 2) + 149 | scale_x_log10(labels = scales::label_number()) + 150 | scale_color_viridis_d(option = "plasma", begin = .9, end = 0) 151 | ``` 152 | 153 | The `show_best()` function shows us the top 5 candidate models by default: 154 | 155 | ```{r} 156 | tree_res %>% 157 | show_best("roc_auc") 158 | ``` 159 | 160 | See `?show_best()` for more details. 161 | 162 | Alternatively, we could use `select_best()` to simply pull out the best decision tree model: 163 | 164 | ```{r} 165 | best_tree <- tree_res %>% 166 | select_best("roc_auc") 167 | 168 | best_tree 169 | ``` 170 | 171 | ## [Finalizing our model](https://www.tidymodels.org/start/tuning/#final-model) 172 | 173 | Finally we can go back and finalize our workflow! 174 | This updates the workflow object such that our model hyperparameters are set to the same values contained in `best_tree`. 175 | 176 | ```{r} 177 | final_wf <- 178 | tree_wf %>% 179 | finalize_workflow(best_tree) 180 | 181 | final_wf 182 | ``` 183 | 184 | ### Exploring results 185 | 186 | Let's fit this final model to the training data. 187 | What does the decision tree look like? 188 | 189 | ```{r final-tree, dependson="final-mod"} 190 | final_tree <- 191 | final_wf %>% 192 | fit(data = cell_train) 193 | 194 | final_tree 195 | ``` 196 | 197 | Extract the final model object from the workflow and use `vip()` from the **vip** package to visualize variable importance. 198 | 199 | ```{r} 200 | library(vip) 201 | 202 | final_tree %>% 203 | pull_workflow_fit() %>% 204 | vip() 205 | ``` 206 | 207 | See `?vip::vip` for more details. 208 | 209 | ### The last fit 210 | 211 | Finally, it's time to go back and see the performance of our model with the "untouched" test data. 212 | 213 | Use `last_fit()` to fit the finalized model on the full training data set and evaluate it on the test data. 214 | 215 | ```{r} 216 | final_fit <- 217 | final_wf %>% 218 | last_fit(cell_split) 219 | ``` 220 | 221 | Collect performance metrics and plot ROC curve: 222 | 223 | ```{r} 224 | final_fit %>% 225 | collect_metrics() 226 | 227 | final_fit %>% 228 | collect_predictions() %>% 229 | roc_curve(class, .pred_PS) %>% 230 | autoplot() 231 | ``` 232 | 233 | It looks like we did not overfit during our tuning procedure! 234 | 235 | ## Your turn! 236 | 237 | You can see available parsnip object arguments with: 238 | 239 | ```{r} 240 | args(decision_tree) 241 | ``` 242 | 243 | The `decision_tree()` function has _another_ hyperparameter `min_n` that can also be tuned. 244 | 245 | Now _you_ can try to tune another decision tree model with `min_n`! 246 | -------------------------------------------------------------------------------- /05_case_study.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "A predictive modeling case study" 3 | output: 4 | html_document: 5 | toc: true 6 | --- 7 | 8 | ```{r setup, include=FALSE} 9 | knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE) 10 | options(tibble.print_min = 5) 11 | ``` 12 | 13 | Get started with building a model in this R Markdown document that accompanies [A predictive modeling case study](https://www.tidymodels.org/start/case-study/) tidymodels start article. 14 | 15 | If you ever get lost, you can visit the links provided next to section headers to see the accompanying section in the online article. 16 | 17 | Take advantage of the RStudio IDE and use "Run All Chunks Above" or "Run Current Chunk" buttons to easily execute code chunks. If you have been running other tidymodels articles in this project, restart R before working on this article so you don't run out of memory on RStudio Cloud. 18 | 19 | 20 | ## [Introduction](https://www.tidymodels.org/start/models/#intro) 21 | 22 | Let's put everything we learned from each of the previous [Get Started](https://www.tidymodels.org/start/) articles together and build a predictive model from beginning to end with data on hotel stays. 23 | 24 | Load necessary packages: 25 | 26 | ```{r} 27 | library(tidymodels) 28 | 29 | # Helper packages 30 | library(readr) # for importing data 31 | library(vip) # for variable importance plots 32 | ``` 33 | 34 | ## [The Hotel Bookings Data](https://www.tidymodels.org/start/case-study/#data) 35 | 36 | Let's read the hotel data into R and randomly select 30% of the rows in the data set to avoid long computation times later on. 37 | 38 | Note that your results will differ from the original article, since you are only using 30% of the data. 39 | 40 | ```{r} 41 | # Fix the random numbers by setting the seed 42 | # This enables the analysis to be reproducible when random numbers are used 43 | set.seed(123) 44 | 45 | hotels <- 46 | read_csv('https://tidymodels.org/start/case-study/hotels.csv') %>% 47 | mutate_if(is.character, as.factor) %>% 48 | # randomly select rows 49 | slice_sample(prop = 0.30) 50 | 51 | 52 | dim(hotels) 53 | glimpse(hotels) 54 | ``` 55 | 56 | Let's look at proportions of hotel stays that include children and/or babies: 57 | 58 | ```{r} 59 | hotels %>% 60 | count(children) %>% 61 | mutate(prop = n/sum(n)) 62 | ``` 63 | 64 | 65 | ## [A first model: penalized logistic regression](https://www.tidymodels.org/start/case-study/#first-model) 66 | 67 | Do you recall [Evaluate your model with resampling](/start/resampling/#data-split) article for data splitting? 68 | 69 | Let's reserve 25% of the `hotels` data for the test set: 70 | 71 | ```{r} 72 | set.seed(123) 73 | splits <- initial_split(hotels, strata = children) 74 | 75 | hotel_other <- training(splits) 76 | hotel_test <- testing(splits) 77 | 78 | # training set proportions by children 79 | hotel_other %>% 80 | count(children) %>% 81 | mutate(prop = n/sum(n)) 82 | 83 | # test set proportions by children 84 | hotel_test %>% 85 | count(children) %>% 86 | mutate(prop = n/sum(n)) 87 | ``` 88 | 89 | Now let's reserve another 20% of the `hotel_other` for our validation set. 90 | 91 | ```{r} 92 | set.seed(234) 93 | val_set <- validation_split(hotel_other, 94 | strata = children, 95 | prop = 0.80) 96 | val_set 97 | ``` 98 | 99 | 100 | ### Build the model 101 | 102 | Let's specify a penalized logistic regression model using the lasso method. 103 | Note that we define `penalty = tune()` so we can tune it in the next steps, and since we are using lasso method, we set `mixture = 1`. 104 | 105 | ```{r} 106 | lr_mod <- 107 | logistic_reg(penalty = tune(), mixture = 1) %>% 108 | set_engine("glmnet") 109 | ``` 110 | 111 | For more details try typing `?logistic_reg` on the console. 112 | 113 | ### Create the recipe 114 | 115 | Remember the second article [Preprocess your data with recipes](https://www.tidymodels.org/start/recipes)? 116 | 117 | Let's preprocess the data by creating a recipe: 118 | 119 | ```{r} 120 | holidays <- c("AllSouls", "AshWednesday", "ChristmasEve", "Easter", 121 | "ChristmasDay", "GoodFriday", "NewYearsDay", "PalmSunday") 122 | 123 | lr_recipe <- 124 | recipe(children ~ ., data = hotel_other) %>% 125 | step_date(arrival_date) %>% 126 | step_holiday(arrival_date, holidays = holidays) %>% 127 | step_rm(arrival_date) %>% 128 | step_dummy(all_nominal(), -all_outcomes()) %>% 129 | step_zv(all_predictors()) %>% 130 | step_normalize(all_predictors()) 131 | ``` 132 | 133 | ### Create the workflow 134 | 135 | Let's bundle the model and recipe into a single `workflow()`: 136 | 137 | ```{r} 138 | lr_workflow <- 139 | workflow() %>% 140 | add_model(lr_mod) %>% 141 | add_recipe(lr_recipe) 142 | ``` 143 | 144 | ### Create the grid for tuning 145 | 146 | We can now tune our model, similar to what is shown in the previous article [Tune model parameters](https://www.tidymodels.org/start/tuning). 147 | Let's create a grid with 30 values for the hyperparameter we would like to tune: 148 | 149 | ```{r} 150 | lr_reg_grid <- tibble(penalty = 10^seq(-4, -1, length.out = 30)) 151 | 152 | lr_reg_grid %>% top_n(-5) # lowest penalty values 153 | lr_reg_grid %>% top_n(5) # highest penalty values 154 | ``` 155 | 156 | ### Train and tune the model 157 | 158 | Let's train all these logistic regression models with 30 different hyperparameter values. 159 | We provide the validation set `val_set`, so model diagnostics computed on `val_set` will be available after the fit. 160 | 161 | ```{r} 162 | lr_res <- 163 | lr_workflow %>% 164 | tune_grid(val_set, 165 | grid = lr_reg_grid, 166 | control = control_grid(save_pred = TRUE, verbose = TRUE), 167 | metrics = metric_set(roc_auc)) 168 | 169 | lr_res 170 | ``` 171 | 172 | Now visualize the validation set metrics by plotting the area under the ROC curve against the range of penalty values: 173 | 174 | ```{r} 175 | lr_plot <- 176 | lr_res %>% 177 | collect_metrics() %>% 178 | ggplot(aes(x = penalty, y = mean)) + 179 | geom_point() + 180 | geom_line() + 181 | ylab("Area under the ROC Curve") + 182 | scale_x_log10(labels = scales::label_number()) 183 | 184 | lr_plot 185 | ``` 186 | 187 | Get the best values for this hyperparameter: 188 | 189 | ```{r} 190 | top_models <- 191 | lr_res %>% 192 | show_best("roc_auc", n = 15) %>% 193 | arrange(penalty) 194 | top_models 195 | ``` 196 | 197 | Let's pick candidate model 12 with a penalty value of `0.00137`: 198 | 199 | Note that because you are using less data, your mean ROC AUC will be slightly lower than what's shown in the article. 200 | 201 | ```{r} 202 | lr_best <- 203 | lr_res %>% 204 | collect_metrics() %>% 205 | arrange(penalty) %>% 206 | slice(12) 207 | lr_best 208 | ``` 209 | 210 | And visualize the validation set ROC curve: 211 | 212 | ```{r} 213 | lr_auc <- 214 | lr_res %>% 215 | collect_predictions(parameters = lr_best) %>% 216 | roc_curve(children, .pred_children) %>% 217 | mutate(model = "Logistic Regression") 218 | 219 | autoplot(lr_auc) 220 | ``` 221 | 222 | 223 | ## [A second model: tree-based ensemble](https://www.tidymodels.org/start/case-study/#second-model) 224 | 225 | Let's try to improve our prediction performance by using a random forest model (model *type*), which we also explored in the [Evaluate your model with resampling](https://www.tidymodels.org/start/resampling/) article. 226 | 227 | Check number of cores to work with: 228 | 229 | ```{r} 230 | cores <- parallel::detectCores() 231 | cores 232 | ``` 233 | 234 | Set model specification and provide number of cores for parallelization while tuning. 235 | 236 | ```{r} 237 | rf_mod <- 238 | rand_forest(mtry = tune(), min_n = tune(), trees = 1000) %>% 239 | set_engine("ranger", num.threads = cores) %>% 240 | set_mode("classification") 241 | ``` 242 | 243 | ### Create the recipe and workflow 244 | 245 | Let's create the recipe for the model. 246 | 247 | ```{r} 248 | rf_recipe <- 249 | recipe(children ~ ., data = hotel_other) %>% 250 | step_date(arrival_date) %>% 251 | step_holiday(arrival_date) %>% 252 | step_rm(arrival_date) 253 | ``` 254 | 255 | Then bundle it with the model specification: 256 | 257 | ```{r} 258 | rf_workflow <- 259 | workflow() %>% 260 | add_model(rf_mod) %>% 261 | add_recipe(rf_recipe) 262 | ``` 263 | 264 | ### Train and tune the model 265 | 266 | When we set up our parsnip model, we chose two hyperparameters for tuning: 267 | 268 | ```{r} 269 | rf_mod 270 | 271 | # show what will be tuned 272 | rf_mod %>% 273 | parameters() 274 | ``` 275 | 276 | We will use a space-filling design to tune with 12 candidate models (instead of 25, to reduce computation time). 277 | 278 | Be patient here! Computing these results will take several minutes to complete if you are using the default RStudio Cloud resources (1 GB memory, 1 CPU). 279 | 280 | ```{r} 281 | set.seed(345) 282 | rf_res <- 283 | rf_workflow %>% 284 | tune_grid(val_set, 285 | grid = 12, 286 | control = control_grid(save_pred = TRUE, verbose = TRUE), 287 | metrics = metric_set(roc_auc)) 288 | ``` 289 | 290 | Here are our top 5 random forest models, out of the 12 candidates: 291 | 292 | Note that your results will be different and your accuracy will take a small hit since you are using less data (only 25% of the whole data set) and setting up a smaller grid to tune model hyperparameters. 293 | 294 | ```{r} 295 | rf_res %>% 296 | show_best(metric = "roc_auc") 297 | ``` 298 | 299 | But we're already getting much better results than our penalized logistic regression! 300 | 301 | Let's plot the results: 302 | 303 | ```{r} 304 | autoplot(rf_res) 305 | ``` 306 | 307 | Let's select the best model according to the ROC AUC metric. Our final tuning parameter values are: 308 | 309 | ```{r rf-best} 310 | rf_best <- 311 | rf_res %>% 312 | select_best(metric = "roc_auc") 313 | rf_best 314 | ``` 315 | 316 | Collect predictions for the best model: 317 | Note that we simply provide our best model's parameter values `rf_best` to subset it from a whole list of tuned models. 318 | 319 | ```{r} 320 | rf_res %>% 321 | collect_predictions() 322 | 323 | rf_auc <- 324 | rf_res %>% 325 | collect_predictions(parameters = rf_best) %>% 326 | roc_curve(children, .pred_children) %>% 327 | mutate(model = "Random Forest") 328 | ``` 329 | 330 | Now, we can compare the validation set ROC curves for our top penalized logistic regression model and random forest model: 331 | ```{r} 332 | bind_rows(rf_auc, lr_auc) %>% 333 | ggplot(aes(x = 1 - specificity, y = sensitivity, col = model)) + 334 | geom_path(lwd = 1.5, alpha = 0.8) + 335 | geom_abline(lty = 3) + 336 | coord_equal() + 337 | scale_color_viridis_d(option = "plasma", end = .6) 338 | ``` 339 | 340 | The random forest is uniformly better across event probability thresholds. 341 | 342 | ## [The last fit](https://www.tidymodels.org/start/case-study/#last-fit) 343 | 344 | Let's evaluate the model performance one last time with the held-out test set. 345 | We'll start by building our parsnip model object again from scratch with our best hyperparameter values from our random forest model: 346 | 347 | ```{r} 348 | # the last model 349 | last_rf_mod <- 350 | rand_forest(mtry = 8, min_n = 7, trees = 1000) %>% 351 | set_engine("ranger", num.threads = cores, importance = "impurity") %>% 352 | set_mode("classification") 353 | 354 | # the last workflow 355 | last_rf_workflow <- 356 | rf_workflow %>% 357 | update_model(last_rf_mod) 358 | 359 | # the last fit 360 | set.seed(345) 361 | last_rf_fit <- 362 | last_rf_workflow %>% 363 | last_fit(splits) 364 | 365 | last_rf_fit 366 | ``` 367 | 368 | Note that we added a new argument `importance = "impurity"` to `set_engine` to get variable importance scores. This is an optional, engine-specific argument. To see its documentation, you need to read the documentation for the underlying `ranger()` function. To see it and other options, type `?ranger` in console. 369 | 370 | Now let's collect the metrics: 371 | 372 | ```{r} 373 | last_rf_fit %>% 374 | collect_metrics() 375 | ``` 376 | 377 | Now let's `pluck` the workflow and pull out the fit and visualize the variable importance scores for the top 20 features: 378 | 379 | ```{r} 380 | last_rf_fit %>% 381 | pluck(".workflow", 1) %>% 382 | pull_workflow_fit() %>% 383 | vip(num_features = 20) 384 | ``` 385 | 386 | Let's generate our last ROC curve to visualize: 387 | 388 | ```{r} 389 | last_rf_fit %>% 390 | collect_predictions() %>% 391 | roc_curve(children, .pred_children) %>% 392 | autoplot() 393 | ``` 394 | 395 | Not bad! 396 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | ## creative commons 2 | 3 | # Attribution-ShareAlike 4.0 International 4 | 5 | Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. 6 | 7 | ### Using Creative Commons Public Licenses 8 | 9 | Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. 10 | 11 | * __Considerations for licensors:__ Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. [More considerations for licensors](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors). 12 | 13 | * __Considerations for the public:__ By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. [More considerations for the public](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees). 14 | 15 | ## Creative Commons Attribution-ShareAlike 4.0 International Public License 16 | 17 | By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. 18 | 19 | ### Section 1 – Definitions. 20 | 21 | a. __Adapted Material__ means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. 22 | 23 | b. __Adapter's License__ means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. 24 | 25 | c. __BY-SA Compatible License__ means a license listed at [creativecommons.org/compatiblelicenses](http://creativecommons.org/compatiblelicenses), approved by Creative Commons as essentially the equivalent of this Public License. 26 | 27 | d. __Copyright and Similar Rights__ means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. 28 | 29 | e. __Effective Technological Measures__ means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. 30 | 31 | f. __Exceptions and Limitations__ means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. 32 | 33 | g. __License Elements__ means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution and ShareAlike. 34 | 35 | h. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License. 36 | 37 | i. __Licensed Rights__ means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. 38 | 39 | j. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License. 40 | 41 | k. __Share__ means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. 42 | 43 | l. __Sui Generis Database Rights__ means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. 44 | 45 | m. __You__ means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. 46 | 47 | ### Section 2 – Scope. 48 | 49 | a. ___License grant.___ 50 | 51 | 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: 52 | 53 | A. reproduce and Share the Licensed Material, in whole or in part; and 54 | 55 | B. produce, reproduce, and Share Adapted Material. 56 | 57 | 2. __Exceptions and Limitations.__ For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. 58 | 59 | 3. __Term.__ The term of this Public License is specified in Section 6(a). 60 | 61 | 4. __Media and formats; technical modifications allowed.__ The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. 62 | 63 | 5. __Downstream recipients.__ 64 | 65 | A. __Offer from the Licensor – Licensed Material.__ Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. 66 | 67 | B. __Additional offer from the Licensor – Adapted Material. Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter’s License You apply. 68 | 69 | C. __No downstream restrictions.__ You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. 70 | 71 | 6. __No endorsement.__ Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). 72 | 73 | b. ___Other rights.___ 74 | 75 | 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. 76 | 77 | 2. Patent and trademark rights are not licensed under this Public License. 78 | 79 | 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties. 80 | 81 | ### Section 3 – License Conditions. 82 | 83 | Your exercise of the Licensed Rights is expressly made subject to the following conditions. 84 | 85 | a. ___Attribution.___ 86 | 87 | 1. If You Share the Licensed Material (including in modified form), You must: 88 | 89 | A. retain the following if it is supplied by the Licensor with the Licensed Material: 90 | 91 | i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); 92 | 93 | ii. a copyright notice; 94 | 95 | iii. a notice that refers to this Public License; 96 | 97 | iv. a notice that refers to the disclaimer of warranties; 98 | 99 | v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; 100 | 101 | B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and 102 | 103 | C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. 104 | 105 | 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. 106 | 107 | 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. 108 | 109 | b. ___ShareAlike.___ 110 | 111 | In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply. 112 | 113 | 1. The Adapter’s License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-SA Compatible License. 114 | 115 | 2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material. 116 | 117 | 3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply. 118 | 119 | ### Section 4 – Sui Generis Database Rights. 120 | 121 | Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: 122 | 123 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database; 124 | 125 | b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and 126 | 127 | c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. 128 | 129 | For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. 130 | 131 | ### Section 5 – Disclaimer of Warranties and Limitation of Liability. 132 | 133 | a. __Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.__ 134 | 135 | b. __To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.__ 136 | 137 | c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. 138 | 139 | ### Section 6 – Term and Termination. 140 | 141 | a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. 142 | 143 | b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: 144 | 145 | 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or 146 | 147 | 2. upon express reinstatement by the Licensor. 148 | 149 | For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. 150 | 151 | c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. 152 | 153 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. 154 | 155 | ### Section 7 – Other Terms and Conditions. 156 | 157 | a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. 158 | 159 | b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.t stated herein are separate from and independent of the terms and conditions of this Public License. 160 | 161 | ### Section 8 – Interpretation. 162 | 163 | a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. 164 | 165 | b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. 166 | 167 | c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. 168 | 169 | d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. 170 | 171 | > Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at [creativecommons.org/policies](http://creativecommons.org/policies), Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. 172 | > 173 | > Creative Commons may be contacted at creativecommons.org 174 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # cloudstart 2 | 3 | ## R Markdown documents for RStudio Cloud ☁️ to accompany tidymodels articles 4 | 5 | This repository contains R Markdown documents to accompany the five [Get Started](https://www.tidymodels.org/start/) articles. 6 | 7 | You can open the R Markdown files by clicking on the file name in the Files pane on the right. 👉 8 | 9 | 1. Build a model: `01_build_a_model.Rmd` 10 | 2. Preprocess your data with recipes: `02_preprocess_with_recipes.Rmd` 11 | 3. Evaluate your model with resampling: `03_evaluate_with_resampling.Rmd` 12 | 4. Tune model parameters: `04_tune_model_parameters .Rmd` 13 | 5. A predictive modeling case study: `05_case_study.Rmd` 14 | 15 | These R Markdown documents are here to help you walk through the articles by running identical code chunks. 16 | Feel free to change the code, and explore the tidymodels functions and objects. 17 | If you would like to keep the changes you've made, don't forget to click on "save a permanent copy" on top right! 18 | 19 | Happy learning! 🤓 20 | -------------------------------------------------------------------------------- /cloudstart.Rproj: -------------------------------------------------------------------------------- 1 | Version: 1.0 2 | 3 | RestoreWorkspace: Default 4 | SaveWorkspace: Default 5 | AlwaysSaveHistory: Default 6 | 7 | EnableCodeIndexing: Yes 8 | UseSpacesForTab: Yes 9 | NumSpacesForTab: 2 10 | Encoding: UTF-8 11 | 12 | RnwWeave: knitr 13 | LaTeX: pdflatex 14 | 15 | AutoAppendNewline: Yes 16 | StripTrailingWhitespace: Yes 17 | --------------------------------------------------------------------------------