Assignment 09

Author

Matthew Albano

Open the assign09.qmd file and complete the exercises.

We will be working the the diamonds dataset and tidymodels to predict the carat of a diamond based on other variables.

The Grading Rubric is available at the end of this document.

Exercises

We will start by loading our required packages.

library(tidymodels)
library(glmnet)

Exercise 1

Create a histogram using geom_histogram(binwidth = 0.1), showing the distribution of carat in the diamonds dataset. Set the fill to “blue” and the color to “black”. In the narrative below describe what the distribution looks like.

library(ggplot2)

ggplot(diamonds, aes(carat)) + 
  geom_histogram(binwidth = 0.1, fill = "blue", color = "black")

  ggtitle("Distribution of Diamond Carats")
$title
[1] "Distribution of Diamond Carats"

attr(,"class")
[1] "labels"

Exercise 2

Repeat the histogram, but this time plot sqrt(carat) instead of carat. Describe if and how the distribution changed.

ggplot(diamonds, aes(sqrt(carat))) +
  geom_histogram(binwidth = 0.1, fill = "blue", color = "black") +
  ggtitle("Distribution of Diamond Carats (square root)")

Exercise 3

Below set.seed(), split the data into two datasets: train_data will contain 80% of the data using stratified sampling on carat, test_data will contain the remaining 20% of the data.

# set a seed for reproducibility
set.seed(1234)

library (tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ forcats   1.0.0     ✔ readr     2.1.5
✔ lubridate 1.9.4     ✔ stringr   1.5.1
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ readr::col_factor() masks scales::col_factor()
✖ purrr::discard()    masks scales::discard()
✖ Matrix::expand()    masks tidyr::expand()
✖ dplyr::filter()     masks stats::filter()
✖ stringr::fixed()    masks recipes::fixed()
✖ dplyr::lag()        masks stats::lag()
✖ Matrix::pack()      masks tidyr::pack()
✖ readr::spec()       masks yardstick::spec()
✖ Matrix::unpack()    masks tidyr::unpack()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(rsample)

split <- diamonds |>
  initial_split(prop = 0.8, strata = "carat")

train_data <- training(split)
test_data <- testing(split)

nrow(train_data)
[1] 43150
nrow(test_data)
[1] 10790

Exercise 4

Exercise 4 is already completed for you. It creates a recipe called lm_all_recipe that uses carat as the target variable and all other variables as predictors. It creates dummy variables for all nominal predictors so we can use the recipe for reguralized regression.

# recipe using all predictors
lm_all_recipe <- recipe(carat ~ ., data = train_data) |> 
  step_dummy(all_nominal_predictors())

Exercise 5

Below is a model specified for reguralized regression model called lasso_spec. Add a second specification called lm_spec for just plain old linear regression using the “lm” engine.

# Define the lasso model specification
lasso_spec <- linear_reg(penalty = 0.01, mixture = 1) |> 
  set_engine("glmnet")

# Define the linear regression model specification.
lm_spec <- linear_reg(penalty = 0.01, mixture = 1) |>
  set_engine("lm")

Exercise 6

Create two workflows. lm_all_workflow should use the lm_spec model specification and lm_all_recipe. lasso_all_workflow should use the lasso_spec model and lm_all_recipe.

lm_all_recipe <- recipe(carat ~ ., data = train_data) |> 
  step_dummy(all_nominal_predictors())

lasso_spec <- linear_reg(penalty = 0.01, mixture = 1) |> 
  set_engine("glmnet")

lm_spec <- linear_reg(penalty = 0.01, mixture = 1) |>
  set_engine("lm")

lm_all_workflow <- workflow(lm_all_recipe, lm_spec)

lasso_all_workflow <- workflow(lm_all_recipe, lasso_spec)

lm_all_workflow
══ Workflow ════════════════════════════════════════════════════════════════════
Preprocessor: Recipe
Model: linear_reg()

── Preprocessor ────────────────────────────────────────────────────────────────
1 Recipe Step

• step_dummy()

── Model ───────────────────────────────────────────────────────────────────────
Linear Regression Model Specification (regression)

Main Arguments:
  penalty = 0.01
  mixture = 1

Computational engine: lm 

Exercise 7

Fit two models. lm_all_fit should use the lm_all_workflow, and lasso_all_fit should use the lasso_all_workflow

lm_all_fit <- fit(lm_all_workflow, train_data)

lasso_all_fit <- fit(lasso_all_workflow, train_data)

lm_all_fit
══ Workflow [trained] ══════════════════════════════════════════════════════════
Preprocessor: Recipe
Model: linear_reg()

── Preprocessor ────────────────────────────────────────────────────────────────
1 Recipe Step

• step_dummy()

── Model ───────────────────────────────────────────────────────────────────────

Call:
stats::lm(formula = ..y ~ ., data = data)

Coefficients:
(Intercept)        depth        table        price            x            y  
 -1.657e+00    1.198e-02    2.313e-03    4.435e-05    2.465e-01    3.024e-03  
          z        cut_1        cut_2        cut_3        cut_4      color_1  
  2.685e-03   -1.990e-02    8.627e-03   -6.279e-03    1.369e-03    1.069e-01  
    color_2      color_3      color_4      color_5      color_6    clarity_1  
  4.031e-02    4.689e-03   -5.070e-03    5.685e-03    2.143e-03   -1.757e-01  
  clarity_2    clarity_3    clarity_4    clarity_5    clarity_6    clarity_7  
  1.081e-01   -5.515e-02    1.695e-02   -1.220e-02   -1.620e-03   -4.479e-05  
lasso_all_fit
══ Workflow [trained] ══════════════════════════════════════════════════════════
Preprocessor: Recipe
Model: linear_reg()

── Preprocessor ────────────────────────────────────────────────────────────────
1 Recipe Step

• step_dummy()

── Model ───────────────────────────────────────────────────────────────────────

Call:  glmnet::glmnet(x = maybe_matrix(x), y = y, family = "gaussian",      alpha = ~1) 

   Df  %Dev  Lambda
1   0  0.00 0.46230
2   1 16.15 0.42130
3   1 29.56 0.38380
4   1 40.70 0.34970
5   1 49.94 0.31870
6   1 57.62 0.29040
7   1 63.99 0.26460
8   2 69.34 0.24110
9   2 74.00 0.21960
10  2 77.87 0.20010
11  2 81.08 0.18240
12  2 83.75 0.16620
13  2 85.96 0.15140
14  2 87.80 0.13790
15  2 89.32 0.12570
16  2 90.59 0.11450
17  2 91.64 0.10440
18  2 92.51 0.09508
19  2 93.24 0.08663
20  3 93.84 0.07894
21  3 94.35 0.07193
22  3 94.77 0.06554
23  3 95.12 0.05971
24  3 95.41 0.05441
25  3 95.65 0.04958
26  3 95.85 0.04517
27  3 96.02 0.04116
28  3 96.15 0.03750
29  3 96.27 0.03417
30  3 96.36 0.03113
31  3 96.44 0.02837
32  4 96.54 0.02585
33  5 96.68 0.02355
34  5 96.80 0.02146
35  5 96.90 0.01955
36  5 96.98 0.01782
37  7 97.07 0.01623
38  7 97.17 0.01479
39  7 97.25 0.01348
40  7 97.32 0.01228
41  7 97.37 0.01119
42  8 97.42 0.01020
43  9 97.47 0.00929
44  9 97.52 0.00846
45  9 97.55 0.00771
46  9 97.58 0.00703

...
and 29 more lines.

Exercise 8

Make predictions into two new tibbles: lm_all_predictions and lasso_all_predictions

lm_all_predictions <- predict(lm_all_fit, new_data = test_data) |> 
  bind_cols(test_data)
lasso_all_predictions <- predict(lasso_all_fit, new_data = test_data) |> 
  bind_cols(test_data)

head(lm_all_predictions)
# A tibble: 6 × 11
  .pred carat cut       color clarity depth table price     x     y     z
  <dbl> <dbl> <ord>     <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>
1 0.130  0.23 Good      E     VS1      56.9    65   327  4.05  4.07  2.31
2 0.300  0.29 Premium   I     VS2      62.4    58   334  4.2   4.23  2.63
3 0.218  0.24 Very Good I     VVS1     62.3    57   336  3.95  3.98  2.47
4 0.248  0.26 Very Good H     SI1      61.9    55   337  4.07  4.11  2.53
5 0.178  0.23 Very Good H     VS1      59.4    61   338  4     4.05  2.39
6 0.396  0.3  Good      J     SI1      64      55   339  4.25  4.28  2.73
head(lasso_all_predictions)
# A tibble: 6 × 11
  .pred carat cut       color clarity depth table price     x     y     z
  <dbl> <dbl> <ord>     <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>
1 0.138  0.23 Good      E     VS1      56.9    65   327  4.05  4.07  2.31
2 0.270  0.29 Premium   I     VS2      62.4    58   334  4.2   4.23  2.63
3 0.178  0.24 Very Good I     VVS1     62.3    57   336  3.95  3.98  2.47
4 0.237  0.26 Very Good H     SI1      61.9    55   337  4.07  4.11  2.53
5 0.173  0.23 Very Good H     VS1      59.4    61   338  4     4.05  2.39
6 0.323  0.3  Good      J     SI1      64      55   339  4.25  4.28  2.73

Exercise 9

Compute and display the rmse for each model. Discuss which one performed better and why in the narrative below.

lm_rmse <- lm_all_predictions |> 
  rmse(carat, .pred)
lasso_rmse <- lasso_all_predictions |> 
  rmse(carat, .pred)
lm_rmse
# A tibble: 1 × 3
  .metric .estimator .estimate
  <chr>   <chr>          <dbl>
1 rmse    standard      0.0744
lasso_rmse
# A tibble: 1 × 3
  .metric .estimator .estimate
  <chr>   <chr>          <dbl>
1 rmse    standard      0.0812

lm_rmse performed better than lasso_rmse. The lower value that lm_rmse provided meant more precision compared to lasso_rmse.

Submission

To submit your assignment:

  • Change the author name to your name in the YAML portion at the top of this document
  • Render your document to html and publish it to RPubs.
  • Submit the link to your Rpubs document in the Brightspace comments section for this assignment.
  • Click on the “Add a File” button and upload your .qmd file for this assignment to Brightspace.

Grading Rubric

Item
(percent overall)
100% - flawless 67% - minor issues 33% - moderate issues 0% - major issues or not attempted
Document formatting: correctly implemented instructions
(9%)
Exercises - 9% each
(81% )
Submitted properly to Brightspace
(10%)
NA NA You must submit according to instructions to receive any credit for this portion.