From 3a1eeec915c184ce7793248024fa17538d5fc4bc Mon Sep 17 00:00:00 2001 From: Paolo Rivas Date: Wed, 11 Nov 2020 23:44:52 -0500 Subject: [PATCH 1/2] committing assigment 4 --- Assignment 4.Rmd | 105 +++++++-- Assignment_4.html | 579 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 671 insertions(+), 13 deletions(-) create mode 100644 Assignment_4.html diff --git a/Assignment 4.Rmd b/Assignment 4.Rmd index 54b0e66..aa1a5e0 100644 --- a/Assignment 4.Rmd +++ b/Assignment 4.Rmd @@ -1,5 +1,7 @@ --- -title: "Assignment 4: K Means Clustering" +title: 'Assignment 4: K Means Clustering' +name: Paolo Rivas + --- In this assignment we will be applying the K-means clustering algorithm we looked at in class. At the following link you can find a description of K-means: @@ -8,13 +10,19 @@ https://www.cs.uic.edu/~wilkinson/Applets/cluster.html ```{r} -library() +library(dplyr) +library(tidyr) +library(ggplot2) + ``` Now, upload the file "Class_Motivation.csv" from the Assignment 4 Repository as a data frame called "K1"" ```{r} -K1 <- read.csv(...) +K1 <- read.csv("Class_Motivation.csv", header = TRUE) +K1b <- gather(K1, week , measure, 2:6) + +plot(as.factor(K1b$week), K1b$measure) ``` @@ -26,7 +34,7 @@ The algorithm will treat each row as a value belonging to a person, so we need t ```{r} -K2 <- +K2 <- select(K1, 2:6) ``` @@ -41,13 +49,18 @@ We will remove people with missing values for this assignment, but keep in mind K3 <- na.omit(K2) #This command create a data frame with only those people with no missing values. It "omits" all rows with missing values, also known as a "listwise deletion". EG - It runs down the list deleting rows as it goes. +K3 <- K2 + +K3[is.na(K3)] <- 0 + + ``` Another pre-processing step used in K-means is to standardize the values so that they have the same range. We do this because we want to treat each week as equally important - if we do not standardise then the week with the largest range will have the greatest impact on which clusters are formed. We standardise the values by using the "scale()" command. ```{r} -K3 <- +K3 <- scale(K3) ``` @@ -65,22 +78,38 @@ Notice that in this case we have 5 variables and in class we only had 2. It is i Also, we need to choose the number of clusters we think are in the data. We will start with 2. ```{r} - -fit <- +fit1a <- kmeans(K3, 2) +fit1b <- kmeans(K3, 2) +fit1c <- kmeans(K3, 2) #We have created an object called "fit" that contains all the details of our clustering including which observations belong to each cluster. #We can access the list of clusters by typing "fit$cluster", the top row corresponds to the original order the rows were in. Notice we have deleted some rows. - +fit1a$cluester #We can also attach these clusters to the original dataframe by using the "data.frame" command to create a new data frame called K4. -K4 +K4 <- data.frame(K3, fit1a$cluster, fit1b$cluster, fit1c$cluster) -#Have a look at the K4 dataframe. Lets change the names of the variables to make it more convenient with the names() command. +fit1a$withinss +fit1b$withinss +fit1c$withinss +fit1a$tot.withinss +fit1b$tot.withinss +fit1c$tot.withinss + +fit1a$betweenss +fit1b$betweenss +fit1c$betweenss + +K4 <- data.frame(K3, fit1a$cluster) + +#Have a look at the K4 dataframe. Lets change the names of the variables to make it more convenient with the names() command. + +names(K4) <- c("1", "2", "3", "4", "5", "cluster") ``` Now we need to visualize the clusters we have created. To do so we want to play with the structure of our data. What would be most useful would be if we could visualize average motivation by cluster, by week. To do this we will need to convert our data from wide to long format. Remember your old friends tidyr and dplyr! @@ -95,7 +124,7 @@ Now lets use dplyr to average our motivation values by week and by cluster. ```{r} -K6 <- K5 %>% group_by(week, cluster) %>% summarise(K6, avg = mean(motivation)) +K6 <- K5 %>% group_by(week, cluster) %>% summarise(avg = mean(motivation)) ``` @@ -113,9 +142,9 @@ Likewise, since "cluster" is not numeric but rather a categorical label we want ```{r} -K6$week <- +K6$week <- as.numeric(K6$week) -K6$cluster <- +K6$cluster <- as.factor((K6$cluster)) ``` @@ -153,9 +182,59 @@ Using the data collected in the HUDK4050 entrance survey (HUDK4050-cluster.csv) Create a visualization that shows the overlap between the two clusters each student belongs to in Part II. IE - Are there geographical patterns that correspond to the answers? ```{r} +library(tidyverse) + +M1 <- read.csv("HUDK405020-cluster.csv", header = TRUE) +M2 <- select(M1, 4:9) + +fit2a <- kmeans(M2, 1) +fit2b <- kmeans(M2, 2) +fit2c <- kmeans(M2, 3) +fit2d <- kmeans(M2, 4) +fit2e <- kmeans(M2, 5) +fit2f <- kmeans(M2, 6) +fit2g <- kmeans(M2, 7) + +mss <-c(fit2a$tot.withinss, fit2b$tot.withinss, fit2c$tot.withinss, fit2d$tot.withinss, fit2e$tot.withinss, fit2f$tot.withinss, fit2g$tot.withinss,fit2a$betweenss, fit2b$betweenss, fit2c$betweenss, fit2d$betweenss, fit2e$betweenss, fit2f$betweenss, fit2g$betweenss) +clusters <- c(seq(1,7,1), seq(1,7,1)) +col <- c(rep("blue", 7), rep("red", 7)) + +plot(clusters, mss, col = col) + + +``` +```{r} +L1 <- select(M1, 2:3) + +plot(L1$long, L1$lat) + +fit3a <- kmeans(L1, 2) +fit3b <- kmeans(L1, 2) +fit3c <- kmeans(L1, 2) + +fit3a$tot.withinss +fit3b$tot.withinss +fit3c$tot.withinss + +ML <- data.frame(M1$compare.features, M1$math.accuracy, M1$planner.use, M1$enjoy.discuss, M1$enjoy.group, M1$meet.deadline, fit2c$cluster, M1$lat, M1$long, fit3a$cluster) + +pairs(ML) +``` +```{r} +table(ML$fit2c.cluster, ML$fit3a.cluster) + +ML2 <- ML %>% group_by(fit2c.cluster, fit3a.cluster) %>% summarise(count = n()) + +ggplot(ML2, aes(x = fit2c.cluster, y = fit3a.cluster, size = count)) + geom_point() ``` ## Please render your code as an .html file using knitr and Pull Resquest both your .Rmd file and .html files to the Assignment 3 repository. +```{r} +#install.packages("vcd") +library(vcd) +P1 <- structable(fit2c$cluster ~ fit3a$cluster) +mosaic(P1, shade=TRUE, legend = TRUE) +``` diff --git a/Assignment_4.html b/Assignment_4.html new file mode 100644 index 0000000..cff3fa6 --- /dev/null +++ b/Assignment_4.html @@ -0,0 +1,579 @@ + + + + + + + + + + + + + +Assignment 4: K Means Clustering + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + +

In this assignment we will be applying the K-means clustering algorithm we looked at in class. At the following link you can find a description of K-means:

+

https://www.cs.uic.edu/~wilkinson/Applets/cluster.html

+
library(dplyr)
+
## 
+## Attaching package: 'dplyr'
+
## The following objects are masked from 'package:stats':
+## 
+##     filter, lag
+
## The following objects are masked from 'package:base':
+## 
+##     intersect, setdiff, setequal, union
+
library(tidyr)
+library(ggplot2)
+

Now, upload the file “Class_Motivation.csv” from the Assignment 4 Repository as a data frame called “K1”"

+
K1 <- read.csv("Class_Motivation.csv", header = TRUE)
+K1b <- gather(K1, week , measure, 2:6)
+
+plot(as.factor(K1b$week), K1b$measure)
+

+

This file contains the self-reported motivation scores for a class over five weeks. We are going to look for patterns in motivation over this time and sort people into clusters based on those patterns.

+

But before we do that, we will need to manipulate the data frame into a structure that can be analyzed by our clustering algorithm.

+

The algorithm will treat each row as a value belonging to a person, so we need to remove the id variable.

+
K2 <- select(K1, 2:6)
+

It is important to think about the meaning of missing values when clustering. We could treat them as having meaning or we could remove those people who have them. Neither option is ideal. What problems do you foresee if we recode or remove these values? Write your answers below:

+

We will remove people with missing values for this assignment, but keep in mind the issues that you have identified.

+
K3 <- na.omit(K2) #This command create a data frame with only those people with no missing values. It "omits" all rows with missing values, also known as a "listwise deletion". EG - It runs down the list deleting rows as it goes.
+
+K3 <- K2
+
+K3[is.na(K3)] <- 0
+

Another pre-processing step used in K-means is to standardize the values so that they have the same range. We do this because we want to treat each week as equally important - if we do not standardise then the week with the largest range will have the greatest impact on which clusters are formed. We standardise the values by using the “scale()” command.

+
K3 <- scale(K3)
+

Now we will run the K-means clustering algorithm we talked about in class. 1) The algorithm starts by randomly choosing some starting values 2) Associates all observations near to those values with them 3) Calculates the mean of those clusters of values 4) Selects the observation closest to the mean of the cluster 5) Re-associates all observations closest to this observation 6) Continues this process until the clusters are no longer changing

+

Notice that in this case we have 5 variables and in class we only had 2. It is impossible to vizualise this process with 5 variables.

+

Also, we need to choose the number of clusters we think are in the data. We will start with 2.

+
fit1a <- kmeans(K3, 2)
+fit1b <- kmeans(K3, 2)
+fit1c <- kmeans(K3, 2)
+
+#We have created an object called "fit" that contains all the details of our clustering including which observations belong to each cluster.
+
+#We can access the list of clusters by typing "fit$cluster", the top row corresponds to the original order the rows were in. Notice we have deleted some rows.
+
+fit1a$cluester
+
## NULL
+
#We can also attach these clusters to the original dataframe by using the "data.frame" command to create a new data frame called K4.
+
+K4 <- data.frame(K3, fit1a$cluster, fit1b$cluster, fit1c$cluster)
+
+
+fit1a$withinss
+
## [1] 71.23506 49.52381
+
fit1b$withinss
+
## [1] 31.97163 76.21636
+
fit1c$withinss
+
## [1] 76.21636 31.97163
+
fit1a$tot.withinss
+
## [1] 120.7589
+
fit1b$tot.withinss
+
## [1] 108.188
+
fit1c$tot.withinss
+
## [1] 108.188
+
fit1a$betweenss
+
## [1] 64.24113
+
fit1b$betweenss
+
## [1] 76.81201
+
fit1c$betweenss
+
## [1] 76.81201
+
K4 <- data.frame(K3, fit1a$cluster)
+
+#Have a look at the K4 dataframe. Lets change the names of the variables to make it more convenient with the names() command.
+
+names(K4) <- c("1", "2", "3", "4", "5", "cluster")
+

Now we need to visualize the clusters we have created. To do so we want to play with the structure of our data. What would be most useful would be if we could visualize average motivation by cluster, by week. To do this we will need to convert our data from wide to long format. Remember your old friends tidyr and dplyr!

+

First lets use tidyr to convert from wide to long format.

+
K5 <- gather(K4, "week", "motivation", 1:5)
+

Now lets use dplyr to average our motivation values by week and by cluster.

+
K6 <- K5 %>% group_by(week, cluster) %>% summarise(avg = mean(motivation))
+
## `summarise()` regrouping output by 'week' (override with `.groups` argument)
+

Now it’s time to do some visualization:

+

https://www.cs.uic.edu/~wilkinson/TheGrammarOfGraphics/GOG.html

+

And you can see the range of available graphics in ggplot here:

+

http://ggplot2.tidyverse.org/reference/index.html

+

We are going to create a line plot similar to the one created in this paper about school dropout Bowers, 2010. It will have motivation on the Y-axis and weeks on the X-axis. To do this we will want our weeks variables to be treated as a number, but because it was created from a variable name it is currently being treated as a character variable. You can see this if you click on the arrow on the left of K6 in the Data pane. Week is designated by “chr”. To convert it to numeric, we use the as.numeric command.

+

Likewise, since “cluster” is not numeric but rather a categorical label we want to convert it from an “integer” format to a “factor” format so that ggplot does not treat it as a number. We can do this with the as.factor() command.

+
K6$week <- as.numeric(K6$week)
+
+K6$cluster <- as.factor((K6$cluster))
+

Now we can plot our line plot using the ggplot command, “ggplot()”.

+ +
ggplot(K6, aes(week, avg, colour = cluster)) + geom_line() + xlab("Week") + ylab("Average Motivation")
+

+

What patterns do you see in the plot?

+

It would be useful to determine how many people are in each cluster. We can do this easily with dplyr.

+
K7 <- count(K4, cluster)
+

Look at the number of people in each cluster, now repeat this process for 3 rather than 2 clusters. Which cluster grouping do you think is more informative? Write your answer below:

+

##Part II

+

Using the data collected in the HUDK4050 entrance survey (HUDK4050-cluster.csv) use K-means to cluster the students first according location (lat/long) and then according to their answers to the questions, each student should belong to two clusters.

+

##Part III

+

Create a visualization that shows the overlap between the two clusters each student belongs to in Part II. IE - Are there geographical patterns that correspond to the answers?

+
library(tidyverse)
+
## ── Attaching packages ───────────────────────────────────────────────────── tidyverse 1.3.0 ──
+
## ✔ tibble  2.1.3     ✔ stringr 1.4.0
+## ✔ readr   1.3.1     ✔ forcats 0.5.0
+## ✔ purrr   0.3.4
+
## ── Conflicts ──────────────────────────────────────────────────────── tidyverse_conflicts() ──
+## ✖ dplyr::filter() masks stats::filter()
+## ✖ dplyr::lag()    masks stats::lag()
+
M1 <- read.csv("HUDK405020-cluster.csv", header = TRUE)
+M2 <- select(M1, 4:9)
+
+fit2a <- kmeans(M2, 1)
+fit2b <- kmeans(M2, 2)
+fit2c <- kmeans(M2, 3)
+fit2d <- kmeans(M2, 4)
+fit2e <- kmeans(M2, 5)
+fit2f <- kmeans(M2, 6)
+fit2g <- kmeans(M2, 7)
+
+mss <-c(fit2a$tot.withinss, fit2b$tot.withinss, fit2c$tot.withinss, fit2d$tot.withinss, fit2e$tot.withinss, fit2f$tot.withinss, fit2g$tot.withinss,fit2a$betweenss, fit2b$betweenss, fit2c$betweenss, fit2d$betweenss, fit2e$betweenss, fit2f$betweenss, fit2g$betweenss)
+
+clusters <- c(seq(1,7,1), seq(1,7,1))
+col <- c(rep("blue", 7), rep("red", 7))
+
+plot(clusters, mss, col = col)
+

+
L1 <- select(M1, 2:3)
+
+plot(L1$long, L1$lat)
+

+
fit3a <- kmeans(L1, 2)
+fit3b <- kmeans(L1, 2)
+fit3c <- kmeans(L1, 2)
+
+fit3a$tot.withinss
+
## [1] 23589.49
+
fit3b$tot.withinss
+
## [1] 23589.49
+
fit3c$tot.withinss
+
## [1] 23589.49
+
ML <- data.frame(M1$compare.features, M1$math.accuracy, M1$planner.use, M1$enjoy.discuss, M1$enjoy.group, M1$meet.deadline, fit2c$cluster, M1$lat, M1$long, fit3a$cluster)
+
+pairs(ML)
+

+
table(ML$fit2c.cluster, ML$fit3a.cluster)
+
##    
+##      1  2
+##   1  8 16
+##   2 11 14
+##   3 17 18
+
ML2 <- ML %>% group_by(fit2c.cluster, fit3a.cluster) %>% summarise(count = n())
+
## `summarise()` regrouping output by 'fit2c.cluster' (override with `.groups` argument)
+
ggplot(ML2, aes(x = fit2c.cluster, y = fit3a.cluster, size = count)) + geom_point()
+

+
+

Please render your code as an .html file using knitr and Pull Resquest both your .Rmd file and .html files to the Assignment 3 repository.

+
#install.packages("vcd")
+library(vcd)
+
## Loading required package: grid
+
P1 <- structable(fit2c$cluster ~ fit3a$cluster)
+mosaic(P1, shade=TRUE, legend = TRUE)
+

+
+ + + + +
+ + + + + + + + From f312da16ff18f25fe2d4873c4205bca33d7aaddf Mon Sep 17 00:00:00 2001 From: Paolo Rivas Date: Tue, 15 Jun 2021 22:39:12 -0500 Subject: [PATCH 2/2] Update README.md --- README.md | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index b6a298d..976e38a 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,5 @@ -# Assignment 4 +# Cluster Analysis ### Cluster Analysis -In the attached files you will find instructions for assignment 3. Please **fork** this repository to your own Github account and then clone it in RStudio. -In Assignment 4 we will be looking at some class motivation data collected from this class two years ago. You will be expected to cluster and visualize the clusters. - -The instructions to Assignment 4 are in the Assignment 4.rmd file. Assignments are structured in three parts, in the first part you can just follow along with the code, in the second part you will need to apply the code and in the third part is completely freestyle, apply your new knowledge in a new way. - -**Please complete as much as you can by 5:00pm, 11/05/20** - -Once you have finished, commit, push and pull your assignment back to the main branch. - -Good luck! \ No newline at end of file +We will be looking at some class motivation data collected from this class two years ago. You will be expected to cluster and visualize the clusters. This project is structured in three parts, in the first part you can just follow along with the code, in the second part you will need to apply the code and in the third part is completely freestyle, apply your new knowledge in a new way.