C# Box Cox Example

← All NMath Code Examples

 

using System;

using CenterSpace.NMath.Core;

namespace CenterSpace.NMath.Examples.CSharp
{
  class BoxCoxExample
  {
    static void Main( string[] args )
    {
      // The data to be transformed.
      var data = new DoubleVector( "[.15	 .09	 .18	 .10	 .05	 .12	 .08 .05	 .08	" +
        " .10	 .07	 .02	 .01	 .10 .10	 .10	 .02	 .10	 .01	 .40	 .10 .05	 .03	 .05  " +
        " .15	 .10	 .15	 .09 .08	 .18	 .10	 .20	 .11	 .30	 .02 .20	 .20	 .30	 .30	 .40	 .30	 .05]" );

      // The interval to search for the value of lambda which maximizes the log-likelihood
      // function.
      var lambdaInterval = new Interval( -3, 3, Interval.Type.Closed );
      // We want lambda values less than 0.01 to be considered equal to zero.
      double lambdaEpsilon = .01;

      // Construct a BoxCox for the given data and lambda information.
      var bc = new BoxCox( data, lambdaInterval, lambdaEpsilon );

      Console.WriteLine();

      // Write the optimal lambda and the transformed data using that lambda value.
      Console.WriteLine( "Optimal lambda value in {0} is {1}", bc.LambdaInterval, bc.Lambda );
      Console.WriteLine( "\nTransformed data:" );
      Console.WriteLine( bc.TransformedData.ToString( "G5" ) );

      // Print out the log-likelihood function for the data at the optimal lambda value.
      Console.WriteLine( "\nValue of the log-likelihood function at lambda = {0} is {1}",
        bc.Lambda, BoxCox.LogLikelihood( data, bc.Lambda ) );

      // Transform some other data using a lambda value of 0.27.
      double lambda = 0.27;
      var y = new DoubleVector( 10, new RandGenBeta( 2.2 ) );
      DoubleVector transformedY = BoxCox.Transform( y, lambda );
      Console.WriteLine( "\ny transformed with lambda = {0}:", lambda );
      Console.WriteLine( transformedY.ToString( "G5" ) );

      Console.WriteLine();
      Console.WriteLine( "Press Enter Key" );
      Console.Read();
    }
  }
}

← All NMath Code Examples
Top