diff --git a/Assignment 4 - solution.Rmd b/Assignment 4 - solution.Rmd new file mode 100644 index 0000000..92074f6 --- /dev/null +++ b/Assignment 4 - solution.Rmd @@ -0,0 +1,303 @@ +--- +title: "Assignment 3: 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 + + +```{r} +library(dplyr) +library(tidyr) +library(ggplot2) + +``` + +Now, upload the file "Class_Motivation.csv" from the Assignment 3 Repository as a data frame called "K1"" +```{r} + +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. + +```{r} + +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. + + +```{r} + +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 "scales()" command. + +```{r} + +K3 <- scale(K3) #Go to whiteboard + +``` + + +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. + +```{r} + +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. + +fit1b$cluster + +#We can also attach these clusters to te 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 +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") #c() stands for concatonate and it creates a vector of anything, in this case a vector of names. + + +``` + +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. +```{r} + +K5 <- tidyr::gather(K4, "week", "motivation", 1:5) + +``` + +Now lets use dplyr to average our motivation values by week and by cluster. + +```{r} + +K6 <- K5 %>% group_by(week, cluster) %>% summarise(avg = mean(motivation)) + +``` + +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](http://pareonline.net/pdf/v15n7.pdf). 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. + +```{r} + +K6$week <- as.numeric(K6$week) + +K6$cluster <- as.factor(K6$cluster) + +``` + +Now we can plot our line plot using the ggplot command, "ggplot()". + +- The first argument in a ggplot is the dataframe we are using: K6 +- Next is what is called an aesthetic (aes), the aesthetic tells ggplot which variables to use and how to use them. Here we are using the variables "week" and "avg" on the x and y axes and we are going color these variables using the "cluster" variable +- Then we are going to tell ggplot which type of plot we want to use by specifiying a "geom()", in this case a line plot: geom_line() +- Finally we are going to clean up our axes labels: xlab("Week") & ylab("Average Motivation") + +```{r} + +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. + +```{r} +K7 <- dplyr::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: + +Once you have done this, save both of your plots to the Assignment 5 file. Create a Zotero item to index your new computer program (Assignment 5.rmd) in Zotero. Then commit your assignment, push it to your Github account and then Pull request your version to the original assignment version so I can see it. + +##Part II + +Now, try to do the same for the data collected in class. Create two sets of clusters, the answers to the questions and regions where people grew up. + +```{r} +library(tidyverse) + +M1 <- read.csv("HUDK405020-cluster.csv", header = TRUE) +#Create a dataframe that only includes the surevy questions about hours +M2 <- select(M1,4:9) +#Dealing with missing values - there are two problems created by students skipping questions in the survey. 1. There are missing values and 2. read.csv() is treating those missing values as characters when it imports the data. That means the variables are being stored as factor type and not numeric type and if you try to recode the missing variables it will give an error that you cannot add levels to the factor + +#First convert the blank cells to NAs and convert all columns to numeric +#M2[M2==""] <- NA +#M2 <- M2 %>% mutate_all(funs(as.numeric(levels(.))[.])) + +#Solution 1: Remove students with missing values - but we will lose those students and be unable to allocate them to a group +#M2 <- na.omit(M2) + +#Solution 2: Recode as zero - but missing is not the same as recording zero hours +#M2[is.na(M2)] <- 0 + +#Solution 3: Recode as some other number that doesn't appear in your data (EG - 99) and rescale +#M2[is.na(M2)] <- 99 +#M2 <- as.data.frame(scale(M2)) + +#Generate clusters for survey questions +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) + +#Create a dataframe that only includes location data +L1 <- select(M1, 2:3) +#L1 <- unite(L1, place, Q1_1, Q1_2, sep = ",") + +#Request lattitude and longitude from Google Maps API +#library(ggmap) +#L2 <- geocode(as.character(L1$place), output = "latlon", source = "dsk") + +#Generate clusters for lat/lon + +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 + +#Combine everything together + +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) + +``` + + +##Part III + +Create a visualization that shows the overlap between the two groups of clusters you created in part III. + +```{r} +#There are lots of ways to answer this question. A common way was to do a scatterplot of students coloring the points with one set of clusters and using shapes for the other set of clusters. I think better way is to use a mosaic plot that can be generated eithe through ggplot or with a specific package called vcd. + +table(ML$fit2c.cluster,ML$fit3a.cluster) + +ML2 <- ML %>% group_by(fit2c.cluster,fit3a.cluster) %>% summarize(count = n()) +#ML2$fit3a.cluster <- ifelse(ML2$fit3a.cluster == 1, "A","B") +ggplot(ML2, aes(x = fit2c.cluster, y = fit3a.cluster, size = count)) + geom_point() + #geom_bar(stat = "identity", position = "fill", colour = "black") + +#install.packages("vcd") +library(vcd) +P1 <- structable(fit2c$cluster ~ fit3a$cluster) +mosaic(P1, shade=TRUE, legend=TRUE) + +#This shows how much overlap there are between the groups of clusters +``` + +```{r} +D1$compare.features <- ifelse(D1$compare.features == "100% of the time", 100, + ifelse(D1$compare.features == "75% of the time", 75, + ifelse(D1$compare.features == "50% of the time", 50, + ifelse(D1$compare.features == "25% of the time", 25,0)))) + +D1$math.accuracy <- ifelse(D1$math.accuracy == "100% of the time", 100, + ifelse(D1$math.accuracy == "75% of the time", 75, + ifelse(D1$math.accuracy == "50% of the time", 50, + ifelse(D1$math.accuracy == "25% of the time", 25,0)))) + +D1$planner.use <- ifelse(D1$planner.use == "100% of the time", 100, + ifelse(D1$planner.use == "75% of the time", 75, + ifelse(D1$planner.use == "50% of the time", 50, + ifelse(D1$planner.use == "25% of the time", 25,0)))) + +D1$enjoy.discuss <- ifelse(D1$enjoy.discuss == "Yes, all the time", 100, + ifelse(D1$enjoy.discuss == "Most of the time", 75, + ifelse(D1$enjoy.discuss == "About half the time", 50, + ifelse(D1$enjoy.discuss == "Rarely", 25,0)))) + +D1$enjoy.group <- ifelse(D1$enjoy.group == "Yes, all the time", 100, + ifelse(D1$enjoy.group == "Most of the time", 75, + ifelse(D1$enjoy.group == "About half the time", 50, + ifelse(D1$enjoy.group == "Rarely", 25,0)))) + +D1$meet.deadline <- ifelse(D1$meet.deadline == "Yes, all the time", 100, + ifelse(D1$meet.deadline == "Most of the time", 75, + ifelse(D1$meet.deadline == "About half the time", 50, + ifelse(D1$meet.deadline == "Rarely", 25,0)))) +``` +