Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Mean Absolute Error in R, when we do modeling always need to measure the accuracy of the model fit. The mean absolute error (MAE) allows us to measure the accuracy of a given model.
The formula for mean absolute error is
MAE = (1/n) * Σ|yi – xi|
where:
Σ symbol Indicate that “sum”
Yi indicates that ith observed value.
Xi indicates that ith predicted value
N indicates the total number of observations
Wilcoxon Signed-Rank Test in R » an Overview »
Mean Absolute Error in R
How to Calculate Mean Absolute Error in R, here we are exploring two possible ways.
Approach 1: Calculate Mean Absolute Error Between Two Vectors
For approach 1 we can make use of the Metrics package. Let’s load the library first.
library(Metrics)
Now we need observed and predicted observations. Let’s create some random values.
observed <- c(13, 15, 15, 15, 14, 22, 25, 25, 23, 20, 22) predicted <- c(12, 13, 13, 14, 15, 24, 24, 26, 22, 26, 24)
Calculate the mean absolute error between observed and predicted values.
mae(observed, predicted)
[1] 1.818182
The mean absolute error (MAE) turns out to be 1.818182.
This MAE value indicates that the average absolute difference between the observed values and the predicted values is 1.818182.
Approach 2: Calculate Mean Absolute Error for a Regression Model
One of the common model fit methods is regression modeling, Let’s see how to calculate MAE for a given regression model.
Let’s load the library
library(Metrics)
We need a data frame for regression model fitting. Let’s create the data frame.
Minimum number of units in an Experimental Design »
df <- data.frame(x1=c(4, 3, 5, 4, 4, 8, 6, 10, 5, 6), x2=c(8, 7, 8, 9, 10, 15, 11, 15, 18, 24), y=c(15, 16, 17, 20, 22, 27, 25, 28, 29, 22)) head(df) x1 x2 y 1 4 8 15 2 3 7 16 3 5 8 17 4 4 9 20 5 4 10 22 6 8 15 27
Fit the regression model
model <- lm(y~x1+x2, data=df) model Call: lm(formula = y ~ x1 + x2, data = df) Coefficients: (Intercept) x1 x2 10.9240 1.2587 0.3403
Now we can calculate MAE value between predicted and observed values
Timeseries analysis in R » Decomposition, & Forecasting »
mae(df$y, predict(model)) [1] 2.591844
The mean absolute error (MAE) is 2.591844.
This indicates that the average absolute difference between the observed values and the predicted values is 2.591844.
Conclusion
Lower the MAE value indicates a better model fit. This will be more useful when we compare two different models.
KNN Algorithm Machine Learning » Classification & Regression »
The post How to Calculate Mean Absolute Error in R appeared first on finnstats.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.