Coins Classification

Author

Enrique Delamonica

library(tidyverse)
Warning: package 'ggplot2' was built under R version 4.6.2
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.2.1     ✔ readr     2.2.0
✔ forcats   1.0.1     ✔ stringr   1.6.0
✔ ggplot2   4.0.4     ✔ tibble    3.3.1
✔ lubridate 1.9.5     ✔ tidyr     1.3.2
✔ purrr     1.2.2     
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(tidymodels)
Warning: package 'tidymodels' was built under R version 4.6.2
── Attaching packages ────────────────────────────────────── tidymodels 1.5.0 ──
✔ broom        1.0.13     ✔ rsample      1.3.2 
✔ dials        1.4.5      ✔ tailor       0.1.0 
✔ infer        1.1.0      ✔ tune         2.1.0 
✔ modeldata    1.6.0      ✔ workflows    1.3.0 
✔ parsnip      1.7.0      ✔ workflowsets 1.1.1 
✔ recipes      1.4.0      ✔ yardstick    1.5.0 
Warning: package 'dials' was built under R version 4.6.2
Warning: package 'modeldata' was built under R version 4.6.2
Warning: package 'recipes' was built under R version 4.6.2
Warning: package 'rsample' was built under R version 4.6.2
Warning: package 'tailor' was built under R version 4.6.2
Warning: package 'tune' was built under R version 4.6.2
Warning: package 'workflows' was built under R version 4.6.2
Warning: package 'workflowsets' was built under R version 4.6.2
Warning: package 'yardstick' was built under R version 4.6.2
── Conflicts ───────────────────────────────────────── tidymodels_conflicts() ──
✖ scales::discard() masks purrr::discard()
✖ dplyr::filter()   masks stats::filter()
✖ recipes::fixed()  masks stringr::fixed()
✖ dplyr::lag()      masks stats::lag()
✖ yardstick::spec() masks readr::spec()
✖ recipes::step()   masks stats::step()
library(tidyr)
library(dplyr)
library(ggplot2)
library(rpart)

Attaching package: 'rpart'

The following object is masked from 'package:dials':

    prune
library(rpart.plot)
Warning: package 'rpart.plot' was built under R version 4.6.2
url<- "https://raw.githubusercontent.com/Robby955/canadian-coin-database/47779ea7ead4de9d4288a6d7eb9a077e968b825e/data/coins.csv"
Coins <- read_csv(file = url, show_col_types = FALSE, progress = FALSE)
Coins
# A tibble: 5,791 × 18
   id        name   year denomination category metal purity weight_g diameter_mm
   <chr>     <chr> <dbl> <chr>        <chr>    <chr>  <dbl>    <dbl>       <dbl>
 1 limited-… Limi…    NA <NA>         set      <NA>  NA        NA           NA  
 2 wonders-… Wond…    NA <NA>         collect… silv…  0.999    10           NA  
 3 wonders-… Wond…    NA <NA>         collect… silv…  0.999    10           NA  
 4 wonders-… Wond…    NA <NA>         collect… silv…  0.999    10           NA  
 5 wonders-… Wond…    NA <NA>         collect… silv…  0.999    10           NA  
 6 1-cent-1… 1 ce…  1858 1 cent       circula… copp… NA         4.54        25.4
 7 5-cents-… 5 ce…  1858 5 cents      circula… silv…  0.925     1.16        15.5
 8 10-cents… 10 c…  1858 10 cents     circula… silv…  0.925     2.32        18  
 9 20-cents… 20 c…  1858 20 cents     circula… silv…  0.925     4.65        23.3
10 1-cent-1… 1 ce…  1859 1 cent       circula… copp… NA         4.54        25.4
# ℹ 5,781 more rows
# ℹ 9 more variables: mintage <dbl>, series <chr>, monarch <chr>,
#   obverse_designer <chr>, reverse_designer <chr>, edge <chr>, finish <chr>,
#   composition <chr>, country <chr>

When I tried to work with the data frame, there was an error as R was expecting factors. Thus, I used “convert character to factor in r dplyr” as a query in Google and I found:

https://gist.github.com/ramhiser/93fe37be439c480dc26c4bed8aab03dd

I used it to create a new data frame (“Coins_factor”):

Coins_factor <- Coins |> 
  mutate(across(where(is_character),as_factor))

Then I split the date frame, using the command data_split. I found this command, and all the following ones, unless otherwise indicated, in: https://www.datacamp.com/tutorial/decision-trees-R

set.seed(1235)
data_split <- initial_split(Coins_factor, prop = 0.75)
train_data <- training(data_split)
test_data <- testing(data_split)

As the data frame has information on all Canadian coins, including some minted by provinces (which are included in a variable called “countries”, with five categories), my hypothesis was that “countries” should have been an easy variable to classify. I though that, in particular, “year” would have been a good predictor as provinces would have been unlikely to mint their own coins as the central government became stronger and more institutionalized with time.

Then, I used a “classification” model. However, while the syntax below (outside of a chunk so it does not mess up rendering) seemed to work, when I tried to fit the model (the following command, also outside of a chunk), R always got stuck. I even let it run overnight once, to no avail.

{r} “Create a decision tree model specification”

tree_specCL <- decision_tree() |>

set_engine(“rpart”) |>

set_mode(“classification”)

{r} “Fit the model to the training data”

tree_fit <- tree_specCL |>

fit(country~., data = train_data)

Consequently, I chose a continuous variable (“purity”). In this case I used the “regression” model. I also found additional information about “rpatr” in https://www.rdocumentation.org/packages/rminer/versions/1.5.0/topics/fit

# Create a decision tree model specification
tree_specRG <- decision_tree() |>
 set_engine("rpart") |>
 set_mode("regression")
# Fit the model to the training data
tree_fit <- tree_specRG |>
 fit(purity~., data = train_data)

Then, I used the testing data to make predictions and evaluate the performance of the model.

#Make predictions on the testing data
predictions <- tree_fit %>%
 predict(test_data) %>%
 pull(.pred)

I calculated the RMSE and R-Squared.

# Calculate RMSE and R-squared
metrics <- metric_set(rmse, rsq)
model_performance <- test_data %>%
 mutate(predictions = predictions) %>%
 metrics(truth = purity, estimate = predictions)

The results can be seen with

print(model_performance)
# A tibble: 2 × 3
  .metric .estimator .estimate
  <chr>   <chr>          <dbl>
1 rmse    standard      0.0331
2 rsq     standard      0.852 

These results do not seem to be terribly bad. The rsq row presents the R-squared of the regression used in the classification. If it is an adjusted R-squared (instead of a simple one which does not decline as more variable are added to the model), it is a high value - at least in the context of social and economic work, as the model explains 85% of the variability of the purity of the coins. However, I am not sure if it is a sufficiently high value for classification of coins.

The rmse (the Root Mean Squared Error, which measures the average difference between predicted and true values) is very low, which is good (according to the explanation in the Datacamp link). The value of 0.03, prima facie, is low. However, using “?Coins” I could not find information about the unit of measure of the variable, so I am not sure. Again, I have no information to assess the practical significance of an average distance of 0.03 when describing the purity of the metal content of coins.