File: mae.R

package info (click to toggle)
r-cran-modelmetrics 1.2.2.2-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 300 kB
  • sloc: cpp: 252; sh: 10; makefile: 2
file content (76 lines) | stat: -rw-r--r-- 1,565 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#' @title Mean absolute error
#' @description Calculates the mean absolute error
#'
#' @param actual A vector of the labels
#' @param predicted A vector of predicted values
#' @param \dots additional parameters to be passed the the s3 methods
#' @param modelObject the model object. Currently supported \code{glm, randomForest, glmerMod, gbm}
#'
#' @export

mae <- function(...){
  UseMethod("mae")
}

#' @rdname mae
#' @export
mae.default <- function(actual, predicted, ...){
  mae_(actual, predicted)
}


#' @rdname mae
#' @export
mae.glm <- function(modelObject, ...){

  family <- family(modelObject)[[1]]
  if(any(family %in% c('binomial', 'poisson'))){
    actual <- modelObject$y
    predicted <- modelObject$fitted.values
  } else {
    stop(paste0("family: ", family, " is not currently supported"))
  }

  mae.default(actual, predicted)
}

#' @rdname mae
#' @export
mae.randomForest <- function(modelObject, ...){

  actual <- as.numeric(modelObject$y) - 1
  predicted <- predict(modelObject, type = 'prob')[,2]

  mae.default(actual, predicted)
}

#' @rdname mae
#' @export
mae.glmerMod <- function(modelObject, ...){

  actual <- modelObject@resp$y
  predicted <- modelObject@resp$mu

  mae.default(actual, predicted)
}

#' @rdname mae
#' @export
mae.gbm <- function(modelObject, ...){

  actual <- modelObject$data$y
  predicted <- modelObject$fit

  mae.default(actual, predicted)
}

#' @rdname mae
#' @export
mae.rpart <- function(modelObject, ...){

  actual <- modelObject$y
  predicted <- predict(modelObject)

  mae.default(actual, predicted)
}