Theil’s Inequality Algorithm using C#

TheilsInequality

public class TheilInEqualityAlgorithm
{
private readonly int _holdOutPeriod;
private readonly IEnumerable _actualAndPredictedValues;
public TheilInEqualityAlgorithm(int holdOutPeriod, IEnumerable actualAndPredictedValues)
{
_holdOutPeriod = holdOutPeriod;
_actualAndPredictedValues = actualAndPredictedValues;
}
private double CalculateRootMeanSquareDeviation()
{
double sum = 0;
foreach (ActualAndPredictedValue actualAndPredictedValue in _actualAndPredictedValues)
{
double difference = actualAndPredictedValue.Actual - actualAndPredictedValue.Predicted;
double squareOfdifference = Math.Pow(difference, 2);
sum = sum + squareOfdifference;
}

double rootMeanSquareDeviation = Math.Sqrt(sum / _holdOutPeriod);
return rootMeanSquareDeviation;
}
public Dictionary<string,double> CalculateTheilInEquality()
{
var results=new Dictionary<string, double>();
double calculatedRootMeanSquareDeviation = CalculateRootMeanSquareDeviation();
results.Add("RMSD",calculatedRootMeanSquareDeviation);
double actualSquareSum = 0;
double predictedSquareSum = 0;
foreach (ActualAndPredictedValue actualAndPredictedValue in _actualAndPredictedValues)
{
double actualSquare = Math.Pow(actualAndPredictedValue.Actual, 2);
double predictedSquare = Math.Pow(actualAndPredictedValue.Predicted, 2);
actualSquareSum = actualSquareSum + actualSquare;
predictedSquareSum = predictedSquareSum + predictedSquare;
}
double sqrtOfActualSum = Math.Sqrt(actualSquareSum / _holdOutPeriod);
double sqrtOfPredictedSum = Math.Sqrt(predictedSquareSum / _holdOutPeriod);
double theilInEquality = (calculatedRootMeanSquareDeviation) / (sqrtOfActualSum + sqrtOfPredictedSum);
results.Add("TheilInEquality", theilInEquality);
return results;
}
}
public class ActualAndPredictedValue
{
public double Actual { get; set; }
public double Predicted { get; set; }
}

Pass actual and predicted values for the periods

var actualPredictedCollection = new List
{
new ActualAndPredictedValue
{
Actual =-659505.150000,
Predicted =-900587.246911
}};
var results = new TheilInEqualityAlgorithm(12,actualPredictedCollection).CalculateTheilInEquality();
double theilInEquality=results[“TheilInEquality”];
Enjoy coding…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s