【问题标题】:Using MAE as the error function for a linear model使用 MAE 作为线性模型的误差函数
【发布时间】:2018-04-02 21:39:42
【问题描述】:

我想执行线性回归,但是我不想使用 RMSE 作为我的误差函数,而是使用 MAE(平均绝对误差)。

有没有可以让我这样做的包?

【问题讨论】:

标签: r linear-regression


【解决方案1】:

您可以使用 caretMetrics 包。

library(caret)
data("mtcars")
maeSummary <- function (data,
                        lev = NULL,
                        model = NULL) {

  require(Metrics)
  out <- mae(data$obs, data$pred)  
  names(out) <- "MAE"
  out
}

mControl <- trainControl(summaryFunction = maeSummary)

set.seed(123)
lm_model <- train(mpg ~ wt,
                  data = mtcars, 
                  method = "lm",
                  metric = "MAE",
                  maximize = FALSE,
                  trControl = mControl)
> lm_model$metric
[1] "MAE"

【讨论】:

  • 对不起,这个答案是错误的......仍然在 RMSE 上进行了优化(比较系数以确认 lm_modellm(mpg ~ wt, mtcars)$coefficients
【解决方案2】:

可能迟到了,但这里有一个使用 CVXR 包进行优化的解决方案。

library(CVXR)

# defining variables to be tuned during optimisation
coefficient <- Variable(1)
intercept <- Variable(1)

# defining the objective i.e. minimizing the sum af absolute differences (MAE)
objective <- Minimize(sum(abs(mtcars$disp - (mtcars$hp * coefficient) - intercept)))

# optimisation
problem <- Problem(objective)
result <- solve(problem)

# result
result$status
mae_coefficient <- result$getValue(coefficient)
mae_intercept <- result$getValue(intercept)

lm_coeff_intrc <- lm(formula = disp ~ hp, data = mtcars)$coefficients

library(tidyverse)

ggplot(mtcars, aes(hp, disp)) +
  geom_point() +
  geom_abline(
    slope = lm_coeff_intrc["hp"],
    intercept = lm_coeff_intrc["(Intercept)"],
    color = "red"
  ) +
  geom_abline(
    slope = mae_coefficient,
    intercept = mae_intercept,
    color = "blue"
  )

df <- mtcars %>%
  select(disp, hp) %>%
  rownames_to_column() %>%
  mutate(
    mae = disp - hp * mae_coefficient - mae_intercept,
    lm = disp - hp * lm_coeff_intrc["hp"] - lm_coeff_intrc["(Intercept)"]
  )

df %>%
  select(mae, lm) %>%
  pivot_longer(cols = 1:2) %>%
  group_by(name) %>%
  summarise(
    mae = sum(abs(value))
  )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-27
    • 2017-12-13
    • 1970-01-01
    • 2021-11-13
    • 2014-04-18
    • 2018-10-13
    • 2023-01-30
    • 1970-01-01
    相关资源
    最近更新 更多