calculator of the root-mean-square error, confidence interval and relative error as a percentage in python

Root-Mean-Square Error

To calculate the root-mean-square error (RMSE), first import the math module and numpy module:

main.py
import math
import numpy as np
31 chars
3 lines

Given the actual values y_true and predicted values y_pred as arrays, RMSE can be calculated with the following code:

main.py
def rmse(y_true, y_pred):
    return math.sqrt(np.mean((y_true - y_pred) ** 2))
80 chars
3 lines

Confidence Interval

To calculate the confidence interval, first import the statistics module:

main.py
import statistics
18 chars
2 lines

Given a list of values data, a confidence level of conf_level, and a sample size of n, you can calculate the confidence interval with the following code:

main.py
def confidence_interval(data, conf_level, n):
    mean = statistics.mean(data)
    std = np.std(data, ddof=1)
    crit_value = scipy.stats.t.ppf((1 + conf_level) / 2, n-1)
    return (mean - crit_value * std / math.sqrt(n), mean + crit_value * std / math.sqrt(n))
264 chars
6 lines

Relative Error as a Percentage

To calculate the relative error as a percentage, define a function that takes in the actual value y_true and predicted value y_pred as inputs:

main.py
def relative_error(y_true, y_pred):
    return abs((y_true - y_pred) / y_true) * 100
85 chars
3 lines

gistlibby LogSnag