RMT Homework: Clustering - Durim Kaleziq

Introduction

For my homework, I used diamonds data from R. I will only take some columns because not all are understandable and I want it to be understandable. I will take these variables from original dataset: “price, carat, x, y, z, cut” and rename them. Carat means weight of diamond, x means length in mm, y means width in mm, and z means depth in mm - it will be more understandable.

Because my data will have a lot of units, I will take a smaller sample of 1000. I will now import data and later explain it.

mydata <- force(diamonds)
mydata <- mydata[c(1, 2, 7, 8, 9, 10)] #taking only the variables I listed above for this exercise - the others are hard to imagine
set.seed(1) #Setting point of sampling so my sample won't change
mydata <- mydata[sample(nrow(mydata), 1000), ] #Taking sample of 1000
mydata$ID <- seq(1, nrow(mydata)) #adding ID to data
mydata <- mydata[c("ID", "price", "carat", "x", "y", "z", "cut")] #setting order of columns
colnames(mydata) <- c("ID", "Price", "Carat", "Length", "Width", "Depth", "Cut") #renaming columns
head(mydata, 6)
## # A tibble: 6 × 7
##      ID Price Carat Length Width Depth Cut      
##   <int> <int> <dbl>  <dbl> <dbl> <dbl> <ord>    
## 1     1   638  0.41   4.72  4.75  2.95 Very Good
## 2     2  1402  0.5    5.05  5.08  3.18 Very Good
## 3     3  3530  1.03   6.42  6.35  4.16 Fair     
## 4     4  5037  1.1    6.6   6.64  4.11 Ideal    
## 5     5 13757  1.51   7.24  7.17  4.56 Very Good
## 6     6   457  0.3    4.3   4.33  2.68 Ideal

Data set and variables explanation

Data set:

  • Price: Price of diamond in US dollars.

  • Carat: Weight of diamond (not clearly specified, but probably unit is “carat”, because of variable name).

  • Length: Length in milimeters.

  • Width: Width in milimeters.

  • Depth: Depth in milimeters.

  • Cut: Quality of the cut (fair/good/very good/premium/ideal).

The unit of observation is a diamond

My samples observes 1000 units of the 6 variables (+ID).

Variables (no ID):

  • Price, carat, length, width, and depth (first 5 variables) are all numeric variables. They are not the same scale so I will standardize them later.

  • Cut is a categorical variable with 5 categories. I will factor it with dummy variables to include it.

Data source: R documentation - diamonds {ggplot2}

Why clustering?

I decided to use clustering because I think I can sort diamonds in groups. I want to use all 5 numeric variables as cluster variables: Price, Carat, Length, Width, and Depth. I excluded some variables (columns) in start because I believed they were not intuitive to understand. I have no theory to use, so I decided to use all five cluster variables left. Maybe our data will not be perfect for clustering and maybe there will be correlation, but because I have no theory, I cannot do a lot about that. This is my exercise to show understanding and my data is not necessarily perfect.

I will then verify my clustering using my categorical variable: Cut.

My research question: Can I group diamonds based on their price, carat, length, width, and depth?

I will factor my categorical variable.

mydata$Cut <- factor(mydata$Cut, 
                             levels = c("Fair", "Good", "Very Good", "Premium", "Ideal"),
                             labels = c("Fair", "Good", "Very Good", "Premium", "Ideal"))

In last step here, I will show some descriptive statistics (not for ID)

summary(mydata[ , -1])
##      Price           Carat            Length           Width            Depth             Cut     
##  Min.   :  362   Min.   :0.2300   Min.   : 0.000   Min.   : 0.000   Min.   :0.00   Fair     : 33  
##  1st Qu.:  957   1st Qu.:0.4000   1st Qu.: 4.737   1st Qu.: 4.730   1st Qu.:2.92   Good     :100  
##  Median : 2677   Median :0.7150   Median : 5.760   Median : 5.795   Median :3.55   Very Good:246  
##  Mean   : 4186   Mean   :0.8348   Mean   : 5.795   Mean   : 5.799   Mean   :3.58   Premium  :244  
##  3rd Qu.: 5420   3rd Qu.:1.0700   3rd Qu.: 6.562   3rd Qu.: 6.582   3rd Qu.:4.06   Ideal    :377  
##  Max.   :18757   Max.   :5.0100   Max.   :10.740   Max.   :10.540   Max.   :6.98

Some explanations:

  • Mean of Price: On average, a diamond in my sample costs 4186$.

  • 1st quartile of Length: 25% of diamonds in my sample are up to 4,74 milimeters in length, and the other 75% are longer.

Max of Width: The widest diamond in my sample is 10,54 milimeters wide.

Checking if our data is good for clustering

In clustering, we want units inside a group to be similar, but the groups to be different from one another. Units inside a group should be homogeneous. Groups should be heterogeneous to one another.

We choose only numeric or only categorical cluster variables - I chose numeric. I will check if data is good for clustering with Hopkins statistics. But first, I must standardize my variables, because they are not all on same scale. I standardize to make sure they have same impact on my final results.

mydata$Price_z <- scale(mydata$Price)
mydata$Carat_z <- scale(mydata$Carat)
mydata$Length_z <- scale(mydata$Length)
mydata$Width_z <- scale(mydata$Width)
mydata$Depth_z <- scale(mydata$Depth)

Now I want to check that cluster variables are not too strongly correlated. Ideally, I want values below 0,3 (weak correlation).

rcorr(as.matrix(mydata[ , c("Price_z", "Carat_z", "Length_z", "Width_z", "Depth_z")]),
      type = "pearson")
##          Price_z Carat_z Length_z Width_z Depth_z
## Price_z     1.00    0.93     0.87    0.87    0.85
## Carat_z     0.93    1.00     0.96    0.95    0.94
## Length_z    0.87    0.96     1.00    1.00    0.98
## Width_z     0.87    0.95     1.00    1.00    0.98
## Depth_z     0.85    0.94     0.98    0.98    1.00
## 
## n= 1000 
## 
## 
## P
##          Price_z Carat_z Length_z Width_z Depth_z
## Price_z           0       0        0       0     
## Carat_z   0               0        0       0     
## Length_z  0       0                0       0     
## Width_z   0       0       0                0     
## Depth_z   0       0       0        0

I think my cluster variables are too much correlated. I will try using 3 cluster variables only - price, carat, and length. Length is too correlated to width and depth. I will drop width and depth and their standardized values too.

mydata <- mydata[c(1, 2, 3, 4, 7, 8, 9, 10)]
rcorr(as.matrix(mydata[ , c("Price_z", "Carat_z", "Length_z")]),
      type = "pearson")
##          Price_z Carat_z Length_z
## Price_z     1.00    0.93     0.87
## Carat_z     0.93    1.00     0.96
## Length_z    0.87    0.96     1.00
## 
## n= 1000 
## 
## 
## P
##          Price_z Carat_z Length_z
## Price_z           0       0      
## Carat_z   0               0      
## Length_z  0       0

Correlation between our 3 cluster variables is still extremely high. Price is very strongly correlated to carat (very strong correlation is from 0.9 to 1) and strongly correlated to length (strong correlation is from 0.7 to 0.9). Carat is very strongly correlated to length.

There is not much I can do about this, because I have such data. It is logical that bigger and heavier diamonds will have a higher price. Since all variables are correlated, this should not stop me from clustering. I can still do clusters, but because variables are correlated, I will just probably get boring clusters - of small and high values of all variables. Maybe it is not a very meaningful analysis, but I can still show understanding of R with it.

I will now use dissimilarity to check for outliers in my data.

mydata$Dissimilarity <- sqrt(mydata$Price_z^2 + mydata$Carat_z^2 + mydata$Length_z^2)

head(mydata[order(-mydata$Dissimilarity), c(1, 2, 3, 4, 5, 9)], 10) #Showing 10 units with most dissimilarity
## # A tibble: 10 × 6
##       ID Price Carat Length Cut     Dissimilarity[,1]
##    <int> <int> <dbl>  <dbl> <ord>               <dbl>
##  1   149 18018  5.01  10.7  Fair                 9.71
##  2   130 15686  1.2    0    Premium              5.68
##  3   804 18756  2.61   8.85 Ideal                5.52
##  4   276 18255  2.51   8.76 Premium              5.29
##  5   233 18020  2.51   8.73 Premium              5.25
##  6   177 16314  2.65   8.82 Premium              5.22
##  7   607 17504  2.33   8.52 Ideal                4.87
##  8   782 16789  2.37   8.58 Ideal                4.84
##  9    74 14543  2.51   8.81 Premium              4.82
## 10   386 17666  2.29   8.43 Premium              4.81

I will remove units with dissimilarity values of 5 and above as outliers: ID values are 149, 130, 804, 276, 233 and 177.

After, I must standardize variables again, because removing units changes standardized values.

mydata <- mydata %>%
    filter(!ID %in% c(149, 130, 804, 276, 233, 177))

head(mydata[order(-mydata$Dissimilarity), c(1, 2, 3, 4, 5, 9)], 6)
## # A tibble: 6 × 6
##      ID Price Carat Length Cut     Dissimilarity[,1]
##   <int> <int> <dbl>  <dbl> <ord>               <dbl>
## 1   607 17504  2.33   8.52 Ideal                4.87
## 2   782 16789  2.37   8.58 Ideal                4.84
## 3    74 14543  2.51   8.81 Premium              4.82
## 4   386 17666  2.29   8.43 Premium              4.81
## 5   466 18462  2.16   8.34 Ideal                4.76
## 6   874 17233  2.25   8.47 Premium              4.72

I removed those units, now I must standardize again.

mydata$Price_z <- scale(mydata$Price)
mydata$Carat_z <- scale(mydata$Carat)
mydata$Length_z <- scale(mydata$Length)

Next, I will do Euclidean distances and do dissimilarity matrix.

distance <- get_dist(mydata[c("Price_z", "Carat_z", "Length_z")],
                     method = "euclidian")

distance2 <- distance^2 #Here I make also squared Euclidean distances

fviz_dist(distance2)

It looks like I will be able to divide my data to clusters. The picture above appears to show 4 clusters, but I will check later. Like I said before with high correlation - clustering is possible, it is just not as informative as it could be with good data. I will now check Hopkins statistics.

get_clust_tendency(mydata[c("Price_z", "Carat_z", "Length_z")],
                   n = nrow(mydata) - 1,
                   graph = FALSE)
## $hopkins_stat
## [1] 0.9619106
## 
## $plot
## NULL

As general rule, I want Hopkins above 0,5. I can see Hopkins is 0.96, which makes it look like my data is very clusterable, but this is because clusters are easy to make when all cluster variables are correlated - we can easily find small, medium, and high clusters in values. So Hopkins can be misleading; data is clusterable, but the information I get in the end can be very simple. Maybe I am wrong and the clusters will be good, I will see.

Clustering

I will now do a dendrogram to decide the number of cluster groups I will use.

WARD <- mydata[c("Price_z", "Carat_z", "Length_z")] %>%
           get_dist(method = "euclidian") %>%
           hclust(method = "ward.D2")

WARD
## 
## Call:
## hclust(d = ., method = "ward.D2")
## 
## Cluster method   : ward.D2 
## Distance         : euclidean 
## Number of objects: 994

I have Ward’s distances, that I now use for dendrogram.

fviz_dend(WARD)
## Warning: The `<scale>` argument of `guides()` cannot be `FALSE`. Use "none" instead as of ggplot2 3.3.4.
## ℹ The deprecated feature was likely used in the factoextra package.
##   Please report the issue at <https://github.com/kassambara/factoextra/issues>.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was generated.

I cut this dendrogram to 4 groups - somewhere around vertical value between around 15 adn 20. On vertical axis I have information on how heterogeneous units are in groups, and I want this to be smaller so I get more different groups. Cutting more high up will give me less groups with more heterogeneous units (units will be more different), which I don’t want. Cutting lower would not make sense because I would not make much difference in heterogeneity (the horizontal lines of those groups are too close together).

I can show how I want to cut my dendrogram with colors now.

fviz_dend(WARD,
          k = 4,
          cex = 0.5,
          palette = "jama",
          color_labels_by_k = TRUE,
          rect = TRUE)

I will let program know I am cutting into 4 groups.

mydata$ClusterWard <- cutree(WARD,
                             k = 4)
head(mydata[c(1, 2, 3, 4, 10)])
## # A tibble: 6 × 5
##      ID Price Carat Length ClusterWard
##   <int> <int> <dbl>  <dbl>       <int>
## 1     1   638  0.41   4.72           1
## 2     2  1402  0.5    5.05           1
## 3     3  3530  1.03   6.42           2
## 4     4  5037  1.1    6.6            2
## 5     5 13757  1.51   7.24           3
## 6     6   457  0.3    4.3            1

With ClusterWard variable I can see a number of group of each unit. For example unit ID 1 went in group 1 and unit ID 3 went in group 2.

I will now do initial leaders that hierarchical clustering with dendrogram gives me.

Initial_leaders <- aggregate(mydata[ , c("Price_z", "Carat_z", "Length_z")],
                             by = list(mydata$ClusterWard),
                             FUN = mean)
Initial_leaders
##   Group.1    Price_z    Carat_z   Length_z
## 1       1 -0.8023830 -0.9777338 -1.1255047
## 2       2  0.3377115  0.5033922  0.6525903
## 3       3  2.1256649  2.0285806  1.7535543
## 4       4 -0.4361740 -0.3653993 -0.2193954

I have initial leaders for each variable - price, carat and length that will be used for groups 1-4. I can now do K-means that will reassign my units to groups.

K_MEANS <- hkmeans(mydata[c("Price_z", "Carat_z", "Length_z")], 
                   k = 4,
                   hc.metric = "euclidean",
                   hc.method = "ward.D2")

K_MEANS
## Hierarchical K-means clustering with 4 clusters of sizes 324, 300, 107, 263
## 
## Cluster means:
##      Price_z    Carat_z   Length_z
## 1 -0.8023830 -0.9777338 -1.1255047
## 2  0.4130089  0.5769313  0.7170169
## 3  2.2898494  2.1052740  1.8081490
## 4 -0.4142375 -0.3101062 -0.1669715
## 
## Clustering vector:
##   [1] 1 1 2 2 3 1 4 2 2 3 3 3 1 2 4 1 3 4 1 4 1 4 1 2 1 3 2 3 2 4 2 3 4 2 2 2 2 4 4 3 1 3 2 1 1 4 1 2 2 1 1 2 1 2 1 1 1
##  [58] 1 1 1 1 2 1 4 1 1 2 4 2 4 3 2 2 3 4 2 1 2 4 1 3 1 1 2 2 1 2 4 2 2 3 2 1 1 1 2 4 4 1 1 1 2 2 2 1 2 1 2 4 2 4 2 2 2
## [115] 2 2 4 1 3 2 2 2 2 2 1 2 2 1 1 2 4 1 3 1 2 4 4 4 4 3 2 2 3 2 2 4 4 2 1 1 2 2 1 1 1 2 3 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 2 4 4 3 1 2 4 3 2 1 2 4 4 3 3 2 2 3 4 4 2 1 1 1 2 4 4 2 1 1 2 1 4 4 1 2 2
## [685] 1 2 1 2 2 1 3 1 4 4 4 4 1 4 1 4 3 1 2 4 1 4 1 1 1 4 3 3 2 2 4 2 2 3 2 2 1 1 1 2 2 3 1 1 1 2 2 1 4 1 1 1 4 3 1 2 2
## [742] 1 2 2 1 4 4 2 3 1 1 4 2 2 1 4 3 2 2 2 3 2 4 4 1 2 2 2 3 1 1 2 1 3 4 4 3 1 2 1 4 2 4 2 2 1 2 2 2 2 4 1 2 2 1 1 4 2
## [799] 1 2 4 2 1 1 1 2 1 1 1 3 4 2 4 4 4 3 4 4 4 1 2 2 2 2 2 4 2 1 1 2 1 4 1 4 4 1 2 1 2 1 1 1 4 2 1 1 4 2 4 4 2 1 4 1 4
## [856] 1 4 4 3 1 2 3 2 2 1 4 2 3 1 3 2 4 1 2 1 1 2 4 4 4 2 4 4 2 4 2 1 1 3 2 4 1 4 2 3 1 4 2 2 4 2 4 1 2 2 3 1 2 4 4 2 4
## [913] 2 1 1 1 4 4 2 1 2 1 2 1 1 1 1 4 1 4 3 2 3 1 4 1 1 4 2 4 4 2 1 3 2 4 2 2 4 1 4 4 1 1 2 1 3 1 4 1 3 1 3 1 3 1 2 4 1
## [970] 4 4 4 2 4 1 4 4 1 1 2 4 2 1 3 3 4 2 4 3 4 2 2 1 2
## 
## Within cluster sum of squares by cluster:
## [1]  21.80399 113.62076  99.98757  46.69919
##  (between_SS / total_SS =  90.5 %)
## 
## Available components:
## 
##  [1] "cluster"      "centers"      "totss"        "withinss"     "tot.withinss" "betweenss"    "size"        
##  [8] "iter"         "ifault"       "data"         "hclust"

On top, I can see my group sizes: 324 for group 1, 300 for group 2, 107 for group 3 and 263 for group 4.

I can see that initial leaders changed in groups 2, 3, and 4. They stayed the same for group 1.

Clustering vector shows me group for each unit. For example unit 3 is in group 2 and unit 119 is in group 3.

My ratio of between group sum of squares divided by total sum of squares should be as high as possible. This is because we want groups to be different from each other while units in a group should be similar. The higher my ratio is, the more of total sum of squares will be given to sum of squares between groups (the groups will be more different from each other). My value is 90,5%, which is good - the groups will be different.

Now I will show this graphically.

fviz_cluster(K_MEANS, 
             palette = "jama", 
             repel = FALSE,
             ggtheme = theme_classic())

Like I said before with correlation - my groups are very different from each other because all cluster variables are very correlated. We have some units that have low Carat and Length (they are not long, so they are also not heavy in weight) and their price is low in consequence. Others are the opposite - this will happen with strong correlation like mine.

I want to remove some units from the groups above to make units inside groups less heterogeneous. I could do this a lot, but I want to only show the principle - I can change yellow group the most (group 2), so I will do this there. I can also change the blue group, but not so much so I will show it with yellow group - there we have clear standout units.

I will remove units with ID 224, 498, 825, 945 and 508. I then have to standardize values again and repeat the process.

mydata <- mydata %>%
    filter(!ID %in% c(224, 498, 825, 945, 508))

I removed units, and I have to standardize again.

mydata$Price_z <- scale(mydata$Price)
mydata$Carat_z <- scale(mydata$Carat)
mydata$Length_z <- scale(mydata$Length)

I can now do clustering again.

WARD <- mydata[c("Price_z", "Carat_z", "Length_z")] %>%
           get_dist(method = "euclidian") %>%
           hclust(method = "ward.D2")

WARD
## 
## Call:
## hclust(d = ., method = "ward.D2")
## 
## Cluster method   : ward.D2 
## Distance         : euclidean 
## Number of objects: 989

I do dendrogram next.

fviz_dend(WARD)

And dendrogram with colors.

fviz_dend(WARD,
          k = 4,
          cex = 0.5,
          palette = "jama",
          color_labels_by_k = TRUE,
          rect = TRUE)

I let program know about 4 groups.

mydata$ClusterWard <- cutree(WARD,
                             k = 4)
head(mydata[c(1, 2, 3, 4, 10)])
## # A tibble: 6 × 5
##      ID Price Carat Length ClusterWard
##   <int> <int> <dbl>  <dbl>       <int>
## 1     1   638  0.41   4.72           1
## 2     2  1402  0.5    5.05           1
## 3     3  3530  1.03   6.42           2
## 4     4  5037  1.1    6.6            2
## 5     5 13757  1.51   7.24           3
## 6     6   457  0.3    4.3            1

I get my new initial leaders for groups.

Initial_leaders <- aggregate(mydata[ , c("Price_z", "Carat_z", "Length_z")],
                             by = list(mydata$ClusterWard),
                             FUN = mean)
Initial_leaders
##   Group.1    Price_z    Carat_z   Length_z
## 1       1 -0.8006873 -0.9760536 -1.1228786
## 2       2  0.3411736  0.5084507  0.6567852
## 3       3  2.1391134  2.0366985  1.7592797
## 4       4 -0.4340939 -0.3622323 -0.2156351

I can see that after dropping the 5 units above, my initial leaders are different for all groups.

I do K-means for reassigning to groups.

K_MEANS <- hkmeans(mydata[c("Price_z", "Carat_z", "Length_z")], 
                   k = 4,
                   hc.metric = "euclidean",
                   hc.method = "ward.D2")

K_MEANS
## Hierarchical K-means clustering with 4 clusters of sizes 324, 298, 106, 261
## 
## Cluster means:
##      Price_z    Carat_z   Length_z
## 1 -0.8006873 -0.9760536 -1.1228786
## 2  0.4154569  0.5790389  0.7189930
## 3  2.2938463  2.1100662  1.8117281
## 4 -0.4119969 -0.3064338 -0.1627986
## 
## Clustering vector:
##   [1] 1 1 2 2 3 1 4 2 2 3 3 3 1 2 4 1 3 4 1 4 1 4 1 2 1 3 2 3 2 4 2 3 4 2 2 2 2 4 4 3 1 3 2 1 1 4 1 2 2 1 1 2 1 2 1 1 1
##  [58] 1 1 1 1 2 1 4 1 1 2 4 2 4 3 2 2 3 4 2 1 2 4 1 3 1 1 2 2 1 2 4 2 2 3 2 1 1 1 2 4 4 1 1 1 2 2 2 1 2 1 2 4 2 4 2 2 2
## [115] 2 2 4 1 3 2 2 2 2 2 1 2 2 1 1 2 4 1 3 1 2 4 4 4 4 3 2 2 3 2 2 4 4 2 1 1 2 2 1 1 1 2 3 1 1 3 2 1 2 2 2 2 4 4 3 1 1
## [172] 2 1 1 2 1 4 1 2 1 3 2 1 2 4 4 1 1 2 4 1 2 1 4 2 1 4 2 2 1 1 4 4 4 1 1 4 2 1 4 4 2 4 4 2 4 3 1 2 2 4 4 2 4 1 4 4 4
## [229] 4 1 3 1 4 3 1 4 2 1 4 1 1 4 3 2 1 1 3 2 4 2 2 1 1 3 1 4 4 2 2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4 2 2 1 4 3 2 2 2 3 2 4 4 1 2 2 2 3 1 1 2 1 3 4 4 3 1 2 1 4 2 4 2 2 1 2 2 2 2 4 1 2 2 1 1 4 2 1 2 4
## [799] 2 1 1 1 2 1 1 1 3 4 2 4 4 4 3 4 4 1 2 2 2 2 2 4 2 1 1 2 1 4 1 4 4 1 2 1 2 1 1 1 4 2 1 1 4 2 4 4 2 1 4 1 4 1 4 4 3
## [856] 1 2 3 2 2 1 4 2 3 1 3 2 4 1 2 1 1 2 4 4 4 2 4 4 2 4 2 1 1 3 2 4 1 4 2 3 1 4 2 2 4 2 4 1 2 2 3 1 2 4 4 2 4 2 1 1 1
## [913] 4 4 2 1 2 1 2 1 1 1 1 4 1 4 3 2 3 1 4 1 1 4 4 4 2 1 3 2 4 2 2 4 1 4 4 1 1 2 1 3 1 4 1 3 1 3 1 3 1 2 4 1 4 4 4 2 4
## [970] 1 4 4 1 1 2 4 2 1 3 3 4 2 4 3 4 2 2 1 2
## 
## Within cluster sum of squares by cluster:
## [1]  21.85228 111.87526 100.06568  46.54764
##  (between_SS / total_SS =  90.5 %)
## 
## Available components:
## 
##  [1] "cluster"      "centers"      "totss"        "withinss"     "tot.withinss" "betweenss"    "size"        
##  [8] "iter"         "ifault"       "data"         "hclust"

My group sizes have now changed for all groups except group 1 - I have 324 units in group 1, 298 in group 2, 106 in group 3 and 261 in group 4

I can see my new reclassified leaders.

The current reclassified leaders are different from current initial leaders in every group except group 1. I will show this in more detail later.

I show clusters again graphically.

fviz_cluster(K_MEANS, 
             palette = "jama", 
             repel = FALSE,
             ggtheme = theme_classic())

Unit 223, that is now in group 2, was before in group 4 (before I removed those 5 units from group 2 - yellow group - above). I could again remove this unit, because units in group 4 are again more heterogeneous than they could be. I will not do this again. I could keep getting groups like this and would keep removing units, that would just extend this homework. The point was to show understanding of how to remove units to make them more homogeneous in groups. I did this already.

I will just look at how my units got reclassified now when I went from hierarchical approach to K-means. I start by doing a variable for K-means.

mydata$ClusterK_Means <- K_MEANS$cluster
head(mydata[c("Price_z", "Carat_z", "Length_z")])
## # A tibble: 6 × 3
##   Price_z[,1] Carat_z[,1] Length_z[,1]
##         <dbl>       <dbl>        <dbl>
## 1      -0.840      -0.848       -0.935
## 2      -0.654      -0.663       -0.644
## 3      -0.138       0.430        0.564
## 4       0.228       0.574        0.723
## 5       2.35        1.42         1.29 
## 6      -0.884      -1.08        -1.31

I now look at my initial leaders with hierarchical clustering (Ward’s).

table(mydata$ClusterWard)
## 
##   1   2   3   4 
## 324 312 119 234

Above, I can see initial numbers of units in each group with hierarchical clustering.

I will also show these numbers after reclassification with K-means next.

table(mydata$ClusterK_Means)
## 
##   1   2   3   4 
## 324 298 106 261

As I can see, numbers of units changed in groups 2, 3 and 4.

I can look at this with more detail in table below.

table(mydata$ClusterWard, mydata$ClusterK_Means)
##    
##       1   2   3   4
##   1 324   0   0   0
##   2   0 285   0  27
##   3   0  13 106   0
##   4   0   0   0 234

I will explain one row and one column

Row 3: With hierarchical clustering, I initially had a total of 119 units in group 3. Later, 13 of these units were reclassified to group 2 with K-means.

Column 2: In group 2 I have 298 units after using K-means clustering. Of these 298 units, 285 were there in the start and 13 came from group 3.

Our groups changed in total when 13 units from group 3 were given to group 2 and 27 units from group 2 were given to group 4. So after K-means group 2 had 14 less units (-27 + 13), group 3 had 13 less units and group 4 had 27 more units. This is how group 2 went from 312 to 298 units, group 3 went from 119 to 106 units, and group 4 went from 234 to 261 units.

Now I do centroids which I will use for a visual display of groups that gives me more information.

Centroids <- K_MEANS$centers
Centroids
##      Price_z    Carat_z   Length_z
## 1 -0.8006873 -0.9760536 -1.1228786
## 2  0.4154569  0.5790389  0.7189930
## 3  2.2938463  2.1100662  1.8117281
## 4 -0.4119969 -0.3064338 -0.1627986

Now the visual display.

Figure <- as.data.frame(Centroids)
Figure$id <- 1:nrow(Figure)
Figure <- pivot_longer(Figure, cols = c("Price_z", "Carat_z", "Length_z"))

Figure$Groups <- factor(Figure$id, 
                        levels = c(1, 2, 3, 4), 
                        labels = c("1", "2", "3", "4"))

Figure$nameFactor <- factor(Figure$name, 
                            levels = c("Price_z", "Carat_z", "Length_z"), 
                            labels = c("Price_z", "Carat_z", "Length_z"))

ggplot(Figure, aes(x = nameFactor, y = value)) +
  geom_hline(yintercept = 0) +
  theme_bw() +
  geom_point(aes(shape = Groups, col = Groups), size = 3) +
  geom_line(aes(group = id), linewidth = 1) +
  ylab("Averages") +
  xlab("Cluster variables") +
  ylim(-2.5, 2.5)

I can now explain all groups better.

Group 1

In group 1 are diamonds that are the most below average in Price, Length and Carat standardized values. These are the smallest, lightest, and least expensive diamonds.

Group 2

In group 2 are diamonds that are slightly above average in Price, Length and Carat standardized values. These are the second biggest, second heaviest, and second most expensive diamonds.

Group 3

In group 3 are diamonds that are the most above average in Price, Length and Carat standardized values. These are the biggest, heaviest, and most expensive diamonds.

Group 4

In group 4 are diamonds that are slightly below average in Price, Length and Carat standardized values. These are the second smallest, second lightest, and second least expensive diamonds.

Now I check if all variables are good at classifying units in groups with ANOVA checks for each.

fit <- aov(cbind(Price_z, Length_z, Carat_z) ~ as.factor(ClusterK_Means), 
                 data = mydata)

summary(fit)
##  Response 1 :
##                            Df Sum Sq Mean Sq F value    Pr(>F)    
## as.factor(ClusterK_Means)   3  861.2 287.066  2229.9 < 2.2e-16 ***
## Residuals                 985  126.8   0.129                      
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
##  Response 2 :
##                            Df Sum Sq Mean Sq F value    Pr(>F)    
## as.factor(ClusterK_Means)   3 917.42 305.805  4267.5 < 2.2e-16 ***
## Residuals                 985  70.58   0.072                      
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
##  Response 3 :
##                            Df Sum Sq Mean Sq F value    Pr(>F)    
## as.factor(ClusterK_Means)   3 905.04 301.681  3582.1 < 2.2e-16 ***
## Residuals                 985  82.96   0.084                      
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Each response is for respective variable. Response 1 is for Price, Response 2 is for Length, Response 3 is for Carat.

ANOVA test hypothesis for each variable (response) is:

  • H0: the means of variable (Price, Length or Carat) are equal across all groups. Example of H0 with Response 1 is: mean price (group 1) = mean price (group 2) = mean price (group 3).

  • H1: At least one mean is different in the groups. In my example with Response 1, at least one group has a different price mean.

All three ANOVA tests are significant. All three variables: Price, Length and Carat are different in all groups (p<0,001).

Validation of results with categorical variables

I will now validate results with my categorical variable “Cut”. I will use chi-square test. Assumptions for this test are that units are independent (this is met), and that at least 80% of expected frequencies (16 out of 20 expected frequencies) are above 5. 20% of them can be below 1 and 5, but never below 1. As soon as one of expected frequencies is between 1 and 5, the statistical power of the test is lower.

The assumptions are met (I will show later) and I can use this test, but at less statistical power (one expected frequency will be below 5).

chisq_results <- chisq.test(mydata$Cut, as.factor(mydata$ClusterK_Means))
## Warning in chisq.test(mydata$Cut, as.factor(mydata$ClusterK_Means)): Chi-squared approximation may be incorrect
chisq_results
## 
##  Pearson's Chi-squared test
## 
## data:  mydata$Cut and as.factor(mydata$ClusterK_Means)
## X-squared = 53.726, df = 12, p-value = 3.058e-07

The hypotheses for chi-square are:

  • H0: There is no association between Cut and K-means clusters.

  • H1: There is association between Cut and K-means clusters.

I reject null hypothesis and conclude that there is association between Cut and reclassified K-means cluster groups (p<0,001).

I will now show tables of observed frequencies, expected frequencies, and residuals.

addmargins(chisq_results$observed)
##            
## mydata$Cut    1   2   3   4 Sum
##   Fair        3  16   1  12  32
##   Good       21  42  10  27 100
##   Very Good  75  83  21  66 245
##   Premium    72  80  37  49 238
##   Ideal     153  77  37 107 374
##   Sum       324 298 106 261 989

I can for example say that in cluster group 1, 3 diamonds were cut fair, 21 were cut good, 75 were cut very good, 72 were cut premium and 153 were cut ideal.

round(chisq_results$expected, 2)
##            
## mydata$Cut       1      2     3     4
##   Fair       10.48   9.64  3.43  8.44
##   Good       32.76  30.13 10.72 26.39
##   Very Good  80.26  73.82 26.26 64.66
##   Premium    77.97  71.71 25.51 62.81
##   Ideal     122.52 112.69 40.08 98.70

All expected frequencies except 1 are above 5, that one is between 1 and 5. Test assumptions are met.

For example, I can expect that of diamonds in cluster group 1, 32,76 would be cut “good”.

I will finally show the most important table of residuals.

round(chisq_results$res, 2)
##            
## mydata$Cut      1     2     3     4
##   Fair      -2.31  2.05 -1.31  1.22
##   Good      -2.05  2.16 -0.22  0.12
##   Very Good -0.59  1.07 -1.03  0.17
##   Premium   -0.68  0.98  2.28 -1.74
##   Ideal      2.75 -3.36 -0.49  0.84

I will comment significant values by group.

Group 1

There is less than expected diamonds that were cut “fair” and “good” in group 1 (a = 0,05). There is more than expected diamonds that were cut “ideal” in group 1 (a = 0,01). Diamonds in group 1 were cut better than expected. Group 1 diamonds were the smallest, lightest, and least expensive.

Group 2

There is more than expected diamonds that were cut “fair” and “good” in group 2 (a = 0,05). There were less than expected diamonds that were cut “ideal” in group 2 (a = 0,001). Diamonds in group 2 were cut worse than expected. Group 2 diamonds were the second biggest, second heaviest, and second most expensive.

Group 3

There is more than expected diamonds that were cut “premium” in group 3 (a = 0,05). Diamonds in group 3 were cut better than expected (not as conclusive as with groups 1 and 2). Group 3 diamonds were the biggest, heaviest, and most expensive.

Group 4

There is less than expected diamonds that were cut “premium” in group 4 (a = 0,05). Diamonds in group 4 were cut worse than expected (not as conclusive as with groups 1 and 2). Group 4 diamonds were the second smallest, second lightest, and second least expensive.

Results

My research question said: Can I group diamonds based on their price, carat, length, width, and depth? I grouped diamonds based on their price, carat, and length. I could also group them by all 5 variables as cluster variables, but I did not because of the high correlation values.

I used Ward’s algorithm for hierarchical clustering. Based on my dendrogram I classified diamonds into four cluster groups. I optimized clusters with K-Means clustering that reassigned units between clusters. Later I removed some units as outliers and repeated clustering with same methods again.

I will now draw conclusions for my groups.

Group 1

Group 1 contains the most diamonds (32,76% or 324/989 diamonds). It is characterized by the lowest values of length, carat and price - all three values are the most below average among all groups. This cluster contains less than expected diamonds that were cut “fair” and “good” (a = 0,05) and more than expected diamonds that were cut “ideal”(a = 0,01). In this worst-performing group, diamonds were cut better.

Group 2

Group 2 comes second in number of diamonds in it (30,13% or 298/989 diamonds). It is characterized by second highest values of length, carat and price - all three values are slightly above average. This cluster contains more than expected diamonds that were cut “fair” and “good” (a = 0,05) and less than expected diamonds that were cut “ideal” (a = 0,001). In this second-best performing group, diamonds were cut worse.

Group 3

Group 3 contains the least diamonds (10,72% or 106/989 diamonds). It is characterized by the highest values of length, carat and price - all three values are the most above average among all groups. This cluster contains more than expected diamonds that were cut “premium” (a = 0,05). In this best-performing group, diamonds were cut better.

Group 4

Group 4 comes third in number of diamonds in it (26,39% or 261/989 diamonds). It is characterized by the second lowest values of length, carat and price - all three values are slightly below average. This cluster contains less than expected diamonds that were cut “premium” (a = 0,05). In this second-worst performing group, diamonds were cut worse than expected.

My results suggest that length, weight (carat), and prices of diamonds are not always consistent with the quality of their cut. Like I discovered, those diamonds that had the lowest values of length, carat and price (group 1), were cut better. But also those diamonds that had the highest values of length, carat and price (group 3) were cut better (not as decidedly better as with group 1, but still better). While price of diamonds appears to increase along their values of length and carat, having those values high does not consistently correspond with the cut of a diamond.