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
df = read.csv("https://raw.githubusercontent.com/BDavidoff/Data_621/main/classification-output-data.csv")
df = df[,c('class', 'scored.class','scored.probability')]
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.
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
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
# 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
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
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
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
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.
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
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
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.
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.