Introduction

Understanding and predicting students’ progress is essential for creating educational strategies, as it identifies key factors affecting academic success. It enhances the learning environment, supporting individual needs and driving educational advancements, fostering a more educated society.

Objectives

1.Identify the key variables affecting student academic performance.

2.Develop models for predicting student academic progress.

Let’s take a look into the data set

This data set is shared by a 2014 published research paper - Using data mining to predict secondary school student performance.

The data set includes diverse metrics such as age, school type, parental background, etc。

str(df)
## 'data.frame':    382 obs. of  54 variables:
##  $ X           : int  1 2 3 4 5 6 7 8 9 10 ...
##  $ school      : chr  "GP" "GP" "GP" "GP" ...
##  $ sex         : chr  "F" "F" "F" "F" ...
##  $ age         : int  15 15 15 15 15 15 15 15 15 15 ...
##  $ address     : chr  "R" "R" "R" "R" ...
##  $ famsize     : chr  "GT3" "GT3" "GT3" "GT3" ...
##  $ Pstatus     : chr  "T" "T" "T" "T" ...
##  $ Medu        : int  1 1 2 2 3 3 3 2 3 3 ...
##  $ Fedu        : int  1 1 2 4 3 4 4 2 1 3 ...
##  $ Mjob        : chr  "at_home" "other" "at_home" "services" ...
##  $ Fjob        : chr  "other" "other" "other" "health" ...
##  $ reason      : chr  "home" "reputation" "reputation" "course" ...
##  $ nursery     : chr  "yes" "no" "yes" "yes" ...
##  $ internet    : chr  "yes" "yes" "no" "yes" ...
##  $ guardian.x  : chr  "mother" "mother" "mother" "mother" ...
##  $ traveltime.x: int  2 1 1 1 2 1 2 2 2 1 ...
##  $ studytime.x : int  4 2 1 3 3 3 3 2 4 4 ...
##  $ failures.x  : int  1 2 0 0 2 0 2 0 0 0 ...
##  $ schoolsup.x : chr  "yes" "yes" "yes" "yes" ...
##  $ famsup.x    : chr  "yes" "yes" "yes" "yes" ...
##  $ paid.x      : chr  "yes" "no" "yes" "yes" ...
##  $ activities.x: chr  "yes" "no" "yes" "yes" ...
##  $ higher.x    : chr  "yes" "yes" "yes" "yes" ...
##  $ romantic.x  : chr  "no" "yes" "no" "no" ...
##  $ famrel.x    : int  3 3 4 4 4 4 4 4 4 4 ...
##  $ freetime.x  : int  1 3 3 3 2 3 2 1 4 3 ...
##  $ goout.x     : int  2 4 1 2 1 2 2 3 2 3 ...
##  $ Dalc.x      : int  1 2 1 1 2 1 2 1 2 1 ...
##  $ Walc.x      : int  1 4 1 1 3 1 2 3 3 1 ...
##  $ health.x    : int  1 5 2 5 3 5 5 4 3 4 ...
##  $ absences.x  : int  2 2 8 2 8 2 0 2 12 10 ...
##  $ G1.x        : int  7 8 14 10 10 12 12 8 16 10 ...
##  $ G2.x        : int  10 6 13 9 10 12 0 9 16 11 ...
##  $ G3.x        : int  10 5 13 8 10 11 0 8 16 11 ...
##  $ guardian.y  : chr  "mother" "mother" "mother" "mother" ...
##  $ traveltime.y: int  2 1 1 1 2 1 2 2 2 1 ...
##  $ studytime.y : int  4 2 1 3 3 3 3 2 4 4 ...
##  $ failures.y  : int  0 0 0 0 0 0 0 0 0 0 ...
##  $ schoolsup.y : chr  "yes" "yes" "yes" "yes" ...
##  $ famsup.y    : chr  "yes" "yes" "yes" "yes" ...
##  $ paid.y      : chr  "yes" "no" "no" "no" ...
##  $ activities.y: chr  "yes" "no" "yes" "yes" ...
##  $ higher.y    : chr  "yes" "yes" "yes" "yes" ...
##  $ romantic.y  : chr  "no" "yes" "no" "no" ...
##  $ famrel.y    : int  3 3 4 4 4 4 4 4 4 4 ...
##  $ freetime.y  : int  1 3 3 3 2 3 2 1 4 3 ...
##  $ goout.y     : int  2 4 1 2 1 2 2 3 2 3 ...
##  $ Dalc.y      : int  1 2 1 1 2 1 2 1 2 1 ...
##  $ Walc.y      : int  1 4 1 1 3 1 2 3 3 1 ...
##  $ health.y    : int  1 5 2 5 3 5 5 4 3 4 ...
##  $ absences.y  : int  4 2 8 2 2 2 0 0 6 10 ...
##  $ G1.y        : int  13 13 14 10 13 11 10 11 15 10 ...
##  $ G2.y        : int  13 11 13 11 13 12 11 10 15 10 ...
##  $ G3.y        : int  13 11 12 10 13 12 12 11 15 10 ...

Data Cleaning

The data set is clean and ready for further analysis. Before that, we went through some examinations to confirm the absence of missing or duplicate entries.

Checking for Missing Values and Duplicate data

We used the following R code to check for any missing values and duplicate data in the dataset:

paste('Missing value is:',sum(is.na(df)))
## [1] "Missing value is: 0"
num_duplicates <- sum(duplicated(df))
paste("Number of duplicate rows:", num_duplicates)
## [1] "Number of duplicate rows: 0"

Remove unnecessary variable X

The X variable only counts the observations, which is irrelevant to our EDA. Therefore, we’ll remove this variable before further analysis and visualisation.

df <- df %>% select(-X)
str(df)
## 'data.frame':    382 obs. of  53 variables:
##  $ school      : chr  "GP" "GP" "GP" "GP" ...
##  $ sex         : chr  "F" "F" "F" "F" ...
##  $ age         : int  15 15 15 15 15 15 15 15 15 15 ...
##  $ address     : chr  "R" "R" "R" "R" ...
##  $ famsize     : chr  "GT3" "GT3" "GT3" "GT3" ...
##  $ Pstatus     : chr  "T" "T" "T" "T" ...
##  $ Medu        : int  1 1 2 2 3 3 3 2 3 3 ...
##  $ Fedu        : int  1 1 2 4 3 4 4 2 1 3 ...
##  $ Mjob        : chr  "at_home" "other" "at_home" "services" ...
##  $ Fjob        : chr  "other" "other" "other" "health" ...
##  $ reason      : chr  "home" "reputation" "reputation" "course" ...
##  $ nursery     : chr  "yes" "no" "yes" "yes" ...
##  $ internet    : chr  "yes" "yes" "no" "yes" ...
##  $ guardian.x  : chr  "mother" "mother" "mother" "mother" ...
##  $ traveltime.x: int  2 1 1 1 2 1 2 2 2 1 ...
##  $ studytime.x : int  4 2 1 3 3 3 3 2 4 4 ...
##  $ failures.x  : int  1 2 0 0 2 0 2 0 0 0 ...
##  $ schoolsup.x : chr  "yes" "yes" "yes" "yes" ...
##  $ famsup.x    : chr  "yes" "yes" "yes" "yes" ...
##  $ paid.x      : chr  "yes" "no" "yes" "yes" ...
##  $ activities.x: chr  "yes" "no" "yes" "yes" ...
##  $ higher.x    : chr  "yes" "yes" "yes" "yes" ...
##  $ romantic.x  : chr  "no" "yes" "no" "no" ...
##  $ famrel.x    : int  3 3 4 4 4 4 4 4 4 4 ...
##  $ freetime.x  : int  1 3 3 3 2 3 2 1 4 3 ...
##  $ goout.x     : int  2 4 1 2 1 2 2 3 2 3 ...
##  $ Dalc.x      : int  1 2 1 1 2 1 2 1 2 1 ...
##  $ Walc.x      : int  1 4 1 1 3 1 2 3 3 1 ...
##  $ health.x    : int  1 5 2 5 3 5 5 4 3 4 ...
##  $ absences.x  : int  2 2 8 2 8 2 0 2 12 10 ...
##  $ G1.x        : int  7 8 14 10 10 12 12 8 16 10 ...
##  $ G2.x        : int  10 6 13 9 10 12 0 9 16 11 ...
##  $ G3.x        : int  10 5 13 8 10 11 0 8 16 11 ...
##  $ guardian.y  : chr  "mother" "mother" "mother" "mother" ...
##  $ traveltime.y: int  2 1 1 1 2 1 2 2 2 1 ...
##  $ studytime.y : int  4 2 1 3 3 3 3 2 4 4 ...
##  $ failures.y  : int  0 0 0 0 0 0 0 0 0 0 ...
##  $ schoolsup.y : chr  "yes" "yes" "yes" "yes" ...
##  $ famsup.y    : chr  "yes" "yes" "yes" "yes" ...
##  $ paid.y      : chr  "yes" "no" "no" "no" ...
##  $ activities.y: chr  "yes" "no" "yes" "yes" ...
##  $ higher.y    : chr  "yes" "yes" "yes" "yes" ...
##  $ romantic.y  : chr  "no" "yes" "no" "no" ...
##  $ famrel.y    : int  3 3 4 4 4 4 4 4 4 4 ...
##  $ freetime.y  : int  1 3 3 3 2 3 2 1 4 3 ...
##  $ goout.y     : int  2 4 1 2 1 2 2 3 2 3 ...
##  $ Dalc.y      : int  1 2 1 1 2 1 2 1 2 1 ...
##  $ Walc.y      : int  1 4 1 1 3 1 2 3 3 1 ...
##  $ health.y    : int  1 5 2 5 3 5 5 4 3 4 ...
##  $ absences.y  : int  4 2 8 2 2 2 0 0 6 10 ...
##  $ G1.y        : int  13 13 14 10 13 11 10 11 15 10 ...
##  $ G2.y        : int  13 11 13 11 13 12 11 10 15 10 ...
##  $ G3.y        : int  13 11 12 10 13 12 12 11 15 10 ...

G3.x and G3.y represent the final score for both math and Portuguese language subjects which is our dependent variable. Let’s take a closer look to these two variables!

mean_g3x <- mean(df$G3.x, na.rm = TRUE)
median_g3x <- median(df$G3.x, na.rm = TRUE)
sd_g3x <- sd(df$G3.x, na.rm = TRUE)

mean_g3y <- mean(df$G3.y, na.rm = TRUE)
median_g3y <- median(df$G3.y, na.rm = TRUE)
sd_g3y <- sd(df$G3.y, na.rm = TRUE)

# Create a data frame for the results
results <- data.frame(
  Metric = c("Mean", "Median", "Standard Deviation"),
  G3x = c(mean_g3x, median_g3x, sd_g3x),
  G3y = c(mean_g3y, median_g3y, sd_g3y)
)

# Create the table
kable(results, caption = "Statistical Summary for G3.x and G3.y", align = 'c')
Statistical Summary for G3.x and G3.y
Metric G3x G3y
Mean 10.387435 12.515707
Median 11.000000 13.000000
Standard Deviation 4.687242 2.945438

Single Variables Visualisation

numeric_cols <- names(df)[sapply(df, is.numeric)]
character_cols <- names(df)[sapply(df, is.character)]

long_df_numeric <- pivot_longer(df, cols = all_of(numeric_cols), names_to = "variable", values_to = "value") %>%
  mutate(value = as.character(value))

long_df_character <- pivot_longer(df, cols = all_of(character_cols), names_to = "variable", values_to = "value")

long_df <- bind_rows(long_df_numeric, long_df_character)

for (var in unique(long_df$variable)) {
  print(
    ggplot(subset(long_df, variable == var), aes(x = value)) +
      geom_bar() +
      theme_minimal() +
      theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
      labs(title = var)
  )
}

Visualisation of relationship with G3

#The relationship of G3 and study time
ggplot(df, aes(x = factor(studytime.x), y = G3.x)) + 
  geom_boxplot() +
  labs(title = "Study Time vs G3.x (Math)", x = "Study Time", y = "Final Grade (Math)")

ggplot(df, aes(x = factor(studytime.y), y = G3.y)) + 
  geom_boxplot() +
  labs(title = "Study Time vs G3.y (Portuguese)", x = "Study Time", y = "Final Grade (Portuguese)")

#The relationship of G3 and Medu
ggplot(df, aes(x = factor(Medu), y = G3.x)) + 
  geom_boxplot() +
  labs(title = "Mother's Education vs G3.x (Math)", x = "Mother's Education", y = "G3.x Score")

ggplot(df, aes(x = factor(Medu), y = G3.y)) + 
  geom_boxplot() +
  labs(title = "Mother's Education vs G3.y (Portuguese)", x = "Mother's Education", y = "G3.y Score")

#The relationship of G3 and Fedu
ggplot(df, aes(x = factor(Fedu), y = G3.x)) + 
  geom_boxplot() +
  labs(title = "Father's Education vs G3.x (Math)", x = "Father's Education", y = "G3.x Score")

ggplot(df, aes(x = factor(Fedu), y = G3.y)) + 
  geom_boxplot() +
  labs(title = "Father's Education vs G3.y (Portuguese)", x = "Father's Education", y = "G3.y Score")

#The relationship of G3 and guardian
ggplot(df, aes(x = factor(guardian.x), y = G3.x)) + 
  geom_boxplot() +
  labs(title = "Guardian vs G3.x (Math)", x = "Guardian", y = "G3.x Score")

ggplot(df, aes(x = factor(guardian.y), y = G3.y)) + 
  geom_boxplot() +
  labs(title = "Guardian vs G3.y (Portuguese)", x = "Guardian", y = "G3.y Score")

#The relationship of G3 and Nursery
ggplot(df, aes(x = factor(nursery), y = G3.x)) + 
  geom_boxplot() +
  labs(title = "Nursery School vs G3.x (Math)", x = "Nursery School", y = "G3.x Score")

#The relationship of G3 and failures
ggplot(df, aes(x = factor(failures.x), y = G3.x)) + 
  geom_boxplot() +
  labs(title = "Number of Failures vs G3.x (Math)", x = "Number of Failures", y = "G3.x Score")

ggplot(df, aes(x = factor(failures.y), y = G3.y)) + 
  geom_boxplot() +
  labs(title = "Number of Failures vs G3.y (Portuguese)", x = "Number of Failures", y = "G3.y Score")

#The relationship of G3 and school
ggplot(df, aes(x = factor(school), y = G3.x)) + 
  geom_boxplot() +
  labs(title = "School Type vs G3.x (Math)", x = "School Type", y = "G3.x Score")

#The relationship of G3 and Family Size (famsize)
ggplot(df, aes(x = famsize, y = G3.x)) +
  geom_boxplot() +
  labs(title = "Family Size vs G3", x = "Family Size", y = "G3 Score")

ggplot(df, aes(x = famsize, y = G3.y)) +
  geom_boxplot() +
  labs(title = "Family Size vs G3", x = "Family Size", y = "G3 Score")

#The relationship of G3 and Mother's Job (Mjob)
ggplot(df, aes(x = Mjob, y = G3.x)) +
  geom_boxplot() +
  labs(title = "Mother's Job vs G3", x = "Mother's Job", y = "G3 Score")

ggplot(df, aes(x = Mjob, y = G3.y)) +
  geom_boxplot() +
  labs(title = "Mother's Job vs G3", x = "Mother's Job", y = "G3 Score")

#The relationship of G3 and Father's Job (Fjob)
ggplot(df, aes(x = Fjob, y = G3.x)) +
  geom_boxplot() +
  labs(title = "Father's Job vs G3", x = "Father's Job", y = "G3 Score")

ggplot(df, aes(x = Fjob, y = G3.y)) +
  geom_boxplot() +
  labs(title = "Father's Job vs G3", x = "Father's Job", y = "G3 Score")

#The relationship of G3 and Extra Educational Support (schoolsup)
ggplot(df, aes(x = schoolsup.x, y = G3.x)) +
  geom_boxplot() +
  labs(title = "Extra Educational Support vs G3", x = "Extra Educational Support", y = "G3 Score")

ggplot(df, aes(x = schoolsup.y, y = G3.y)) +
  geom_boxplot() +
  labs(title = "Extra Educational Support vs G3", x = "Extra Educational Support", y = "G3 Score")

#The relationship of G3 and Family Educational Support (famsup)
ggplot(df, aes(x = famsup.x, y = G3.x)) +
  geom_boxplot() +
  labs(title = "Family Educational Support vs G3", x = "Family Educational Support", y = "G3 Score")

ggplot(df, aes(x = famsup.y, y = G3.y)) +
  geom_boxplot() +
  labs(title = "Family Educational Support vs G3", x = "Family Educational Support", y = "G3 Score")

#The relationship of G3 and Family Relationships (famrel)
ggplot(df, aes(x = factor(famrel.x), y = G3.x)) +
  geom_boxplot() +
  labs(title = "Quality of Family Relationships vs G3", x = "Quality of Family Relationships", y = "G3 Score")

ggplot(df, aes(x = factor(famrel.y), y = G3.y)) +
  geom_boxplot() +
  labs(title = "Quality of Family Relationships vs G3", x = "Quality of Family Relationships", y = "G3 Score")

#The relationship of G3 and Free Time after School (freetime)
ggplot(df, aes(x = factor(freetime.x), y = G3.x)) +
  geom_boxplot() +
  labs(title = "Free Time after School vs G3", x = "Free Time after School", y = "G3 Score")

ggplot(df, aes(x = factor(freetime.y), y = G3.y)) +
  geom_boxplot() +
  labs(title = "Free Time after School vs G3", x = "Free Time after School", y = "G3 Score")

#The relationship of G3 and Going Out with Friends (goout)
ggplot(df, aes(x = factor(goout.x), y = G3.x)) +
  geom_boxplot() +
  labs(title = "Going Out with Friends vs G3", x = "Going Out with Friends", y = "G3 Score")

ggplot(df, aes(x = factor(goout.y), y = G3.y)) +
  geom_boxplot() +
  labs(title = "Going Out with Friends vs G3", x = "Going Out with Friends", y = "G3 Score")

#The relationship of G3 and Workday Alcohol Consumption (Dalc)
ggplot(df, aes(x = factor(Dalc.x), y = G3.x)) +
  geom_boxplot() +
  labs(title = "Workday Alcohol Consumption vs G3", x = "Workday Alcohol Consumption", y = "G3 Score")

ggplot(df, aes(x = factor(Dalc.y), y = G3.y)) +
  geom_boxplot() +
  labs(title = "Workday Alcohol Consumption vs G3", x = "Workday Alcohol Consumption", y = "G3 Score")

#The relationship of G3 and Weekend Alcohol Consumption (Walc)
ggplot(df, aes(x = factor(Walc.x), y = G3.x)) +
  geom_boxplot() +
  labs(title = "Weekend Alcohol Consumption vs G3", x = "Weekend Alcohol Consumption", y = "G3 Score")

ggplot(df, aes(x = factor(Walc.y), y = G3.y)) +
  geom_boxplot() +
  labs(title = "Weekend Alcohol Consumption vs G3", x = "Weekend Alcohol Consumption", y = "G3 Score")

#The relationship of G3 and Current Health Status (health)
ggplot(df, aes(x = factor(health.x), y = G3.x)) +
  geom_boxplot() +
  labs(title = "Current Health Status vs G3", x = "Current Health Status", y = "G3 Score")

ggplot(df, aes(x = factor(health.y), y = G3.y)) +
  geom_boxplot() +
  labs(title = "Current Health Status vs G3", x = "Current Health Status", y = "G3 Score")

Statistical analysis

#ANOVA
#Gender
anova_sex_g3x <- aov(G3.x ~ sex, data = df)
anova_sex_g3y <- aov(G3.y ~ sex, data = df)

#Education 
anova_medu_g3x <- aov(G3.x ~ factor(Medu), data = df)
anova_medu_g3x <- aov(G3.y ~ factor(Medu), data = df)
anova_fedu_g3x <- aov(G3.x ~ factor(Fedu), data = df)
anova_fedu_g3x <- aov(G3.y ~ factor(Fedu), data = df)

#Health
anova_health_x_g3x <- aov(G3.x ~ health.x, data = df)
anova_health_y_g3y <- aov(G3.y ~ health.y, data = df)

#Pearson correlation
#G2 and G3
cor_g2x_g3x <- cor.test(df$G2.x, df$G3.x, method = "pearson")
cor_g2y_g3y <- cor.test(df$G2.y, df$G3.y, method = "pearson")

#Study time with G3
cor_test_studytime_x_g3x <- cor.test(df$studytime.x, df$G3.x, method = "pearson")
cor_test_studytime_y_g3y <- cor.test(df$studytime.y, df$G3.y, method = "pearson")

#Failures experience with G3
spearman_corr_failures_g3x <- cor.test(df$failures.x, df$G3.x, method = "spearman")
spearman_corr_failures_g3y <- cor.test(df$failures.y, df$G3.y, method = "spearman")


#Create a dataframe for the ANOVA result
anova_results <- data.frame(
  Variable = c("Sex (G3.x)", "Sex (G3.y)", "Mother's Education (G3.x)", "Mother's Education (G3.y)", "Father's Education (G3.x)", "Father's Education (G3.y)", "Health (G3.x)", "Health (G3.y)"),
  Df = c(1, 1, 4, 4, 4, 4, 1, 1),
  Sum_Sq = c(124, 134, 440, 144.5, 304, 142, 30, 112),
  Mean_Sq = c(123.9, 133.63, 110.06, 36.13, 76.01, 35.53, 29.56, 111.5),
  F_value = c(5.71, 16.01, 5.232, 4.309, 3.552, 4.235, 1.347, 13.27),
  Pr_F = c(0.0174, 7.58e-05, 0.000412, 0.00202, 0.00734, 0.0023, 0.247, 0.000307)
)

# Create Kable table
kable(anova_results, caption = "ANOVA Results Summary")
ANOVA Results Summary
Variable Df Sum_Sq Mean_Sq F_value Pr_F
Sex (G3.x) 1 124.0 123.90 5.710 1.74e-02
Sex (G3.y) 1 134.0 133.63 16.010 7.58e-05
Mother’s Education (G3.x) 4 440.0 110.06 5.232 4.12e-04
Mother’s Education (G3.y) 4 144.5 36.13 4.309 2.02e-03
Father’s Education (G3.x) 4 304.0 76.01 3.552 7.34e-03
Father’s Education (G3.y) 4 142.0 35.53 4.235 2.30e-03
Health (G3.x) 1 30.0 29.56 1.347 2.47e-01
Health (G3.y) 1 112.0 111.50 13.270 3.07e-04
# Create a data frame for Pearson result
correlation_results <- data.frame(
  Comparison = c("G2.x and G3.x", "G2.y and G3.y"),
  Correlation = c(cor_g2x_g3x$estimate, cor_g2y_g3y$estimate),
  P_Value = c(cor_g2x_g3x$p.value, cor_g2y_g3y$p.value)
)

# Create kable table for Pearson
kable(correlation_results, caption = "Pearson Correlation Results Summary")
Pearson Correlation Results Summary
Comparison Correlation P_Value
G2.x and G3.x 0.9030267 0
G2.y and G3.y 0.8924436 0
# Create a data frame for Spearman results
spearman_results <- data.frame(
  Comparison = c("Failures (G3.x) and G3.x", "Failures (G3.y) and G3.y"),
  Correlation = c(-0.398, -0.342),
  P_Value = c("5.765e-16", "6.854e-12")
)

# Create kable table for Spearman
kable(spearman_results, caption = "Spearman Correlation Results Summary")
Spearman Correlation Results Summary
Comparison Correlation P_Value
Failures (G3.x) and G3.x -0.398 5.765e-16
Failures (G3.y) and G3.y -0.342 6.854e-12

EDA Findings

Our EDA for this student performance data set began with single-variable explorations. We reveal crucial insights into each variable’s distribution and its relationship with G3 scores.

Besides, We discovered that gender significantly impacts Portuguese language scores, as shown by ANOVA tests. Parent education emerged as a key factor, it showing a significant correlation with G3 scores. The health status of students only shows statistical significant for language scores.

Pearson correlation tests indicated a strong positive link between G2 and G3 scores, suggesting that prior performance is a potential indicator of students’ final results. Study time was weak correlated with final scores, particularly in language results.

We faced a statistical nuance in the analysis while computing Spearman rank correlation for the relationship between the number of failures and final scores. A warning indicated difficulties in calculating exact p-values due to ‘ties’ in failure data. Such ties occur when multiple students have the same number of failures, affecting the ranking process used in Spearman analysis. Despite this, we observed a negative correlation, suggesting increased failures correlate with lower final scores. The approximation in p-value computation doesn’t significantly detract from the validity of this finding.

These findings highlight gender, parental education, health status, previous academic performance, study time, and failure experience as essential factors for our predictive modelling to help us determine the impact on educational outcomes for the prediction.

Random Forest

Data Preparation

First, extract features that will be used to train the model

data <- df %>% select("sex", "Medu", "Fedu", "health.x", "studytime.x", "failures.x", "G1.x", "G2.x", "G3.x") %>% mutate(G3.x = factor(G3.x))

Since there is an imbalanced data in the G3.x (target), oversampling is performed

data <- data %>% group_by(G3.x) %>%  slice(sample(n(), 20, replace = T)) %>% ungroup() %>% as.data.frame()

Perform train test split with 80% of train data and 20% of test data

index <- createDataPartition(data$G3.x, p = 0.8, list = FALSE)

data_train <- data[index, ]
data_test <- data[-index, ]

Modeling

model_rf <- randomForest(G3.x ~ ., data=data_train, importance=TRUE)
model_rf
## 
## Call:
##  randomForest(formula = G3.x ~ ., data = data_train, importance = TRUE) 
##                Type of random forest: classification
##                      Number of trees: 500
## No. of variables tried at each split: 2
## 
##         OOB estimate of  error rate: 30.21%
## Confusion matrix:
##    0  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 class.error
## 0  5  0  1  3  1  1  2  3  0  0  0  0  0  0  0  0  0  0      0.6875
## 4  0 16  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0      0.0000
## 5  0  0 14  1  1  0  0  0  0  0  0  0  0  0  0  0  0  0      0.1250
## 6  1  1  0 13  0  0  0  1  0  0  0  0  0  0  0  0  0  0      0.1875
## 7  0  0  0  1 15  0  0  0  0  0  0  0  0  0  0  0  0  0      0.0625
## 8  2  1  0  0  1 11  0  1  0  0  0  0  0  0  0  0  0  0      0.3125
## 9  0  0  0  0  0  0 14  1  1  0  0  0  0  0  0  0  0  0      0.1250
## 10 1  0  0  0  0  5  3  5  0  2  0  0  0  0  0  0  0  0      0.6875
## 11 0  0  0  0  0  0  1  1  8  4  2  0  0  0  0  0  0  0      0.5000
## 12 0  0  0  0  0  0  0  5  4  5  2  0  0  0  0  0  0  0      0.6875
## 13 0  0  0  0  0  0  0  1  1  3  9  2  0  0  0  0  0  0      0.4375
## 14 0  0  0  0  0  0  0  0  2  3  3  7  1  0  0  0  0  0      0.5625
## 15 0  0  0  0  0  0  0  0  0  0  1  3  9  2  1  0  0  0      0.4375
## 16 0  0  0  0  0  0  0  0  0  0  0  0  3  9  4  0  0  0      0.4375
## 17 0  0  0  0  0  0  0  0  0  0  0  0  0  0 15  1  0  0      0.0625
## 18 0  0  0  0  0  0  0  0  0  0  0  0  0  1  0 14  1  0      0.1250
## 19 0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0 16  0      0.0000
## 20 0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0 16      0.0000

Evaluation

Evaluate the trained model using test data.

# Test the model using test data
prediction <- predict(model_rf, data_test %>% select(-c("G3.x")))
confusionMatrix(prediction, data_test$G3.x)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction 0 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
##         0  3 0 1 0 1 2 0  0  0  0  0  0  0  0  0  0  0  0
##         4  0 4 0 0 0 0 0  0  0  0  0  0  0  0  0  0  0  0
##         5  0 0 3 1 0 0 0  0  0  0  0  0  0  0  0  0  0  0
##         6  0 0 0 3 0 0 1  0  0  0  0  0  0  0  0  0  0  0
##         7  0 0 0 0 3 1 0  0  0  0  0  0  0  0  0  0  0  0
##         8  0 0 0 0 0 0 1  0  0  0  0  0  0  0  0  0  0  0
##         9  0 0 0 0 0 1 1  1  0  0  0  0  0  0  0  0  0  0
##         10 1 0 0 0 0 0 0  2  0  0  0  0  0  0  0  0  0  0
##         11 0 0 0 0 0 0 1  0  4  2  0  0  0  0  0  0  0  0
##         12 0 0 0 0 0 0 0  0  0  2  0  1  0  0  0  0  0  0
##         13 0 0 0 0 0 0 0  1  0  0  3  1  0  0  0  0  0  0
##         14 0 0 0 0 0 0 0  0  0  0  1  2  1  1  0  0  0  0
##         15 0 0 0 0 0 0 0  0  0  0  0  0  3  0  0  1  0  0
##         16 0 0 0 0 0 0 0  0  0  0  0  0  0  3  0  0  0  0
##         17 0 0 0 0 0 0 0  0  0  0  0  0  0  0  4  0  0  0
##         18 0 0 0 0 0 0 0  0  0  0  0  0  0  0  0  3  0  0
##         19 0 0 0 0 0 0 0  0  0  0  0  0  0  0  0  0  4  0
##         20 0 0 0 0 0 0 0  0  0  0  0  0  0  0  0  0  0  4
## 
## Overall Statistics
##                                           
##                Accuracy : 0.7083          
##                  95% CI : (0.5893, 0.8095)
##     No Information Rate : 0.0556          
##     P-Value [Acc > NIR] : < 2.2e-16       
##                                           
##                   Kappa : 0.6912          
##                                           
##  Mcnemar's Test P-Value : NA              
## 
## Statistics by Class:
## 
##                      Class: 0 Class: 4 Class: 5 Class: 6 Class: 7 Class: 8
## Sensitivity           0.75000  1.00000  0.75000  0.75000  0.75000  0.00000
## Specificity           0.94118  1.00000  0.98529  0.98529  0.98529  0.98529
## Pos Pred Value        0.42857  1.00000  0.75000  0.75000  0.75000  0.00000
## Neg Pred Value        0.98462  1.00000  0.98529  0.98529  0.98529  0.94366
## Prevalence            0.05556  0.05556  0.05556  0.05556  0.05556  0.05556
## Detection Rate        0.04167  0.05556  0.04167  0.04167  0.04167  0.00000
## Detection Prevalence  0.09722  0.05556  0.05556  0.05556  0.05556  0.01389
## Balanced Accuracy     0.84559  1.00000  0.86765  0.86765  0.86765  0.49265
##                      Class: 9 Class: 10 Class: 11 Class: 12 Class: 13 Class: 14
## Sensitivity           0.25000   0.50000   1.00000   0.50000   0.75000   0.50000
## Specificity           0.97059   0.98529   0.95588   0.98529   0.97059   0.95588
## Pos Pred Value        0.33333   0.66667   0.57143   0.66667   0.60000   0.40000
## Neg Pred Value        0.95652   0.97101   1.00000   0.97101   0.98507   0.97015
## Prevalence            0.05556   0.05556   0.05556   0.05556   0.05556   0.05556
## Detection Rate        0.01389   0.02778   0.05556   0.02778   0.04167   0.02778
## Detection Prevalence  0.04167   0.04167   0.09722   0.04167   0.06944   0.06944
## Balanced Accuracy     0.61029   0.74265   0.97794   0.74265   0.86029   0.72794
##                      Class: 15 Class: 16 Class: 17 Class: 18 Class: 19
## Sensitivity            0.75000   0.75000   1.00000   0.75000   1.00000
## Specificity            0.98529   1.00000   1.00000   1.00000   1.00000
## Pos Pred Value         0.75000   1.00000   1.00000   1.00000   1.00000
## Neg Pred Value         0.98529   0.98551   1.00000   0.98551   1.00000
## Prevalence             0.05556   0.05556   0.05556   0.05556   0.05556
## Detection Rate         0.04167   0.04167   0.05556   0.04167   0.05556
## Detection Prevalence   0.05556   0.04167   0.05556   0.04167   0.05556
## Balanced Accuracy      0.86765   0.87500   1.00000   0.87500   1.00000
##                      Class: 20
## Sensitivity            1.00000
## Specificity            1.00000
## Pos Pred Value         1.00000
## Neg Pred Value         1.00000
## Prevalence             0.05556
## Detection Rate         0.05556
## Detection Prevalence   0.05556
## Balanced Accuracy      1.00000
# Variable importance plot
varImpPlot(model_rf)

GBM

Data Preparation

Data selection of the variables to analyze

data <- df %>% select("sex", "Medu", "Fedu", "health.y", "studytime.y","freetime.y","absences.y","G1.y", "G2.y", "G3.y")

Convert categorical variables to factors if not already

data$studytime.y <- as.factor(data$studytime.y)
data$sex <- as.factor(data$sex)

Convert ‘sex’ variable into binary format

data$sex_binary <- ifelse(data$sex == "F", 0, 1)

Considering of 70/30 Split as a reasonable split because we have a moderate-sized dataset of 382 observations

set.seed(123)  # for reproducibility
trainIndex <- sample(1:nrow(data), 0.7 * nrow(data))
trainData <- data[trainIndex, ]
testData <- data[-trainIndex, ]

Modeling for Classification

Create a classification model for studytime.y using train data

# Classification using GBM with binary response
classification_model <- gbm(studytime.y ~ ., data = trainData, distribution = "multinomial", n.trees = 100, interaction.depth = 4, shrinkage = 0.01)
## Warning: Setting `distribution = "multinomial"` is ill-advised as it is
## currently broken. It exists only for backwards compatibility. Use at your own
## risk.
# Summary of the classification model
summary(classification_model)

##                   var   rel.inf
## absences.y absences.y 17.049527
## G3.y             G3.y 14.393278
## G2.y             G2.y 13.844942
## G1.y             G1.y 13.255341
## health.y     health.y  9.827764
## Fedu             Fedu  7.303855
## sex               sex  7.154498
## freetime.y freetime.y  6.728204
## Medu             Medu  5.735124
## sex_binary sex_binary  4.707467

Evaluation for Classification

Evaluate the trained model using test data

# Evaluate the model's performance
predict_class <- predict(classification_model, testData, n.trees = 100, type = "response")
results_class <- data.frame(Actual = testData$studytime.y, Predicted = predict_class)
predicted_classes <- apply(results_class[, -1], 1, function(row) {which.max(row)})
levels_actual <- levels(results_class$Actual)
predicted_classes <- factor(predicted_classes, levels = levels_actual)

# Create a confusion matrix
confusionMatrix(predicted_classes, testData$studytime.y)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  1  2  3  4
##          1  7  6  1  0
##          2 20 49 21  9
##          3  0  2  0  0
##          4  0  0  0  0
## 
## Overall Statistics
##                                           
##                Accuracy : 0.487           
##                  95% CI : (0.3927, 0.5819)
##     No Information Rate : 0.4957          
##     P-Value [Acc > NIR] : 0.61            
##                                           
##                   Kappa : 0.0524          
##                                           
##  Mcnemar's Test P-Value : NA              
## 
## Statistics by Class:
## 
##                      Class: 1 Class: 2 Class: 3 Class: 4
## Sensitivity           0.25926   0.8596  0.00000  0.00000
## Specificity           0.92045   0.1379  0.97849  1.00000
## Pos Pred Value        0.50000   0.4949  0.00000      NaN
## Neg Pred Value        0.80198   0.5000  0.80531  0.92174
## Prevalence            0.23478   0.4957  0.19130  0.07826
## Detection Rate        0.06087   0.4261  0.00000  0.00000
## Detection Prevalence  0.12174   0.8609  0.01739  0.00000
## Balanced Accuracy     0.58986   0.4988  0.48925  0.50000

Modeling for Regression

Create a Regression model for G3.y using train data

#Create a regression model for G3.y
regression_model <- gbm(G3.y ~ ., data = trainData, distribution = "gaussian", n.trees = 100, interaction.depth = 3)

# Summary of the regression model
summary(regression_model)

##                     var    rel.inf
## G2.y               G2.y 74.5669501
## G1.y               G1.y 11.6645109
## absences.y   absences.y  3.3303632
## studytime.y studytime.y  3.0536021
## Fedu               Fedu  2.4244802
## Medu               Medu  2.0663494
## freetime.y   freetime.y  1.4078908
## health.y       health.y  0.8561561
## sex                 sex  0.4473757
## sex_binary   sex_binary  0.1823217

Evaluation for Regression

Evaluate the trained model using test data

# Evaluate the model's performance
predict_regres <- predict(regression_model, testData, n.trees = 100)
results_regres <- data.frame(Actual = testData$G3.y, Predicted = predict_regres)
results_regres$Predicted <- floor(results_regres$Predicted)

# Create a confusion matrix
confusion_matrix <- table(results_regres$Actual, results_regres$Predicted)

# Print the confusion matrix
print(confusion_matrix)
##     
##      6 7 8 9 10 11 12 13 14 15 16 17
##   0  1 0 0 0  0  0  0  0  0  0  0  0
##   1  0 0 0 0  0  1  0  0  0  0  0  0
##   8  0 0 1 0  0  0  0  0  0  0  0  0
##   9  0 1 1 0  0  0  1  0  0  0  0  0
##   10 0 1 1 4  5  2  0  1  0  0  0  0
##   11 0 0 0 0  4  9  0  0  0  0  0  0
##   12 0 0 0 0  1  7  9  3  0  0  0  0
##   13 0 0 0 0  0  2  6  9  0  0  0  0
##   14 0 0 0 0  0  0  3  7  5  0  0  0
##   15 0 0 0 0  0  0  0  1  3  4  1  0
##   16 0 0 0 0  0  0  0  0  1  4  6  0
##   17 0 0 0 0  0  0  0  0  1  0  2  1
##   18 0 0 0 0  0  0  0  0  0  0  1  4
##   19 0 0 0 0  0  0  0  0  0  0  1  0
# Evaluation Metrics based on 'predict_regres' as our predicted values and 'testData$G3.y' as our actual values
mae <- mean(abs(predict_regres - testData$G3.y))
mse <- mean((predict_regres - testData$G3.y)^2)
rmse <- sqrt(mse)
r_squared <- 1 - (sum((testData$G3.y - predict_regres)^2) / sum((testData$G3.y - mean(testData$G3.y))^2))

# Print the evaluation metrics
cat("Mean Absolute Error (MAE):", mae, "\n")
## Mean Absolute Error (MAE): 0.8332569
cat("Mean Squared Error (MSE):", mse, "\n")
## Mean Squared Error (MSE): 2.108806
cat("Root Mean Squared Error (RMSE):", rmse, "\n")
## Root Mean Squared Error (RMSE): 1.452173
cat("R-squared (R²):", r_squared, "\n")
## R-squared (R²): 0.7464548
# Checked the Accuracy of the predicton
accuracy <- mean(results_regres$Predicted == testData$G3.y)
print(paste("Accuracy:", accuracy))
## [1] "Accuracy: 0.426086956521739"
# Visualization of the prediction
ggplot(results_regres, aes(x = Actual, y = Predicted)) +
    geom_point() +
    labs(x = "Actual G3.y", y = "Predicted G3.y") +
    ggtitle("Scatterplot of Actual vs. Predicted G3.y")

ggplot(results_regres, aes(x = 1:nrow(results_class), y = Actual, group = 1)) +
    geom_line(aes(y = Actual, color = "Actual"), linetype = "solid") +
    geom_line(aes(y = Predicted, color = "Predicted"), linetype = "dashed") +
    labs(x = "Data Point", y = "G3.y Value") +
    scale_color_manual(values = c("Actual" = "blue", "Predicted" = "red")) +
    ggtitle("Line Chart of Actual vs. Predicted G3.y")

# Evalute the random forest model using test data
# Make predictions on test data
predict_rf_test <- predict(model_rf, data_test %>% select(-c("G3.x")))
results_rf_test <- data.frame(Actual = data_test$G3.x, Predicted = predict_rf_test)
results_rf_test$Predicted <- as.numeric(as.character(results_rf_test$Predicted))


# Line chart for test data
ggplot(results_rf_test, aes(x = 1:nrow(results_rf_test), y = Actual, group = 1)) +
  geom_line(aes(y = Actual, color = "Actual"), linetype = "solid") +
  geom_line(aes(y = Predicted, color = "Predicted"), linetype = "dashed") +
  labs(x = "Data Point", y = "G3.x Value") +
  scale_color_manual(values = c("Actual" = "blue", "Predicted" = "red")) +
  ggtitle("Line Chart of Actual vs. Predicted G3.x (Test)")

Model Evalution

After analyzing the Random Forest and Gradient Boosting machine (GBM) models, we obtained the following accuracy scores:

  1. Random Forest: 0.7361
  2. GBM: 0.4869

The visual representation on the Line Chart underscores the Random Forest’s significantly higher accuracy, indicating superior predictive capabilities compared to GBM. Despite the relatively higher accuracy of the Random Forest model, both models show room for improvement. To enhance predictive performance, we can look into Feature Engineering, exploring additional relevant variables/features to provide more meaningful information to the model. Additionally, Data Augmentation techniques, such as oversampling and undersampling, can increase the size and diversity of our dataset. Another aspect to consider is cross-validation, where implementing techniques can help generalize the underseen data better and prevent overfitting.

The evaluation of Random Forest and GBM models unveils varying predictive performances. The Random Forest model excels with an accuracy of 73.61%, showcasing its effectiveness in predicting student performance based on selected features. Conversely, the GBM model lags with an accuracy of 48.69%, suggesting potential inefficiencies in capturing underlying data patterns. Evaluation metrics like Mean Absolute Error (MAE), Mean Squared Error (MSE), Root Mean Squared Error (RMSE), and R-squared (R²) offer comprehensive insights into predictive capabilities. Refinement opportunities lie in feature engineering, data augmentation, and model interpretability to elevate these models’ accuracy and optimize educational outcome predictions.

Conclusion: In conclusion, our exploration of student performance data using exploratory data analysis (EDA), Random Forest, and Gradient Boosting Machine (GBM) models has provided valuable insights. The EDA revealed key factors such as gender, parental education, health status, prior academic performance, study time, and the experience of failures as crucial elements influencing students’ final grades. The predictive models, particularly Random Forest, demonstrated varying levels of accuracy. The Random Forest model exhibited a higher accuracy rate of 73.61%, outperforming the GBM model with an accuracy of 48.69%. While these accuracies indicate predictive capabilities, further improvement is possible through techniques like feature engineering, data augmentation, and a deeper exploration of cross-validation. These steps can refine the models, making them more robust and insightful for better understanding and predicting student performance.