libraries

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(ggplot2)
library(caret)
## Warning: package 'caret' was built under R version 4.0.5
## Loading required package: lattice
library(pROC)
## Warning: package 'pROC' was built under R version 4.0.5
## Type 'citation("pROC")' for a citation.
## 
## Attaching package: 'pROC'
## The following objects are masked from 'package:stats':
## 
##     cov, smooth, var
  1. Download the classification output data set.(attached in Blackboard to the assignment)
df = read.csv("https://raw.githubusercontent.com/BDavidoff/Data_621/main/classification-output-data.csv")
df = df[,c('class', 'scored.class','scored.probability')]
  1. The data set has three key columns we will use; Use the table() function to get the raw confusion matrix for this scored dataset. Make sure you understand the output. In particular, do the rows represent the actual or predicted class? The columns?
cm <- table("predicted" = df$scored.class, "actual" = df$class)
cm
##          actual
## predicted   0   1
##         0 119  30
##         1   5  27

The rows represent the predicted class and the columns represent the actual class.

  1. Write a function that takes the data set as a dataframe, with actual and predicted classifications identified, and returns the accuracy of the predictions.
outcomes = function(df){
  outs=aggregate(df, by = list(df[,1], df[,2]), FUN=length) %>%
    select(1:3) %>%
    `colnames<-` (c('class','prediction','count'))
  return(outs)
}

acc = function(df){
  outs = outcomes(df)
  TN = outs$count[1]
  FN = outs$count[2]
  TP = outs$count[4]
  FP = outs$count[3]
  acc = (TP+TN)/(TP+FP+TN+FN)
  return(acc)
}
acc(df)
## [1] 0.8066298
  1. Write a function that takes the data set as a dataframe, with actual and predicted classifications identified, and returns the classification error rate of the predictions.
class_error_rate = function(df){
  outs = outcomes(df)
  TN = outs$count[1]
  FN = outs$count[2]
  TP = outs$count[4]
  FP = outs$count[3]
  cer = (FP+FN)/(TP+FP+TN+FN)
  return(cer)
}
class_error_rate(df)
## [1] 0.1933702
  1. Write a function that takes the data set as a dataframe, with actual and predicted classifications identified, and returns the precision of the predictions.
# specify
func_prec <- function(dataframe, actual, predicted){
    y <- as.vector(table(df[,actual], df[,predicted]))
    names(y) <- c("TN", "FP", "FN", "TP")
    prec <- y["TP"] / (y["TP"] + y["FP"])
    return(prec)
}
pres <- func_prec(df, "class", "scored.class")
pres
##        TP 
## 0.4736842
  1. Write a function that takes the data set as a dataframe, with actual and predicted classifications identified, and returns the sensitivity of the predictions. Sensitivity is also known as recall.
func_sens <- function(dataframe, actual, predicted){
    y <- as.vector(table(df[,actual], df[,predicted]))
    names(y) <- c("TN", "FP", "FN", "TP")
    sens <- y["TP"] /(y["TP"] + y["FN"])
    return(sens)
}
sens <- func_sens(df, "class", "scored.class")
sens
##      TP 
## 0.84375
  1. Write a function that takes the data set as a dataframe, with actual and predicted classifications identified, and returns the specificity of the predictions.
func_spec <- function(dataframe, actual, predicted){
    y <- as.vector(table(df[,actual], df[,predicted]))
    names(y) <- c("TN", "FP", "FN", "TP")
    spec <- y["TN"] / (y["TN"] + y["FP"])
    return(spec)
}
func_spec(df, "class", "scored.class")
##        TN 
## 0.7986577
  1. Write a function that takes the data set as a dataframe, with actual and predicted classifications identified, and returns the F1 score of the predictions.
func_F1 <- function(dataframe, actual, predicted){
    y <- as.vector(table(df[,actual], df[,predicted]))
    names(y) <- c("TN", "FP", "FN", "TP")
    f1 <- 2 * pres * sens /(pres + sens)
    return(f1)
}
func_F1(df, "class", "scored.class")
##        TP 
## 0.6067416
  1. Before we move on, let’s consider a question that was asked: What are the bounds on the F1 score? Show that the F1 score will always be between 0 and 1. (Hint: If 0 < 𝑎 < 1 and 0 < 𝑏 < 1 then 𝑎𝑏 < 𝑎.)

The F1 score is calculated from the precision and sensitivity scores which both have the bounds between 0 and 1, thus the highest score for F1 would be 1, from perfect precision and sensitivity, and the lowest would be 0, if either the precision or sensitivity value is 0.

Using a foreach loop, we can calculate every possible F1 value to show the range:

l = 20
p = seq(0,1, length.out = l)
df_a = NULL
for(i in 1:l) {
  j = i/l
  temp_df = data.frame(x = p, y = (2*p*j)/(p+j), col = rep(j:j,each = l))
  df_a = rbind(df_a, temp_df)
}
ggplot(df_a,aes(x=x,y=y,group=col,color=factor(col))) + 
  geom_line() +
  ggtitle('ALL F1 VALUES') +
  theme(plot.title = element_text(hjust = 0.5)) +
  ylab('F1') +
  xlab('Precision') + 
  ylim(0,1)

As you can see by this graph, the range does not exceed 0 or 1.

  1. Write a function that generates an ROC curve from a data set with a true classification column (class in our example) and a probability column (scored.probability in our example). Your function should return a list that includes the plot of the ROC curve and a vector that contains the calculated area under the curve (AUC). Note that I recommend using a sequence of thresholds ranging from 0 to 1 at 0.01 intervals.
func_roc <- function(actual, predicted) {
  tab <- as.matrix(table(df$scored.class, df$class))
  tot <- colSums(tab)
  TP <- rev(cumsum(rev(tab[2,])))
  FP <- rev(cumsum(rev(tab[1,])))
  totpositive <- sum(tab[2,])
  totnegative <- sum(tab[1,])
  sensi <-TP/totpositive
  one_minus_spec <- FP/totnegative
  sensi <- c(sensi, 0); one_minus_spec <- c(one_minus_spec, 0)
  
  plot(one_minus_spec, sensi, type = "b", xlab = "FPR", ylab = "TPR")
  grid()
  abline(0, 1, col = "red")
  
  # calculating the AUC
  height = (sensi[-1]+sensi[-length(sensi)])/2
  width = -diff(one_minus_spec) 
  sum(height*width)
  
}
func_roc(df$class, df$scored.class)

## [1] 0.8212039
# manually calculating
  1. Use your created R functions and the provided classification output data set to produce all of the classification metrics discussed above.
func_all_metrics <- function(dataframe){
    accuracy_matrix <- acc(df)
    classerror_matrix <- class_error_rate(df)
    precision_matrix <- func_prec(df, "class", "scored.class")
    sensitivity_matrix <- func_sens(df, "class", "scored.class")
    specificity_matrix <- func_spec(df, "class", "scored.class")
    F1_matrix <- func_F1(df, "class", "scored.class")
    
    output <- data.frame(accuracy_matrix, classerror_matrix, precision_matrix, sensitivity_matrix, specificity_matrix, F1_matrix)
    return(output)
}
func_all_metrics(df)
##    accuracy_matrix classerror_matrix precision_matrix sensitivity_matrix
## TP       0.8066298         0.1933702        0.4736842            0.84375
##    specificity_matrix F1_matrix
## TP          0.7986577 0.6067416
  1. Investigate the caret package. In particular, consider the functions confusionMatrix, sensitivity, and specificity. Apply the functions to the data set. How do the results compare with your own functions?
confusionMatrix(as.factor(df$scored.class), as.factor(df$class), positive = "1")
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction   0   1
##          0 119  30
##          1   5  27
##                                           
##                Accuracy : 0.8066          
##                  95% CI : (0.7415, 0.8615)
##     No Information Rate : 0.6851          
##     P-Value [Acc > NIR] : 0.0001712       
##                                           
##                   Kappa : 0.4916          
##                                           
##  Mcnemar's Test P-Value : 4.976e-05       
##                                           
##             Sensitivity : 0.4737          
##             Specificity : 0.9597          
##          Pos Pred Value : 0.8438          
##          Neg Pred Value : 0.7987          
##              Prevalence : 0.3149          
##          Detection Rate : 0.1492          
##    Detection Prevalence : 0.1768          
##       Balanced Accuracy : 0.7167          
##                                           
##        'Positive' Class : 1               
## 

The data from the confusion matrix function more or less matches the custom functions that i wrote, confirming their accuracy.

  1. Investigate the pROC package. Use it to generate an ROC curve for the data set. How do the results compare with your own functions?
rocCurve <- roc(df$class, df$scored.class, plot = TRUE, grid = TRUE, print.auc = TRUE)
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases

auc(rocCurve)
## Area under the curve: 0.7167

The data from the roc curve function more or less matches the custom functions that i wrote, confirming their accuracy.