NUnit.Framework.Assert.AreEqual(double, double, double)

Here are the examples of the csharp api NUnit.Framework.Assert.AreEqual(double, double, double) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

745 Examples 7

19 View Source File : SpecialTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void LogSumTest()
        {
            double a, e;

            a = Math.Exp(Special.LogSum(Math.Log(0.1), Math.Log(0.001)));
            e = 0.101;
            replacedert.AreEqual(a, e, 1e-10);

            a = Math.Exp(Special.LogSum(Math.Log(10), Math.Log(1000)));
            e = 1010;
            replacedert.AreEqual(a, e, 1e-10);

            a = Math.Exp(Special.LogSum(Math.Log(5), Math.Log(42)));
            e = 47;
            replacedert.AreEqual(a, e, 1e-10);

            a = Math.Exp(Special.LogSum(Math.Log(1), Math.Log(1)));
            e = 2;
            replacedert.AreEqual(a, e, 1e-10);

            double direct = Math.Exp(1.6793491276384929E-12) + Math.Exp(0.014072312433917435);
            a = Math.Exp(Special.LogSum(1.6793491276384929E-12, 0.014072312433917435));
            e = 2.0141717935194383;
            replacedert.AreEqual(a, e, 1e-10);

            double diff = Math.Abs(direct - e);
            replacedert.AreEqual(4.4408920985006262E-16, diff);
        }

19 View Source File : ToolsTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void AtanhTest()
        {
            double d = 0.42;
            double expected = 0.447692023527421;
            double actual = Tools.Atanh(d);
            replacedert.AreEqual(expected, actual, 1e-10);
        }

19 View Source File : ToolsTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void AsinhTest()
        {
            double d = 0.42;
            double expected = 0.408540207829808;
            double actual = Tools.Asinh(d);
            replacedert.AreEqual(expected, actual, 1e-10);
        }

19 View Source File : ToolsTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void AcoshTest()
        {
            double x = 3.14;
            double expected = 1.810991348900196;
            double actual = Tools.Acosh(x);
            replacedert.AreEqual(expected, actual, 1e-10);
        }

19 View Source File : ToolsTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void InvSqrtTest()
        {
            float f = 42f;

            float expected = 1f / (float)System.Math.Sqrt(f);
            float actual = Tools.InvSqrt(f);

            replacedert.AreEqual(expected, actual, 0.001);
        }

19 View Source File : IntegralTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void InfiniteGaussKronrodTest()
        {
            for (int i = -10; i < 10; i++)
            {
                Func<double, double> pdf = (x) => Normal.Derivative(x - i);

                Func<double, double> E = (x) => x * pdf(x);
                UFunction UE = (x) => x * pdf(x);

                double expected = Quadpack.Integrate(UE,
                    Double.NegativeInfinity, Double.PositiveInfinity);

                double actual = InfiniteAdaptiveGaussKronrod.Integrate(E,
                    Double.NegativeInfinity, Double.PositiveInfinity);

                replacedert.AreEqual(expected, actual, 1e-3);
                replacedert.AreEqual(i, actual, 1e-3);
            }
        }

19 View Source File : BernoulliFunctionTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void ConstructorTest()
        {
            // Create a Bernoulli function with sigmoid's alpha = 1
            BernoulliFunction function = new BernoulliFunction();

            // Computes the function output (sigmoid function)
            double y = function.Function(x: 0.4); // 0.5986876

            // Draws a sample from a Bernoulli distribution with
            // mean given by the function output y (given as before)
            double z = function.Generate(x: 0.4); // (random, 0 or 1)

            // Here, z can be either 0 or 1. Since it follows a Bernoulli
            // distribution with mean 0.59, it is expected to be 1 about 
            // 0.59 of the time.

            // Now, please note that the above is completely equivalent 
            // to computing the line below (remember, 0.5986876 == y)
            double w = function.Generate2(y: 0.5986876); // (random, 0 or 1)


            // We can also compute the derivative of the sigmoid function
            double d = function.Derivative(x: 0.4); // 0.240260

            // Or compute the derivative given the functions' output y
            double e = function.Derivative2(y: 0.5986876); // 0.240260

            replacedert.AreEqual(0.5986876, y, 1e-7);
            replacedert.AreEqual(0.2402607, d, 1e-7);
            replacedert.AreEqual(0.2402607, e, 1e-7);
        }

19 View Source File : AugmentedLagrangianTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void AugmentedLagrangianSolverConstructorTest1()
        {
            Accord.Math.Tools.SetupGenerator(0);

            // min 100(y-x*x)²+(1-x)²
            //
            // s.t.  x <= 0
            //       y <= 0
            //

            var f = new NonlinearObjectiveFunction(2,

                function: (x) => 100 * Math.Pow(x[1] - x[0] * x[0], 2) + Math.Pow(1 - x[0], 2),

                gradient: (x) => new[]
                {
                    2.0 * (200.0 * x[0]*x[0]*x[0] - 200.0 * x[0] * x[1] + x[0] - 1), // df/dx
                    200 * (x[1] - x[0]*x[0])                                         // df/dy
                }

            );


            var constraints = new List<NonlinearConstraint>();

            constraints.Add(new NonlinearConstraint(f,

                function: (x) => x[0],
                gradient: (x) => new[] { 1.0, 0.0 },

                shouldBe: ConstraintType.LesserThanOrEqualTo, value: 0
            ));

            constraints.Add(new NonlinearConstraint(f,

                function: (x) => x[1],
                gradient: (x) => new[] { 0.0, 1.0 },

                shouldBe: ConstraintType.LesserThanOrEqualTo, value: 0
            ));

            var solver = new AugmentedLagrangian(f, constraints);

            replacedert.IsTrue(solver.Minimize());
            double minValue = solver.Value;

            replacedert.IsFalse(Double.IsNaN(minValue));
            replacedert.AreEqual(1, minValue, 1e-5);
            replacedert.AreEqual(0, solver.Solution[0], 1e-5);
            replacedert.AreEqual(0, solver.Solution[1], 1e-5);
        }

19 View Source File : AugmentedLagrangianTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void AugmentedLagrangianSolverConstructorTest3()
        {
            // min x*y+ y*z
            //
            // s.t.  x^2 - y^2 + z^2 - 2  >= 0
            //       x^2 + y^2 + z^2 - 10 <= 0
            //

            double x = 0, y = 0, z = 0;

            var f = new NonlinearObjectiveFunction(

                function: () => x * y + y * z,

                gradient: () => new[]
                {
                    y,     // df/dx
                    x + z, // df/dy
                    y,     // df/dz
                }

            );


            var constraints = new List<NonlinearConstraint>();

            constraints.Add(new NonlinearConstraint(f,

                function: () => x * x - y * y + z * z,
                gradient: () => new[] { 2 * x, -2 * y, 2 * z },

                shouldBe: ConstraintType.GreaterThanOrEqualTo, value: 2
            ));

            constraints.Add(new NonlinearConstraint(f,

                function: () => x * x + y * y + z * z,
                gradient: () => new[] { 2 * x, 2 * y, 2 * z },

                shouldBe: ConstraintType.LesserThanOrEqualTo, value: 10
            ));

            var solver = new AugmentedLagrangian(f, constraints);

            solver.Solution[0] = 1;
            solver.Solution[1] = 1;
            solver.Solution[2] = 1;

            bool success = solver.Minimize();
            double minValue = solver.Value;
            replacedert.IsTrue(success);

            replacedert.AreEqual(-6.9, minValue, 1e-1);
            replacedert.AreEqual(+1.73, solver.Solution[0], 1e-2);
            replacedert.AreEqual(-2.00, solver.Solution[1], 1e-2);
            replacedert.AreEqual(+1.73, solver.Solution[2], 1e-2);

            replacedert.IsFalse(Double.IsNaN(minValue));
            replacedert.IsFalse(Double.IsNaN(solver.Solution[0]));
            replacedert.IsFalse(Double.IsNaN(solver.Solution[1]));
            replacedert.IsFalse(Double.IsNaN(solver.Solution[2]));

        }

19 View Source File : AugmentedLagrangianTest.cs
License : MIT License
Project Creator : PacktPublishing

private static void test2(IGradientOptimizationMethod inner)
        {
            Accord.Math.Random.Generator.Seed = 0;

            // maximize 2x + 3y, s.t. 2x² + 2y² <= 50
            //
            // http://www.wolframalpha.com/input/?i=max+2x+%2B+3y%2C+s.t.+2x%C2%B2+%2B+2y%C2%B2+%3C%3D+50

            // Max x' * c
            //  x

            // s.t. x' * A * x <= k
            //      x' * i     = 1
            // lower_bound < x < upper_bound

            double[] c = { 2, 3 };
            double[,] A = { { 2, 0 }, { 0, 2 } };
            double k = 50;

            // Create the objective function
            var objective = new NonlinearObjectiveFunction(2,
                function: (x) => x.InnerProduct(c),
                gradient: (x) => c
            );

            // Test objective
            for (int i = 0; i < 10; i++)
            {
                for (int j = 0; j < 10; j++)
                {
                    double expected = i * 2 + j * 3;
                    double actual = objective.Function(new double[] { i, j });
                    replacedert.AreEqual(expected, actual);
                }
            }


            // Create the optimization constraints
            var constraints = new List<NonlinearConstraint>();

            constraints.Add(new QuadraticConstraint(objective,
                quadraticTerms: A,
                shouldBe: ConstraintType.LesserThanOrEqualTo, value: k
            ));


            // Test first constraint
            for (int i = 0; i < 10; i++)
            {
                for (int j = 0; j < 10; j++)
                {
                    var input = new double[] { i, j };

                    double expected = i * (2 * i + 0 * j) + j * (0 * i + 2 * j);
                    double actual = constraints[0].Function(input);
                    replacedert.AreEqual(expected, actual);
                }
            }


            // Create the solver algorithm
            AugmentedLagrangian solver =
                new AugmentedLagrangian(inner, objective, constraints);

            replacedert.AreEqual(inner, solver.Optimizer);

            replacedert.IsTrue(solver.Maximize());
            double maxValue = solver.Value;

            replacedert.AreEqual(18.02, maxValue, 1e-2);
            replacedert.AreEqual(2.77, solver.Solution[0], 1e-2);
            replacedert.AreEqual(4.16, solver.Solution[1], 1e-2);
        }

19 View Source File : AugmentedLagrangianTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void constructorTest5()
        {
            // AugmentedLagrangian with NonlinearConstraints
            // have a Gradient NullReferenceException issue 
            // https://github.com/accord-net/framework/issues/177

            // Easy three dimensional minimization in ellipsoid.
            var function = new NonlinearObjectiveFunction(3,
                function: x => x[0] * x[1] * x[2],
                gradient: x => new[] { x[1] * x[2], x[0] * x[2], x[0] * x[1] });

            NonlinearConstraint[] constraints =
            {
                new NonlinearConstraint(function,
                    constraint: x =>  (1.0 - x[0] * x[0] - 2.0 * x[1] * x[1] - 3.0 * x[2] * x[2]) >= 0,
                    gradient: x =>  new[] { -2.0 * x[0],  -4.0 * x[1], -6.0 * x[2] }),
                new NonlinearConstraint(function,
                    constraint: x =>  x[0] >= 0,
                    gradient: x =>  new[] { 1.0, 0, 0 }),
                new NonlinearConstraint(function,
                    constraint: x =>  x[1] >= 0,
                    gradient: x =>  new[] { 0, 1.0, 0 }),
                new NonlinearConstraint(function,
                    constraint: x =>  -x[2] >= 0,
                    gradient: x =>  new[] { 0, 0, -1.0 }),
            };

            for (int i = 0; i < constraints.Length; i++)
            {
                replacedert.AreEqual(ConstraintType.GreaterThanOrEqualTo, constraints[i].ShouldBe);
                replacedert.AreEqual(0, constraints[i].Value);
            }

            var inner = new BroydenFletcherGoldfarbShanno(3);
            inner.LineSearch = LineSearch.BacktrackingArmijo;
            inner.Corrections = 10;

            var solver = new AugmentedLagrangian(inner, function, constraints);

            replacedert.AreEqual(inner, solver.Optimizer);

            replacedert.IsTrue(solver.Minimize());
            double minimum = solver.Value;
            double[] solution = solver.Solution;

            double[] expected =
            {
                1.0 / Math.Sqrt(3.0), 1.0 / Math.Sqrt(6.0), -1.0 / 3.0
            };


            for (int i = 0; i < expected.Length; i++)
                replacedert.AreEqual(expected[i], solver.Solution[i], 1e-3);
            replacedert.AreEqual(-0.078567420132031968, minimum, 1e-4);

            double expectedMinimum = function.Function(solver.Solution);
            replacedert.AreEqual(expectedMinimum, minimum);
        }

19 View Source File : BrentSearchTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void FindRootTest()
        {
            //  Example from http://en.wikipedia.org/wiki/Brent%27s_method

            Func<double, double> f = x => (x + 3) * Math.Pow((x - 1), 2);
            double a = -4;
            double b = 4 / 3.0;

            double expected = -3;
            double actual = BrentSearch.FindRoot(f, a, b);

            replacedert.AreEqual(expected, actual, 1e-6);
            replacedert.IsFalse(Double.IsNaN(actual));

            var search = new BrentSearch(f, a, b);
            bool isSuccess = search.FindRoot();

            replacedert.True(isSuccess);
            replacedert.AreEqual(BrentSearchStatus.Success, search.Status);
            replacedert.AreEqual(expected, search.Solution, 1e-6);
            replacedert.That(Math.Abs(search.Value), Is.LessThan(1e-5));
        }

19 View Source File : BrentSearchTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void FindTest()
        {
            //  Example from http://en.wikipedia.org/wiki/Brent%27s_method
            double value = 10;

            Func<double, double> f = x => (x + 3) * Math.Pow((x - 1), 2) + value;
            double a = -4;
            double b = 4 / 3.0;

            double expected = -3;
            double actual = BrentSearch.Find(f, value, a, b);

            replacedert.AreEqual(expected, actual, 1e-6);
            replacedert.AreEqual(value, f(actual), 1e-5);

            var search = new BrentSearch(f, a, b);
            bool isSuccess = search.Find(value);

            replacedert.True(isSuccess);
            replacedert.AreEqual(BrentSearchStatus.Success, search.Status);
            replacedert.AreEqual(expected, search.Solution, 1e-6);
            replacedert.AreEqual(value, search.Value, 1e-5);
        }

19 View Source File : BrentSearchTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void MaximizeTest()
        {
            Func<double, double> f = x => -2 * x * x - 3 * x + 5;

            double expected = -3 / 4d;
            double actual = BrentSearch.Maximize(f, -200, +200);

            replacedert.AreEqual(expected, actual, 1e-10);


            var search = new BrentSearch(f, -200, 200);
            bool isSuccess = search.Maximize();

            replacedert.True(isSuccess);
            replacedert.AreEqual(BrentSearchStatus.Success, search.Status);
            replacedert.AreEqual(expected, search.Solution, 1e-10);
            replacedert.AreEqual(f(expected), search.Value, double.Epsilon);
        }

19 View Source File : QuadraticObjectiveFunctionTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void QuadraticConstructorTest()
        {
            double[,] quadraticTerms =
            {
                {  1, 2, 3 },
                {  2, 5, 6 },
                {  3, 6, 9 },
            };

            double[] linearTerms = { 1, 2, 3 };

            var target = new QuadraticObjectiveFunction(quadraticTerms, linearTerms);

            var function = target.Function;
            var gradient = target.Gradient;

            FiniteDifferences fd = new FiniteDifferences(3, function);

            double[][] x =
            {
                new double[] { 1, 2, 3 },
                new double[] { 3, 1, 4 },
                new double[] { -6 , 5, 9 },
                new double[] { 31, 25, 246 },
                new double[] { -0.102, 0, 10 },
            };


            { // Function test
                for (int i = 0; i < x.Length; i++)
                {
                    double expected = 0.5 *
                        (x[i].Multiply(quadraticTerms)).InnerProduct(x[i])
                        + linearTerms.InnerProduct(x[i]);

                    double actual = function(x[i]);

                    replacedert.AreEqual(expected, actual, 1e-8);
                }
            }

            { // Gradient test
                for (int i = 0; i < x.Length; i++)
                {
                    double[] expected = fd.Compute(x[i]);
                    double[] actual = gradient(x[i]);

                    for (int j = 0; j < actual.Length; j++)
                        replacedert.AreEqual(expected[j], actual[j], 1e-8);
                }
            }
        }

19 View Source File : QuadraticObjectiveFunctionTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void OperatorScalingTest()
        {
            double x = 0;
            double y = 0;
            double z = 0;
            double scalar = 5;

            Func<double> expected1 = () => 2 * y * x - x * y + y * z;
            var actual1 = new QuadraticObjectiveFunction(() => 2 * y * x - x * y + y * z);
            var actual = actual1 * scalar;

            for (int i = 0; i < 10; i++)
                for (int j = 0; j < 10; j++)
                    for (int k = 0; k < 10; k++)
                    {
                        x = (i - 5) / 10.0;
                        y = (j - 5) / 10.0;
                        z = (k - 5) / 10.0;

                        double a = actual.Function(new[] { x, y, z });
                        double e = scalar * expected1();

                        replacedert.AreEqual(e, a, 1e-10);
                        replacedert.IsFalse(double.IsNaN(a));
                        replacedert.IsFalse(double.IsNaN(e));
                    }
        }

19 View Source File : HilbertTransformTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void FHTTest()
        {
            Complex[] original = { (Complex)1, (Complex)2, (Complex)3, (Complex)4 };

            Complex[] actual = (Complex[])original.Clone();
            HilbertTransform.FHT(actual, FourierTransform.Direction.Forward);

            replacedert.AreEqual(actual[0].Real, 1);
            replacedert.AreEqual(actual[1].Real, 2);
            replacedert.AreEqual(actual[2].Real, 3);
            replacedert.AreEqual(actual[3].Real, 4);

            replacedert.AreEqual(actual[0].Imaginary, +1, 0.000000001);
            replacedert.AreEqual(actual[1].Imaginary, -1, 0.000000001);
            replacedert.AreEqual(actual[2].Imaginary, -1, 0.000000001);
            replacedert.AreEqual(actual[3].Imaginary, +1, 0.000000001);

            HilbertTransform.FHT(actual, FourierTransform.Direction.Backward);

            replacedert.AreEqual(actual[0], original[0]);
            replacedert.AreEqual(actual[1], original[1]);
            replacedert.AreEqual(actual[2], original[2]);
            replacedert.AreEqual(actual[3], original[3]);
        }

19 View Source File : HilbertTransformTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void FHTTest2()
        {
            double[] original = { -1.0, -0.8, -0.2, -0.1, 0.1, 0.2, 0.8, 1.0  };

            double[] actual = (double[])original.Clone();

            HilbertTransform.FHT(actual, FourierTransform.Direction.Forward);

            HilbertTransform.FHT(actual, FourierTransform.Direction.Backward);

            replacedert.AreEqual(actual[0], original[0], 0.08);
            replacedert.AreEqual(actual[1], original[1], 0.08);
            replacedert.AreEqual(actual[2], original[2], 0.08);
            replacedert.AreEqual(actual[3], original[3], 0.08);
        }

19 View Source File : LinearDiscriminantAnalysisTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void ProjectionTest()
        {
            var lda = new LinearDiscriminantreplacedysis(inputs, output);

            // Compute the replacedysis
            lda.Compute();

            // Project the input data into discriminant space
            double[,] projection = lda.Transform(inputs);

            double tol = 1e-15;
            replacedert.AreEqual(projection[0, 0], 4.4273255813953485, tol);
            replacedert.AreEqual(projection[0, 1], 1.9629629629629628, tol);
            replacedert.AreEqual(projection[1, 0], 3.7093023255813953, tol);
            replacedert.AreEqual(projection[1, 1], -2.5185185185185186, tol);
            replacedert.AreEqual(projection[2, 0], 3.2819767441860463, tol);
            replacedert.AreEqual(projection[2, 1], -1.5185185185185186, tol);
            replacedert.AreEqual(projection[3, 0], 5.5639534883720927, tol);
            replacedert.AreEqual(projection[3, 1], -3.7777777777777777, tol);
            replacedert.AreEqual(projection[4, 0], 5.7093023255813957, tol);
            replacedert.AreEqual(projection[4, 1], -1.0370370370370372, tol);
            replacedert.AreEqual(projection[5, 0], 13.273255813953488, tol);
            replacedert.AreEqual(projection[5, 1], -3.3333333333333339, tol);
            replacedert.AreEqual(projection[6, 0], 9.4186046511627914, tol);
            replacedert.AreEqual(projection[6, 1], -3.5555555555555554, tol);
            replacedert.AreEqual(projection[7, 0], 11.136627906976745, tol);
            replacedert.AreEqual(projection[7, 1], 1.6666666666666661, tol);
            replacedert.AreEqual(projection[8, 0], 10.991279069767442, tol);
            replacedert.AreEqual(projection[8, 1], -1.0740740740740744, tol);
            replacedert.AreEqual(projection[9, 0], 13.418604651162791, tol);
            replacedert.AreEqual(projection[9, 1], -0.59259259259259345, tol);

            // replacedert the result equals the transformation of the input
            double[,] result = lda.Result;
            replacedert.IsTrue(Matrix.IsEqual(result, projection));
            replacedert.IsFalse(Matrix.HasNaN(projection));
        }

19 View Source File : LogisticRegressionAnalysisTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void FromSummaryTest1()
        {
            // Suppose we have a (ficreplacedious) data set about patients who 
            // underwent cardiac surgery. The first column gives the number
            // of arterial bypreplacedes performed during the surgery. The second
            // column gives the number of patients whose surgery went well,
            // while the third column gives the number of patients who had
            // at least one complication during the surgery.
            // 
            int[,] data =
            {
                // # of stents       success     complications
                {       1,             140,           45       },
                {       2,             130,           60       },
                {       3,             150,           31       },
                {       4,              96,           65       }
            };


            double[][] inputs = data.GetColumn(0).ToDouble().ToJagged();

            int[] positive = data.GetColumn(1);
            int[] negative = data.GetColumn(2);

            // Create a new Logistic Regression replacedysis from the summary data
            var regression = LogisticRegressionreplacedysis.FromSummary(inputs, positive, negative);

            regression.Compute(); // compute the replacedysis.

            // Now we can show a summary of the replacedysis
            // Accord.Controls.DataGridBox.Show(regression.Coefficients);


            // We can also investigate all parameters individually. For
            // example the coefficients values will be available at the
            // vector

            double[] coef = regression.CoefficientValues;

            // The first value refers to the model's intercept term. We
            // can also retrieve the odds ratios and standard errors:

            double[] odds = regression.OddsRatios;
            double[] stde = regression.StandardErrors;


            // Finally, we can use it to estimate risk for a new patient
            double y = regression.Regression.Compute(new double[] { 4 });

            replacedert.AreEqual(3.7586367581050162, odds[0], 1e-8);
            replacedert.AreEqual(0.85772731075090014, odds[1], 1e-8);

            replacedert.AreEqual(0.20884336554629004, stde[0], 1e-8);
            replacedert.AreEqual(0.075837785246620285, stde[1], 1e-8);

            replacedert.AreEqual(0.67044096045332713, y, 1e-8);

            LogisticRegressionreplacedysis expected;


            {
                int[] qtr = data.GetColumn(0);

                var expanded = Accord.Statistics.Tools.Expand(qtr, positive, negative);

                double[][] inp = expanded.GetColumn(0).ToDouble().ToJagged();
                double[] outputs = expanded.GetColumn(1).ToDouble();

                expected = new LogisticRegressionreplacedysis(inp, outputs);

                expected.Compute();

                double slope = expected.Coefficients[1].Value; // should return -0.153
                double inter = expected.Coefficients[0].Value;
                double value = expected.ChiSquare.PValue;      // should return 0.042
                replacedert.AreEqual(-0.15346904821339602, slope, 1e-8);
                replacedert.AreEqual(1.324056323049271, inter, 1e-8);
                replacedert.AreEqual(0.042491262992507946, value, 1e-8);
            }



            var actual = regression;
            replacedert.AreEqual(expected.Coefficients[0].Value, actual.Coefficients[0].Value, 1e-8);
            replacedert.AreEqual(expected.Coefficients[1].Value, actual.Coefficients[1].Value, 1e-8);

            replacedert.AreEqual(expected.ChiSquare.PValue, actual.ChiSquare.PValue, 1e-8);
            replacedert.AreEqual(expected.WaldTests[0].PValue, actual.WaldTests[0].PValue, 1e-8);
            replacedert.AreEqual(expected.WaldTests[1].PValue, actual.WaldTests[1].PValue, 1e-8);

            replacedert.AreEqual(expected.Confidences[0].Max, actual.Confidences[0].Max, 1e-6);
            replacedert.AreEqual(expected.Confidences[0].Min, actual.Confidences[0].Min, 1e-6);
            replacedert.AreEqual(expected.Confidences[1].Max, actual.Confidences[1].Max, 1e-6);
            replacedert.AreEqual(expected.Confidences[1].Min, actual.Confidences[1].Min, 1e-6);
        }

19 View Source File : LogisticRegressionAnalysisTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void FromSummary_new_method()
        {
            #region doc_learn_summary
            // Suppose we have a (ficreplacedious) data set about patients who 
            // underwent cardiac surgery. The first column gives the number
            // of arterial bypreplacedes performed during the surgery. The second
            // column gives the number of patients whose surgery went well,
            // while the third column gives the number of patients who had
            // at least one complication during the surgery.
            // 
            int[,] data =
            {
                // # of stents       success     complications
                {       1,             140,           45       },
                {       2,             130,           60       },
                {       3,             150,           31       },
                {       4,              96,           65       }
            };

            // Get input variable and number of positives and negatives
            double[][] inputs = data.GetColumn(0).ToDouble().ToJagged();
            int[] positive = data.GetColumn(1);
            int[] negative = data.GetColumn(2);

            // Create a new Logistic Regression replacedysis from the summary data
            var lra = new LogisticRegressionreplacedysis();

            // compute the replacedysis
            LogisticRegression regression = lra.Learn(inputs, positive, negative);

            // Now we can show a summary of the replacedysis
            // Accord.Controls.DataGridBox.Show(regression.Coefficients);


            // We can also investigate all parameters individually. For
            // example the coefficients values will be available at the
            // vector

            double[] coef = lra.CoefficientValues;

            // The first value refers to the model's intercept term. We
            // can also retrieve the odds ratios and standard errors:

            double[] odds = lra.OddsRatios;
            double[] stde = lra.StandardErrors;


            // Finally, we can use it to estimate risk for a new patient
            double y = lra.Regression.Probability(new double[] { 4 }); // 67.0
            #endregion


            replacedert.AreEqual(3.7586367581050162, odds[0], 1e-8);
            replacedert.AreEqual(0.85772731075090014, odds[1], 1e-8);

            replacedert.AreEqual(0.20884336554629004, stde[0], 1e-6);
            replacedert.AreEqual(0.075837785246620285, stde[1], 1e-6);

            replacedert.AreEqual(0.67044096045332713, y, 1e-8);

            LogisticRegressionreplacedysis expected;


            {
                int[] qtr = data.GetColumn(0);

                var expanded = Accord.Statistics.Tools.Expand(qtr, positive, negative);

                double[][] inp = expanded.GetColumn(0).ToDouble().ToJagged();
                double[] outputs = expanded.GetColumn(1).ToDouble();

                expected = new LogisticRegressionreplacedysis();

                expected.Learn(inp, outputs);

                double slope = expected.Coefficients[1].Value; // should return -0.153
                double inter = expected.Coefficients[0].Value;
                double value = expected.ChiSquare.PValue;      // should return 0.042
                replacedert.AreEqual(-0.15346904821339602, slope, 1e-8);
                replacedert.AreEqual(1.324056323049271, inter, 1e-8);
                replacedert.AreEqual(0.042491262992507946, value, 1e-8);
            }



            var actual = lra;
            replacedert.AreEqual(expected.Coefficients[0].Value, actual.Coefficients[0].Value, 1e-8);
            replacedert.AreEqual(expected.Coefficients[1].Value, actual.Coefficients[1].Value, 1e-8);

            replacedert.AreEqual(expected.ChiSquare.PValue, actual.ChiSquare.PValue, 1e-8);
            replacedert.AreEqual(expected.WaldTests[0].PValue, actual.WaldTests[0].PValue, 1e-8);
            replacedert.AreEqual(expected.WaldTests[1].PValue, actual.WaldTests[1].PValue, 1e-8);

            replacedert.AreEqual(expected.Confidences[0].Max, actual.Confidences[0].Max, 1e-6);
            replacedert.AreEqual(expected.Confidences[0].Min, actual.Confidences[0].Min, 1e-6);
            replacedert.AreEqual(expected.Confidences[1].Max, actual.Confidences[1].Max, 1e-6);
            replacedert.AreEqual(expected.Confidences[1].Min, actual.Confidences[1].Min, 1e-6);
        }

19 View Source File : MultinomialLogisticRegressionAnalysisTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void learn_test()
        {
            // http://www.ats.ucla.edu/stat/stata/dae/mlogit.htm
            #region doc_learn_1
            // This example downloads an example dataset from the web and learns a multinomial logistic 
            // regression on it. However, please keep in mind that the Multinomial Logistic Regression 
            // can also work without many of the elements that will be shown below, like the codebook, 
            // DataTables, and a CsvReader. 

            // Let's download an example dataset from the web to learn a multinomial logistic regression:
            CsvReader reader = CsvReader.FromUrl("https://raw.githubusercontent.com/rlowrance/re/master/hsbdemo.csv", hasHeaders: true);

            // Let's read the CSV into a DataTable. As mentioned above, this step
            // can help, but is not necessarily required for learning a the model:
            DataTable table = reader.ToTable();

            // We will learn a MLR regression between the following input and output fields of this table:
            string[] inputNames = new[] { "write", "ses" };
            string[] outputNames = new[] { "prog" };

            // Now let's create a codification codebook to convert the string fields in the data 
            // into integer symbols. This is required because the MLR model can only learn from 
            // numeric data, so strings have to be transformed first. We can force a particular
            // interpretation for those columns if needed, as shown in the initializer below:
            var codification = new Codification()
            {
                { "write", CodificationVariable.Continuous },
                { "ses", CodificationVariable.CategoricalWithBaseline, new[] { "low", "middle", "high" } },
                { "prog", CodificationVariable.Categorical, new[] { "academic", "general" } },
            };

            // Learn the codification
            codification.Learn(table);

            // Now, transform symbols into a vector representation, growing the number of inputs:
            double[][] x = codification.Transform(table, inputNames, out inputNames).ToDouble();
            double[][] y = codification.Transform(table, outputNames, out outputNames).ToDouble();

            // Create a new Multinomial Logistic Regression replacedysis:
            var replacedysis = new MultinomialLogisticRegressionreplacedysis()
            {
                InputNames = inputNames,
                OutputNames = outputNames,
            };

            // Learn the regression from the input and output pairs:
            MultinomialLogisticRegression regression = replacedysis.Learn(x, y);

            // Let's retrieve some information about what we just learned:
            int coefficients = replacedysis.Coefficients.Count; // should be 9
            int numberOfInputs = replacedysis.NumberOfInputs;   // should be 3
            int numberOfOutputs = replacedysis.NumberOfOutputs; // should be 3

            inputNames = replacedysis.InputNames; // should be "write", "ses: middle", "ses: high"
            outputNames = replacedysis.OutputNames; // should be "prog: academic", "prog: general", "prog: vocation"

            // The regression is best visualized when it is data-bound to a 
            // Windows.Forms DataGridView or WPF DataGrid. You can get the
            // values for all different coefficients and discrete values:

            // DataGridBox.Show(regression.Coefficients); // uncomment this line

            // You can get the matrix of coefficients:
            double[][] coef = replacedysis.CoefficientValues;

            // Should be equal to:
            double[][] expectedCoef = new double[][]
            {
                new double[] { 2.85217775752471, -0.0579282723520426, -0.533293368378012, -1.16283850605289 },
                new double[] { 5.21813357698422, -0.113601186660817, 0.291387041358367, -0.9826369387481 }
            };

            // And their replacedociated standard errors:
            double[][] stdErr = replacedysis.StandardErrors;

            // Should be equal to:
            double[][] expectedErr = new double[][]
            {
                new double[] { -2.02458003380033, -0.339533576505471, -1.164084923948, -0.520961533343425, 0.0556314901718 },
                new double[] { -3.73971589217449, -1.47672790071382, -1.76795568348094, -0.495032307980058, 0.113563519656386 }
            };

            // We can also get statistics and hypothesis tests:
            WaldTest[][] wald = replacedysis.WaldTests;        // should all have p < 0.05
            ChiSquareTest chiSquare = replacedysis.ChiSquare;  // should be p=1.06300120956871E-08
            double logLikelihood = replacedysis.LogLikelihood; // should be -179.98173272217591

            // You can use the regression to predict the values:
            int[] pred = regression.Transform(x);

            // And get the accuracy of the prediction if needed:
            var cm = GeneralConfusionMatrix.Estimate(regression, x, y.ArgMax(dimension: 1));

            double acc = cm.Accuracy; // should be 0.61
            double kappa = cm.Kappa;  // should be 0.2993487536492252
            #endregion


            replacedert.AreEqual(9, coefficients);
            replacedert.AreEqual(3, numberOfInputs);
            replacedert.AreEqual(3, numberOfOutputs);

            replacedert.AreEqual(new[] { "write", "ses: middle", "ses: high" }, inputNames);
            replacedert.AreEqual(new[] { "prog: academic", "prog: general", "prog: vocation" }, outputNames);

            replacedert.AreEqual(0.61, acc, 1e-10);
            replacedert.AreEqual(0.2993487536492252, kappa, 1e-10);
            replacedert.AreEqual(1.06300120956871E-08, chiSquare.PValue, 1e-8);
            replacedert.AreEqual(-179.98172637136295, logLikelihood, 1e-8);

            testmlr(replacedysis);
        }

19 View Source File : MultipleLinearRegressionAnalysisTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void ComputeTest()
        {
            // Example 5.1 from 
            // http://www.weibull.com/DOEWeb/estimating_regression_models_using_least_squares.htm

            double[][] inputs =
            {
                new double[] { 41.9, 29.1 }, // 1 
                new double[] { 43.4, 29.3 }, // 2
                new double[] { 43.9, 29.5 }, // 3
                new double[] { 44.5, 29.7 }, // 4
                new double[] { 47.3, 29.9 }, // 5
                new double[] { 47.5, 30.3 }, // 6
                new double[] { 47.9, 30.5 }, // 7
                new double[] { 50.2, 30.7 }, // 8
                new double[] { 52.8, 30.8 }, // 9
                new double[] { 53.2, 30.9 }, // 10
                new double[] { 56.7, 31.5 }, // 11
                new double[] { 57.0, 31.7 }, // 12
                new double[] { 63.5, 31.9 }, // 13
                new double[] { 65.3, 32.0 }, // 14
                new double[] { 71.1, 32.1 }, // 15
                new double[] { 77.0, 32.5 }, // 16
                new double[] { 77.8, 32.9 }, // 17
            };

            double[] outputs =
            {
                251.3,
                251.3,
                248.3,
                267.5,
                273.0,
                276.5,
                270.3,
                274.9,
                285.0,
                290.0,
                297.0,
                302.5,
                304.5,
                309.3,
                321.7,
                330.7,
                349.0,
            };

            var target = new MultipleLinearRegressionreplacedysis(inputs, outputs, intercept: true);

            target.Compute();

            replacedert.AreEqual(0.968022, target.RSquared, 1e-5);
            replacedert.AreEqual(0.963454, target.RSquareAdjusted, 1e-5);

            replacedert.AreEqual(2, target.Table[0].DegreesOfFreedom);
            replacedert.AreEqual(14, target.Table[1].DegreesOfFreedom);
            replacedert.AreEqual(16, target.Table[2].DegreesOfFreedom);

            replacedert.AreEqual(12816.345909673832, target.Table[0].SumOfSquares, 1e-10);
            replacedert.AreEqual(423.37409032616614, target.Table[1].SumOfSquares, 1e-10);
            replacedert.AreEqual(13239.719999999998, target.Table[2].SumOfSquares, 1e-10);

            replacedert.IsFalse(Double.IsNaN(target.Table[0].SumOfSquares));
            replacedert.IsFalse(Double.IsNaN(target.Table[1].SumOfSquares));
            replacedert.IsFalse(Double.IsNaN(target.Table[2].SumOfSquares));

            replacedert.AreEqual(6408.1729548369158, target.Table[0].MeanSquares, 1e-10);
            replacedert.AreEqual(30.241006451869008, target.Table[1].MeanSquares, 1e-10);

            replacedert.IsFalse(Double.IsNaN(target.Table[0].MeanSquares));
            replacedert.IsFalse(Double.IsNaN(target.Table[1].MeanSquares));

            replacedert.AreEqual(211.90342871147618, target.Table[0].Statistic.Value, 1e-10);
            replacedert.AreEqual(0.000000000034191538489380946, target.Table[0].Significance.PValue, 1e-16);
            replacedert.IsFalse(Double.IsNaN(target.Table[0].Significance.PValue));

            replacedert.AreEqual(1.2387232694931045, target.Coefficients[0].Value, 1e-10);
            replacedert.AreEqual(12.082353323342893, target.Coefficients[1].Value, 1e-10);
            replacedert.AreEqual(-153.51169396147372, target.Coefficients[2].Value, 1e-10);

            replacedert.IsFalse(Double.IsNaN(target.Coefficients[0].Value));
            replacedert.IsFalse(Double.IsNaN(target.Coefficients[1].Value));
            replacedert.IsFalse(Double.IsNaN(target.Coefficients[2].Value));

            replacedert.IsFalse(target.Coefficients[0].IsIntercept);
            replacedert.IsFalse(target.Coefficients[1].IsIntercept);
            replacedert.IsTrue(target.Coefficients[2].IsIntercept);

            replacedert.AreEqual(0.394590262021004, target.Coefficients[0].StandardError, 1e-10);
            replacedert.AreEqual(3.9322914100115307, target.Coefficients[1].StandardError, 1e-10);

            replacedert.IsFalse(Double.IsNaN(target.Coefficients[0].StandardError));
            replacedert.IsFalse(Double.IsNaN(target.Coefficients[1].StandardError));

            replacedert.AreEqual(3.1392646720388844, target.Coefficients[0].TTest.Statistic, 1e-10);
            replacedert.AreEqual(3.0725986615797285, target.Coefficients[1].TTest.Statistic, 1e-10);

            replacedert.IsFalse(Double.IsNaN(target.Coefficients[0].TTest.Statistic));
            replacedert.IsFalse(Double.IsNaN(target.Coefficients[1].TTest.Statistic));

            DoubleRange range;

            range = target.Coefficients[0].TTest.GetConfidenceInterval(0.9);
            replacedert.AreEqual(0.54372744151743968, range.Min, 1e-10);
            replacedert.AreEqual(1.9337190974687695, range.Max, 1e-10);

            range = target.Coefficients[1].TTest.GetConfidenceInterval(0.9);
            replacedert.AreEqual(5.1563686060690417, range.Min, 1e-10);
            replacedert.AreEqual(19.008338040616746, range.Max, 1e-10);


            MultipleLinearRegression mlr = new MultipleLinearRegression(2, true);
            mlr.Regress(inputs, outputs);
            double r2 = mlr.CoefficientOfDetermination(inputs, outputs, false);
            double r2a = mlr.CoefficientOfDetermination(inputs, outputs, true);

            replacedert.AreEqual(r2, target.RSquared);
            replacedert.AreEqual(r2a, target.RSquareAdjusted);
        }

19 View Source File : MultipleLinearRegressionAnalysisTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void ComputeTest2()
        {
            // Consider the following data. An experimenter would
            // like to infer a relationship between two variables
            // A and B and a corresponding outcome variable R.

            double[][] example =
            {
                //                A    B      R
                new double[] {  6.41, 10.11, 26.1 },
                new double[] {  6.61, 22.61, 33.8 },
                new double[] {  8.45, 11.11, 52.7 },
                new double[] {  1.22, 18.11, 16.2 },
                new double[] {  7.42, 12.81, 87.3 },
                new double[] {  4.42, 10.21, 12.5 },
                new double[] {  8.61, 11.94, 77.5 },
                new double[] {  1.73, 13.13, 12.1 },
                new double[] {  7.47, 17.11, 86.5 },
                new double[] {  6.11, 15.13, 62.8 },
                new double[] {  1.42, 16.11, 17.5 },
            };

            // For this, we first extract the input and output
            // pairs. The first two columns have values for the
            // input variables, and the last for the output:

            double[][] inputs = example.GetColumns(new[] { 0, 1 });
            double[] output = example.GetColumn(2);

            // Next, we can create a new multiple linear regression for the variables
            var regression = new MultipleLinearRegressionreplacedysis(inputs, output, intercept: true);

            regression.Compute(); // compute the replacedysis

            // Now we can show a summary of replacedysis
            // Accord.Controls.DataGridBox.Show(regression.Coefficients);

            // We can also show a summary ANOVA
            // Accord.Controls.DataGridBox.Show(regression.Table);


            // And also extract other useful information, such
            // as the linear coefficients' values and std errors:
            double[] coef = regression.CoefficientValues;
            double[] stde = regression.StandardErrors;

            // Coefficients of performance, such as r²
            double rsquared = regression.RSquared;

            // Hypothesis tests for the whole model
            ZTest ztest = regression.ZTest;
            FTest ftest = regression.FTest;

            // and for individual coefficients
            TTest ttest0 = regression.Coefficients[0].TTest;
            TTest ttest1 = regression.Coefficients[1].TTest;

            // and also extract confidence intervals
            DoubleRange ci = regression.Coefficients[0].Confidence;

            replacedert.AreEqual(3, coef.Length);
            replacedert.AreEqual(8.7405051051757816, coef[0]);
            replacedert.AreEqual(1.1198079243314365, coef[1], 1e-10);
            replacedert.AreEqual(-19.604474518407862, coef[2], 1e-10);
            replacedert.IsFalse(coef.HasNaN());

            replacedert.AreEqual(2.375916659234715, stde[0], 1e-10);
            replacedert.AreEqual(1.7268508921418664, stde[1], 1e-10);
            replacedert.AreEqual(30.989640986710953, stde[2], 1e-10);
            replacedert.IsFalse(coef.HasNaN());

            replacedert.AreEqual(0.62879941171298936, rsquared, 1e-10);

            replacedert.AreEqual(0.99999999999999822, ztest.PValue, 1e-10);
            replacedert.AreEqual(0.018986050133298293, ftest.PValue, 1e-10);

            replacedert.AreEqual(0.0062299844256985537, ttest0.PValue, 1e-10);
            replacedert.AreEqual(0.53484850318449118, ttest1.PValue, 1e-14);
            replacedert.IsFalse(Double.IsNaN(ttest1.PValue));

            replacedert.AreEqual(3.2616314640800566, ci.Min, 1e-10);
            replacedert.AreEqual(14.219378746271506, ci.Max, 1e-10);
        }

19 View Source File : MultipleLinearRegressionAnalysisTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void learn_Test()
        {
            #region doc_learn_part1
            // Consider the following data. An experimenter would
            // like to infer a relationship between two variables
            // A and B and a corresponding outcome variable R.

            double[][] example =
            {
                //                A    B      R
                new double[] {  6.41, 10.11, 26.1 },
                new double[] {  6.61, 22.61, 33.8 },
                new double[] {  8.45, 11.11, 52.7 },
                new double[] {  1.22, 18.11, 16.2 },
                new double[] {  7.42, 12.81, 87.3 },
                new double[] {  4.42, 10.21, 12.5 },
                new double[] {  8.61, 11.94, 77.5 },
                new double[] {  1.73, 13.13, 12.1 },
                new double[] {  7.47, 17.11, 86.5 },
                new double[] {  6.11, 15.13, 62.8 },
                new double[] {  1.42, 16.11, 17.5 },
            };

            // For this, we first extract the input and output
            // pairs. The first two columns have values for the
            // input variables, and the last for the output:

            double[][] inputs = example.GetColumns(new[] { 0, 1 });
            double[] output = example.GetColumn(2);

            // We can create a new multiple linear replacedysis for the variables
            var mlra = new MultipleLinearRegressionreplacedysis(intercept: true);

            // Compute the replacedysis and obtain the estimated regression
            MultipleLinearRegression regression = mlra.Learn(inputs, output);
            #endregion

            // We can also show a summary ANOVA
            // Accord.Controls.DataGridBox.Show(regression.Table);

            #region doc_learn_part2
            // And also extract other useful information, such
            // as the linear coefficients' values and std errors:
            double[] coef = mlra.CoefficientValues;
            double[] stde = mlra.StandardErrors;

            // Coefficients of performance, such as r²
            double rsquared = mlra.RSquared; // 0.62879

            // Hypothesis tests for the whole model
            ZTest ztest = mlra.ZTest; // 0.99999
            FTest ftest = mlra.FTest; // 0.01898

            // and for individual coefficients
            TTest ttest0 = mlra.Coefficients[0].TTest; // 0.00622
            TTest ttest1 = mlra.Coefficients[1].TTest; // 0.53484

            // and also extract confidence intervals
            DoubleRange ci = mlra.Coefficients[0].Confidence; // [3.2616, 14.2193]

            // We can use the replacedysis to predict an output for a sample
            double y = mlra.Regression.Transform(new double[] { 10, 15 });

            // We can also obtain confidence intervals for the prediction:
            DoubleRange pci = mlra.GetConfidenceInterval(new double[] { 10, 15 });

            // and also prediction intervals for the same prediction:
            DoubleRange ppi = mlra.GetPredictionInterval(new double[] { 10, 15 });
            #endregion


            replacedert.AreEqual(3, coef.Length);
            replacedert.AreEqual(8.7405051051757816, coef[0]);
            replacedert.AreEqual(1.1198079243314365, coef[1], 1e-10);
            replacedert.AreEqual(-19.604474518407862, coef[2], 1e-10);
            replacedert.IsFalse(coef.HasNaN());

            replacedert.AreEqual(2.375916659234715, stde[0], 1e-10);
            replacedert.AreEqual(1.7268508921418664, stde[1], 1e-10);
            replacedert.AreEqual(30.989640986710953, stde[2], 1e-10);
            replacedert.IsFalse(coef.HasNaN());

            replacedert.AreEqual(0.62879941171298936, rsquared, 1e-10);

            replacedert.AreEqual(0.99999999999999822, ztest.PValue, 1e-10);
            replacedert.AreEqual(0.018986050133298293, ftest.PValue, 1e-10);

            replacedert.AreEqual(0.0062299844256985537, ttest0.PValue, 1e-10);
            replacedert.AreEqual(0.53484850318449118, ttest1.PValue, 1e-14);
            replacedert.IsFalse(Double.IsNaN(ttest1.PValue));

            replacedert.AreEqual(3.2616314640800566, ci.Min, 1e-10);
            replacedert.AreEqual(14.219378746271506, ci.Max, 1e-10);




            double[][] im = mlra.InformationMatrix;
            double mse = regression.GetStandardError(inputs, output);
            DoubleRange epci = regression.GetConfidenceInterval(new double[] { 10, 15 }, mse, inputs.Length, im);

            replacedert.AreEqual(epci.Min, pci.Min, 1e-10);
            replacedert.AreEqual(epci.Max, pci.Max, 1e-10);

            replacedert.AreEqual(55.27840511658215, pci.Min, 1e-10);
            replacedert.AreEqual(113.91698568006086, pci.Max, 1e-10);

            replacedert.AreEqual(28.783074454641557, ppi.Min, 1e-10);
            replacedert.AreEqual(140.41231634200145, ppi.Max, 1e-10);
        }

19 View Source File : MultipleLinearRegressionAnalysisTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void RegressTest7()
        {
            double[][] example2 =
            {
                new double[] { -0.47, 1.16, -1.25 },
                new double[] {  0.55, 1.15, -0.78 },
                new double[] {  1.38, 0.63, -0.84 },
                new double[] {  0.99, 0.63, -0.81 },
                new double[] {  1.72, 0.62, -1.59 },
                new double[] {  1.05, 0.62, -1.05 },
                new double[] { -0.51, 0.62, -0.98 },
                new double[] {  1.83, 0.61,  0.86 },
                new double[] {  1.16, 0.61,  0.15 },
                new double[] {  0.59, 0.61, -0.28 },
                new double[] {  0.40, 0.60, -0.30 },
                new double[] {  0.48, 0.60, -0.41 },
                new double[] {  1.28, 0.53, -0.31 },
                new double[] {  0.36, 0.53, -0.41 },
                new double[] {  0.93, 0.16, -0.19 },
                new double[] { -0.61, 0.16, -0.32 },
                new double[] { -0.58, 0.16, -0.01 },
                new double[] {  0.53, 0.16, -0.13 },
                new double[] {  1.48, 0.16,  1.12 },
                new double[] { -0.34, 0.15, -0.10 },
                new double[] {  0.81, 0.15,  0.14 },
                new double[] {  0.85, 0.15, -0.02 },
                new double[] {  0.69, 0.15, -0.16 },
                new double[] {  0.39, 0.15, -0.33 },
                new double[] {  0.70, 0.00,  2.00 },
                new double[] {  0.25, 0.00, -0.01 },
                new double[] { -0.96, 0.85, -0.19 },
                new double[] {  1.04, 0.84,  0.35 },
                new double[] {  0.30, 0.83,  0.05 },
                new double[] {  0.28, 0.83,  0.84 },
                new double[] {  0.18, 0.82,  0.06 },
                new double[] {  0.49, 0.81,  0.41 },
                new double[] {  0.40, 0.81,  0.50 },
                new double[] {  0.41, 0.80,  0.00 },
                new double[] {  0.06, 0.79,  0.39 },
                new double[] {  0.55, 0.79,  0,55 },
            };


            double[][] inputs = example2.GetColumns(new[] { 1, 2 });
            double[] outputs = example2.GetColumn(0);

            bool thrown = false;

            MultipleLinearRegressionreplacedysis target;

            try
            {
                target = new MultipleLinearRegressionreplacedysis(inputs, outputs, new string[0], "Test", false);
            }
            catch (ArgumentException) { thrown = true; }

            replacedert.IsTrue(thrown);

            target = new MultipleLinearRegressionreplacedysis(inputs, outputs, new string[2], "Test", false);

            target.Compute();

            replacedert.AreEqual(2, target.NumberOfInputs);
            replacedert.AreEqual(1, target.NumberOfOutputs);

            replacedert.AreEqual(target.Array, inputs);
            replacedert.AreEqual(target.Outputs, outputs);

            replacedert.AreEqual(-0.19371930561139417, target.RSquared, 1e-5);
            replacedert.AreEqual(-0.26606593019390279, target.RSquareAdjusted, 1e-5);

            replacedert.AreEqual(2, target.Table[0].DegreesOfFreedom);
            replacedert.AreEqual(33, target.Table[1].DegreesOfFreedom);
            replacedert.AreEqual(35, target.Table[2].DegreesOfFreedom);

            replacedert.AreEqual(-2.9165797494934651, target.Table[0].SumOfSquares, 1e-10);
            replacedert.AreEqual(17.972279749493463, target.Table[1].SumOfSquares, 1e-10);
            replacedert.AreEqual(15.055699999999998, target.Table[2].SumOfSquares, 1e-10);

            replacedert.IsFalse(Double.IsNaN(target.Table[0].SumOfSquares));
            replacedert.IsFalse(Double.IsNaN(target.Table[1].SumOfSquares));
            replacedert.IsFalse(Double.IsNaN(target.Table[2].SumOfSquares));

            replacedert.AreEqual(-1.4582898747467326, target.Table[0].MeanSquares, 1e-10);
            replacedert.AreEqual(0.54461453786343827, target.Table[1].MeanSquares, 1e-10);

            replacedert.IsFalse(Double.IsNaN(target.Table[0].MeanSquares));
            replacedert.IsFalse(Double.IsNaN(target.Table[1].MeanSquares));

            replacedert.AreEqual(-2.6776550630978524, target.Table[0].Statistic.Value, 1e-10);
            replacedert.AreEqual(1, target.Table[0].Significance.PValue, 1e-16);
            replacedert.IsFalse(Double.IsNaN(target.Table[0].Significance.PValue));

            replacedert.AreEqual(0.72195200211671728, target.Coefficients[0].Value, 1e-10);
            replacedert.AreEqual(0.15872233321508125, target.Coefficients[1].Value, 1e-10);

            replacedert.IsFalse(Double.IsNaN(target.Coefficients[0].Value));
            replacedert.IsFalse(Double.IsNaN(target.Coefficients[1].Value));

            replacedert.IsFalse(target.Coefficients[0].IsIntercept);
            replacedert.IsFalse(target.Coefficients[1].IsIntercept);

            replacedert.AreEqual(0.20506051379737225, target.Coefficients[0].StandardError, 1e-10);
            replacedert.AreEqual(0.18842330299464302, target.Coefficients[1].StandardError, 1e-10);

            replacedert.IsFalse(Double.IsNaN(target.Coefficients[0].StandardError));
            replacedert.IsFalse(Double.IsNaN(target.Coefficients[1].StandardError));

            replacedert.AreEqual(3.5206778172325479, target.Coefficients[0].TTest.Statistic, 1e-10);
            replacedert.AreEqual(0.84237103740609942, target.Coefficients[1].TTest.Statistic, 1e-10);

            replacedert.IsFalse(Double.IsNaN(target.Coefficients[0].TTest.Statistic));
            replacedert.IsFalse(Double.IsNaN(target.Coefficients[1].TTest.Statistic));

            DoubleRange range;

            range = target.Coefficients[0].TTest.GetConfidenceInterval(0.9);
            replacedert.AreEqual(0.37491572761667513, range.Min, 1e-10);
            replacedert.AreEqual(1.0689882766167593, range.Max, 1e-10);

            range = target.Coefficients[1].TTest.GetConfidenceInterval(0.9);
            replacedert.AreEqual(-0.16015778606945111, range.Min, 1e-10);
            replacedert.AreEqual(0.47760245249961364, range.Max, 1e-10);


            MultipleLinearRegression mlr = new MultipleLinearRegression(2, false);
            mlr.Regress(inputs, outputs);

            replacedert.AreEqual(2, target.NumberOfInputs);
            replacedert.AreEqual(1, target.NumberOfOutputs);

            double[] actual = target.Transform(inputs);
            double[] expected = mlr.Transform(inputs);
            replacedert.IsTrue(Matrix.IsEqual(actual, expected, 1e-8));

            double r2 = mlr.CoefficientOfDetermination(inputs, outputs, false);
            double r2a = mlr.CoefficientOfDetermination(inputs, outputs, true);

            replacedert.AreEqual(r2, target.RSquared, 1e-6);
            replacedert.AreEqual(r2a, target.RSquareAdjusted, 1e-6);
        }

19 View Source File : ProportionalHazardsAnalysisTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void ComputeTest1()
        {
            // Consider the following example data, adapted from John C. Pezzullo's
            // example for his great Cox's proportional hazards model example in
            // JavaScript (http://statpages.org/prophaz2.html). 

            // In this data, we have three columns. The first column denotes the
            // input variables for the problem. The second column, the survival
            // times. And the last one is the output of the experiment (if the
            // subject has died [1] or has survived [0]).

            double[,] example =
            {
                // input  time censor
                {   50,    1,    0   },
                {   70,    2,    1   },
                {   45,    3,    0   },
                {   35,    5,    0   },
                {   62,    7,    1   },
                {   50,   11,    0   },
                {   45,    4,    0   },
                {   57,    6,    0   },
                {   32,    8,    0   },
                {   57,    9,    1   },
                {   60,   10,    1   },
            };

            // First we will extract the input, times and outputs
            double[,] inputs = example.GetColumns(new[] { 0 });
            double[] times = example.GetColumn(1);
            SurvivalOutcome[] output = example.GetColumn(2).To<SurvivalOutcome[]>();

            // Now we can proceed and create the replacedysis
            var cox = new ProportionalHazardsreplacedysis(inputs, times, output);

            cox.Compute(); // compute the replacedysis

            // Now we can show an replacedysis summary
            // Accord.Controls.DataGridBox.Show(cox.Coefficients);


            // We can also investigate all parameters individually. For
            // example the coefficients values will be available at

            double[] coef = cox.CoefficientValues;
            double[] stde = cox.StandardErrors;

            // We can also obtain the hazards ratios
            double[] ratios = cox.HazardRatios;

            // And other information such as the partial
            // likelihood, the deviance and also make 
            // hypothesis tests on the parameters

            double partial = cox.LogLikelihood;
            double deviance = cox.Deviance;

            // Chi-Square for whole model
            ChiSquareTest chi = cox.ChiSquare;

            // Wald tests for individual parameters
            WaldTest wald = cox.Coefficients[0].Wald;


            // Finally, we can also use the model to predict
            // scores for new observations (without considering time)

            double y1 = cox.Regression.Compute(new double[] { 63 });
            double y2 = cox.Regression.Compute(new double[] { 32 });

            // Those scores can be interpreted by comparing then
            // to 1. If they are greater than one, the odds are
            // the patient will not survive. If the value is less
            // than one, the patient is likely to survive.

            // The first value, y1, gives approximately 86.138,
            // while the second value, y2, gives about 0.00072.


            // We can also consider instant estimates for a given time:
            double p1 = cox.Regression.Compute(new double[] { 63 }, 2);
            double p2 = cox.Regression.Compute(new double[] { 63 }, 10);

            // Here, p1 is the score after 2 time instants, with a 
            // value of 0.0656. The second value, p2, is the time
            // after 10 time instants, with a value of 6.2907.


            replacedert.AreEqual(86.138421225296526, y1);
            replacedert.AreEqual(0.00072281400325299814, y2, 1e-10);

            replacedert.AreEqual(0.17989138010770425, p1, 1e-10);
            replacedert.AreEqual(15.950244161356357, p2, 1e-10);

            replacedert.AreEqual(1, coef.Length);
            replacedert.AreEqual(0.37704239281490765, coef[0]);
            replacedert.AreEqual(0.25415746361167235, stde[0]);
            replacedert.AreEqual(1.4579661153488215, ratios[0]);

            replacedert.AreEqual(-2.0252666205735466, partial, 1e-6);
            replacedert.AreEqual(4.0505332411470931, deviance, 1e-6);

            replacedert.AreEqual(0.13794183001851756, wald.PValue, 1e-4);

            replacedert.AreEqual(1, chi.DegreesOfFreedom);
            replacedert.AreEqual(7.3570, chi.Statistic, 1e-4);
            replacedert.AreEqual(0.0067, chi.PValue, 1e-3);
        }

19 View Source File : ProportionalHazardsAnalysisTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void learn_test()
        {
            #region doc_learn_part1
            // Consider the following example data, adapted from John C. Pezzullo's
            // example for his great Cox's proportional hazards model example in
            // JavaScript (http://statpages.org/prophaz2.html). 

            // In this data, we have three columns. The first column denotes the
            // input variables for the problem. The second column, the survival
            // times. And the last one is the output of the experiment (if the
            // subject has died [1] or has survived [0]).

            double[][] example =
            {
                //             input  time censor
                new double[] {   50,    1,    0   },
                new double[] {   70,    2,    1   },
                new double[] {   45,    3,    0   },
                new double[] {   35,    5,    0   },
                new double[] {   62,    7,    1   },
                new double[] {   50,   11,    0   },
                new double[] {   45,    4,    0   },
                new double[] {   57,    6,    0   },
                new double[] {   32,    8,    0   },
                new double[] {   57,    9,    1   },
                new double[] {   60,   10,    1   },
            };

            // First we will extract the input, times and outputs
            double[][] inputs = example.Get(null, 0, 1);
            double[] times = example.GetColumn(1);
            SurvivalOutcome[] output = example.GetColumn(2).To<SurvivalOutcome[]>();

            // Now we can proceed and create the replacedysis (giving optional variable names)
            var cox = new ProportionalHazardsreplacedysis(new[] { "input" }, "time", "censor");

            // Then compute the replacedysis, learning a regression in the process:
            ProportionalHazards regression = cox.Learn(inputs, times, output);

            // Now we can show an replacedysis summary
            // Accord.Controls.DataGridBox.Show(cox.Coefficients);
            #endregion

            #region doc_learn_part2

            // We can also investigate all parameters individually. For
            // example the coefficients values will be available at

            double[] coef = cox.CoefficientValues;     // should be { 0.37704239281490765 }
            double[] stde = cox.StandardErrors;        // should be { 0.25415746361167235 }

            // We can also obtain the hazards ratios
            double[] ratios = cox.HazardRatios;        // should be { 1.4579661153488215 }

            // And other information such as the partial
            // likelihood, the deviance and also make 
            // hypothesis tests on the parameters

            double partialL = cox.LogLikelihood;       // should be -2.0252666205735466
            double deviance = cox.Deviance;            // should be 4.0505332411470931
                                                       
            // Chi-Square for whole model              
            ChiSquareTest chi = cox.ChiSquare;         // should be 7.3570 (p=0.0067)

            // Wald tests for individual parameters
            WaldTest wald = cox.Coefficients[0].Wald;  // should be 1.4834 (p=0.1379)


            // Finally, we can also use the model to predict
            // scores for new observations (without considering time)

            double y1 = cox.Regression.Probability(new double[] { 63 }); // should be 86.138421225296526
            double y2 = cox.Regression.Probability(new double[] { 32 }); // should be 0.00072281400325299814

            // Those scores can be interpreted by comparing then
            // to 1. If they are greater than one, the odds are
            // the patient will not survive. If the value is less
            // than one, the patient is likely to survive.

            // The first value, y1, gives approximately 86.138,
            // while the second value, y2, gives about 0.00072.


            // We can also consider instant estimates for a given time:
            double p1 = cox.Regression.Probability(new double[] { 63 }, 2);   // should be 0.17989138010770425
            double p2 = cox.Regression.Probability(new double[] { 63 }, 10);  // should be 15.950244161356357

            // Here, p1 is the score after 2 time instants, with a 
            // value of 0.0656. The second value, p2, is the time
            // after 10 time instants, with a value of 6.2907.

            // In addition, if we would like a higher precision when 
            // computing very small probabilities using the methods 
            // above, we can use the LogLikelihood methods instead:

            double log_y1 = cox.Regression.LogLikelihood(new double[] { 63 });      // should be  4.4559555514489091
            double log_y2 = cox.Regression.LogLikelihood(new double[] { 32 });      // should be -7.2323586258132284
            double log_p1 = cox.Regression.LogLikelihood(new double[] { 63 }, 2);   // should be -1.7154020540835324
            double log_p2 = cox.Regression.LogLikelihood(new double[] { 63 }, 10);  // should be  2.7694741370357177
            #endregion

            replacedert.AreEqual(86.138421225296526, y1, 1e-10);
            replacedert.AreEqual(0.00072281400325299814, y2, 1e-10);

            replacedert.AreEqual(0.17989138010770425, p1, 1e-10);
            replacedert.AreEqual(15.950244161356357, p2, 1e-10);

            replacedert.AreEqual(4.4559555514489091, log_y1, 1e-10);
            replacedert.AreEqual(-7.2323586258132284, log_y2, 1e-10);

            replacedert.AreEqual(-1.7154020540835324, log_p1, 1e-10);
            replacedert.AreEqual(2.7694741370357177, log_p2, 1e-10);

            replacedert.AreEqual(System.Math.Log(y1), log_y1, 1e-10);
            replacedert.AreEqual(System.Math.Log(y2), log_y2, 1e-10);

            replacedert.AreEqual(System.Math.Log(p1), log_p1, 1e-10);
            replacedert.AreEqual(System.Math.Log(p2), log_p2, 1e-10);

            replacedert.AreEqual(1, coef.Length);
            replacedert.AreEqual(0.37704239281490765, coef[0]);
            replacedert.AreEqual(0.25415746361167235, stde[0]);
            replacedert.AreEqual(1.4579661153488215, ratios[0]);

            replacedert.AreEqual(-2.0252666205735466, partialL, 1e-6);
            replacedert.AreEqual(4.0505332411470931, deviance, 1e-6);

            replacedert.AreEqual(1.4834991955655938, wald.Statistic, 1e-4);
            replacedert.AreEqual(0.13794183001851756, wald.PValue, 1e-4);

            replacedert.AreEqual(1, chi.DegreesOfFreedom);
            replacedert.AreEqual(7.3570, chi.Statistic, 1e-4); 
            replacedert.AreEqual(0.0067, chi.PValue, 1e-3);
        }

19 View Source File : MultivariateContinuousDistributionTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void FitTest7()
        {
            MultivariateContinuousDistribution target = CreateMultivariateContinuousDistribution();

            double[][] observations = 
            {
                new double[] { 1, 2 },
                new double[] { 3, 2 },
                new double[] { 2, 3 },
                new double[] { 1, 2 },
            };

            double[] weights = { 0.125, 0.125, 0.25, 0.5 };

            target.Fit(observations, weights);

            double[] expectedMean = { 1.5, 2.25 };
            double[,] expectedCov = 
            {
                { 0.76190476190476186, 0.19047619047619047 },
                { 0.19047619047619047, 0.2857142857142857 },
            };

            replacedert.IsTrue(expectedMean.IsEqual(target.Mean));
            replacedert.IsTrue(expectedCov.IsEqual(target.Covariance));


            replacedert.IsTrue(Matrix.Diagonal(expectedCov).IsEqual(target.Variance));

            double[] x = { 0.4, 2 };
            double expected = 0.168681501947055;
            double actual = target.ProbabilityDensityFunction(x);
            replacedert.AreEqual(expected, actual, 1e-10);
        }

19 View Source File : MultivariateContinuousDistributionTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void FitTest6()
        {
            MultivariateContinuousDistribution target = CreateMultivariateContinuousDistribution(); // TODO: Initialize to an appropriate value
            double[][] observations = 
            {
                new double[] { 1, 2 },
                new double[] { 3, 2 },
                new double[] { 2, 3 },
                new double[] { 1, 2 },
            };

            target.Fit(observations);

            double[] expectedMean = { 1.75, 2.25 };
            double[,] expectedCov = 
            {
                { 0.91666666666666663,  0.083333333333333329 },
                { 0.083333333333333329, 0.25                 },
            };

            replacedert.IsTrue(expectedMean.IsEqual(target.Mean));
            replacedert.IsTrue(expectedCov.IsEqual(target.Covariance));

            replacedert.IsTrue(expectedCov.Diagonal().IsEqual(target.Variance));

            double[] x = { 0.4, 2 };
            double expected = 0.120833904312578;
            double actual = target.ProbabilityDensityFunction(x);
            replacedert.AreEqual(expected, actual, 1e-10);
        }

19 View Source File : MultivariateEmpiricalDistributionTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void WeightedEmpiricalDistributionConstructorTest2()
        {
            double[] original = { 5, 5, 1, 4, 1, 2, 2, 3, 3, 3, 4, 3, 3, 3, 4, 3, 2, 3 };
            var distribution = new MultivariateEmpiricalDistribution(original.ToJagged());

            double[] weights = { 2, 1, 1, 1, 2, 3, 1, 3, 1, 1, 1, 1 };
            double[] source = { 5, 1, 4, 1, 2, 3, 4, 3, 4, 3, 2, 3 };
            double[][] samples = source.ToJagged();

            weights = weights.Divide(weights.Sum());

            var target = new MultivariateEmpiricalDistribution(samples,
                weights, distribution.Smoothing);

            replacedert.AreEqual(distribution.Mean[0], target.Mean[0]);
            replacedert.AreEqual(distribution.Median[0], target.Median[0]);
            replacedert.AreEqual(distribution.Mode[0], target.Mode[0]);
            replacedert.AreEqual(distribution.Smoothing[0, 0], target.Smoothing[0, 0]);
            replacedert.AreEqual(1.3655172413793104, target.Variance[0]);
            replacedert.AreEqual(target.Weights, weights);
            replacedert.AreEqual(target.Samples, samples);

            for (double x = 0; x < 6; x += 0.1)
            {
                double actual, expected;
                expected = distribution.ComplementaryDistributionFunction(x);
                actual = target.ComplementaryDistributionFunction(x);
                replacedert.AreEqual(expected, actual, 1e-15);

                expected = distribution.DistributionFunction(x);
                actual = target.DistributionFunction(x);
                replacedert.AreEqual(expected, actual, 1e-15);

                expected = distribution.LogProbabilityDensityFunction(x);
                actual = target.LogProbabilityDensityFunction(x);
                replacedert.AreEqual(expected, actual, 1e-15);

                expected = distribution.ProbabilityDensityFunction(x);
                actual = target.ProbabilityDensityFunction(x);
                replacedert.AreEqual(expected, actual, 1e-15);
            }
        }

19 View Source File : VonMisesFisherDistributionTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void ConstructorTest1()
        {
            // If p=2 the distribution reduces to the von Mises distribution on the circle.

            double kappa = 4.2;
            var vm = new VonMisesDistribution(0, kappa);
            var target = new VonMisesFisherDistribution(new double[] { -1, 0 }, kappa);

            double s = Math.Sqrt(2) / 2;
            double[] mean = target.Mean;

            double a000 = target.ProbabilityDensityFunction(new double[] { +1, +0 });
            double a045 = target.ProbabilityDensityFunction(new double[] { +s, +s });
            double a090 = target.ProbabilityDensityFunction(new double[] { +0, +1 });
            double a135 = target.ProbabilityDensityFunction(new double[] { -s, +s });
            double a180 = target.ProbabilityDensityFunction(new double[] { -1, +0 });
            double a225 = target.ProbabilityDensityFunction(new double[] { -s, -s });
            double a270 = target.ProbabilityDensityFunction(new double[] { +0, -1 });
            double a315 = target.ProbabilityDensityFunction(new double[] { +s, -s });
            double a360 = target.ProbabilityDensityFunction(new double[] { +1, +0 });

            double offset = -Math.PI;
            double e000 = vm.ProbabilityDensityFunction(offset + 0);
            double e045 = vm.ProbabilityDensityFunction(offset + Math.PI / 4);
            double e090 = vm.ProbabilityDensityFunction(offset + Math.PI / 2);
            double e135 = vm.ProbabilityDensityFunction(offset + Math.PI * (3 / 4.0));
            double e180 = vm.ProbabilityDensityFunction(offset + Math.PI);
            double e225 = vm.ProbabilityDensityFunction(offset + Math.PI * (5 / 4.0));
            double e270 = vm.ProbabilityDensityFunction(offset + Math.PI * (3 / 2.0));
            double e315 = vm.ProbabilityDensityFunction(offset + Math.PI * (7 / 4.0));
            double e360 = vm.ProbabilityDensityFunction(offset + Math.PI * 2);


            replacedert.AreEqual(e000, a000, 1e-8);
            replacedert.AreEqual(e045, a045, 1e-8);
            replacedert.AreEqual(e090, a090, 1e-8);
            replacedert.AreEqual(e135, a135, 1e-8);
            replacedert.AreEqual(e180, a180, 1e-8);
            replacedert.AreEqual(e225, a225, 1e-8);
            replacedert.AreEqual(e270, a270, 1e-8);
            replacedert.AreEqual(e315, a315, 1e-8);
            replacedert.AreEqual(e360, a360, 1e-8);
        }

19 View Source File : JointDistributionTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void DistributionFunctionTest()
        {
            var target = new JointDistribution(new[] { 0.1, 0.4, 0.5 });

            double actual;

            actual = target.DistributionFunction(new[] { 0 });
            replacedert.AreEqual(0.1, actual, 1e-6);

            actual = target.DistributionFunction(new[] { 1 });
            replacedert.AreEqual(0.5, actual, 1e-6);

            actual = target.DistributionFunction(new[] { 2 });
            replacedert.AreEqual(1.0, actual, 1e-6);

            actual = target.DistributionFunction(new[] { 3 });
            replacedert.AreEqual(1.0, actual, 1e-6);
        }

19 View Source File : MultinomialDistributionTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void ProbabilityMreplacedFunctionTest2()
        {
            // Example from http://onlinestatbook.com/2/probability/multinomial.html

            MultinomialDistribution dist = new MultinomialDistribution(12, 0.40, 0.35, 0.25);

            int[] observation = { 7, 2, 3 };

            double actual = dist.ProbabilityMreplacedFunction(observation);
            double expected = 0.02483712;

            replacedert.AreEqual(expected, actual, 1e-6);
        }

19 View Source File : MultivariateMixtureDistributionTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        [Category("Office")]
        public void MixtureWeightsFitTest2()
        {
            string path = Path.Combine(TestContext.CurrentContext.TestDirectory, "Resources", "CircleWithWeights.xls");

            ExcelReader reader = new ExcelReader(path);

            DataTable table = reader.GetWorksheet("Sheet1");

            double[,] matrix = table.ToMatrix();

            double[][] points = matrix.Submatrix(null, 0, 1).ToJagged();
            double[] weights = matrix.GetColumn(2);

            // Randomly initialize some mixture components
            MultivariateNormalDistribution[] components = new MultivariateNormalDistribution[2];
            components[0] = new MultivariateNormalDistribution(new double[] { 0, 1 }, Matrix.Idenreplacedy(2));
            components[1] = new MultivariateNormalDistribution(new double[] { 1, 0 }, Matrix.Idenreplacedy(2));

            // Create an initial mixture
            var mixture = new MultivariateMixture<MultivariateNormalDistribution>(components);

            mixture.Fit(points, weights);

            // Our model will be:
            double mean00 = mixture.Components[0].Mean[0];
            double mean01 = mixture.Components[0].Mean[1];
            double mean10 = mixture.Components[1].Mean[0];
            double mean11 = mixture.Components[1].Mean[1];

            replacedert.AreEqual(-0.11704994950834195, mean00, 1e-10);
            replacedert.AreEqual(0.11603470123007256, mean01, 1e-10);
            replacedert.AreEqual(0.11814483652855159, mean10, 1e-10);
            replacedert.AreEqual(-0.12029275652994373, mean11, 1e-10);
        }

19 View Source File : AndersonDarlingDistributionTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void ConstructorTest()
        {
            // Create a new Anderson Darling distribution (A²) for comparing against a Gaussian
            var a2 = new AndersonDarlingDistribution(AndersonDarlingDistributionType.Normal, 30);

            double median = a2.Median; // 0.33089957635450062

            double chf = a2.replacedulativeHazardFunction(x: 0.27); // 0.42618068373640966
            double cdf = a2.DistributionFunction(x: 0.27); // 0.34700165471995292
            double ccdf = a2.ComplementaryDistributionFunction(x: 0.27); // 0.65299834528004708
            double icdf = a2.InverseDistributionFunction(p: cdf); // 0.27000000012207787

            string str = a2.ToString(CultureInfo.InvariantCulture); // "A²(x; n = 30)"

            replacedert.AreEqual(0.33089957635450062, median, 1e-6);
            replacedert.AreEqual(0.42618068373640966, chf, 1e-6);
            replacedert.AreEqual(0.34700165471995292, cdf, 1e-6);
            replacedert.AreEqual(0.65299834528004708, ccdf, 1e-6);
            replacedert.AreEqual(0.27, icdf, 1e-6);
            replacedert.AreEqual("A²(x; n = 30)", str);

            replacedert.IsFalse(Double.IsNaN(median));

            var range1 = a2.GetRange(0.95);
            var range2 = a2.GetRange(0.99);
            var range3 = a2.GetRange(0.01);

            replacedert.AreEqual(0.1552371857564955, range1.Min, 1e-6);
            replacedert.AreEqual(0.73303544269106991, range1.Max, 1e-6);
            replacedert.AreEqual(0.11507415861447158, range2.Min, 1e-6);
            replacedert.AreEqual(1.0090123686318795, range2.Max, 1e-6);
            replacedert.AreEqual(0.1150741586144715, range3.Min, 1e-6);
            replacedert.AreEqual(1.0090123686318795, range3.Max, 1e-6);

            replacedert.AreEqual(0, a2.Support.Min);
            replacedert.AreEqual(Double.PositiveInfinity, a2.Support.Max);

            replacedert.AreEqual(a2.InverseDistributionFunction(0), a2.Support.Min);
            replacedert.AreEqual(a2.InverseDistributionFunction(1), a2.Support.Max);
        }

19 View Source File : AndersonDarlingDistributionTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void uniform_test()
        {
            // Create a new Anderson Darling distribution (A²) for comparing against a Uniform distribution
            var a2 = new AndersonDarlingDistribution(AndersonDarlingDistributionType.Uniform, 10);

            double median = a2.Median; 

            double chf = a2.replacedulativeHazardFunction(x: 0.27); 
            double cdf = a2.DistributionFunction(x: 0.27); 
            double ccdf = a2.ComplementaryDistributionFunction(x: 0.27);
            double icdf = a2.InverseDistributionFunction(p: cdf); 

            string str = a2.ToString(CultureInfo.InvariantCulture); // "A²(x; n = 30)"

            replacedert.AreEqual(0.76936270639003257, median, 1e-6);
            replacedert.AreEqual(0.0424239540571123, chf, 1e-6);
            replacedert.AreEqual(0.041536650001198654, cdf, 1e-6);
            replacedert.AreEqual(0.95846334999880134, ccdf, 1e-6);
            replacedert.AreEqual(0.27, icdf, 1e-6);
            replacedert.AreEqual("A²(x; n = 10)", str);

            replacedert.IsFalse(Double.IsNaN(median));

            var range1 = a2.GetRange(0.95);
            var range2 = a2.GetRange(0.99);
            var range3 = a2.GetRange(0.01);

            replacedert.AreEqual(0.28254198132705227, range1.Min, 1e-6);
            replacedert.AreEqual(2.5127111321231137, range1.Max, 1e-6);
            replacedert.AreEqual(0.20232764997988909, range2.Min, 1e-6);
            replacedert.AreEqual(3.9195747018635374, range2.Max, 1e-6);
            replacedert.AreEqual(0.20232764997988903, range3.Min, 1e-6);
            replacedert.AreEqual(3.9195747018635374, range3.Max, 1e-6);

            replacedert.AreEqual(0, a2.Support.Min);
            replacedert.AreEqual(Double.PositiveInfinity, a2.Support.Max);

            replacedert.AreEqual(a2.InverseDistributionFunction(0), a2.Support.Min);
            replacedert.AreEqual(a2.InverseDistributionFunction(1), a2.Support.Max);
        }

19 View Source File : BetaDistributionTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void BetaMeanTest()
        {
            double alpha = 0.42;
            double beta = 1.57;

            BetaDistribution betaDistribution = new BetaDistribution(alpha, beta);

            double mean = betaDistribution.Mean; // 0.21105527638190955
            double median = betaDistribution.Median; // 0.11577706212908731
            double var = betaDistribution.Variance; // 0.055689279830523512
            double mode = betaDistribution.Mode;    // 57.999999999999957

            double chf = betaDistribution.replacedulativeHazardFunction(x: 0.27); // 1.1828193992944409
            double cdf = betaDistribution.DistributionFunction(x: 0.27); // 0.69358638272337991
            double pdf = betaDistribution.ProbabilityDensityFunction(x: 0.27); // 0.94644031936694828
            double lpdf = betaDistribution.LogProbabilityDensityFunction(x: 0.27); // -0.055047364344046057
            double hf = betaDistribution.HazardFunction(x: 0.27); // 3.0887671630877072
            double ccdf = betaDistribution.ComplementaryDistributionFunction(x: 0.27); // 0.30641361727662009
            double icdf = betaDistribution.InverseDistributionFunction(p: cdf); // 0.26999999068687469

            string str = betaDistribution.ToString(System.Globalization.CultureInfo.InvariantCulture); // "B(x; α = 0.42, β = 1.57)

            replacedert.AreEqual(0.21105527638190955, mean);
            replacedert.AreEqual(0.11577706212908731, median);
            replacedert.AreEqual(57.999999999999957, mode);
            replacedert.AreEqual(0.055689279830523512, var);
            replacedert.AreEqual(1.1828193992944409, chf);
            replacedert.AreEqual(0.69358638272337991, cdf);
            replacedert.AreEqual(0.94644031936694828, pdf);
            replacedert.AreEqual(-0.055047364344046057, lpdf);
            replacedert.AreEqual(3.0887671630877072, hf);
            replacedert.AreEqual(0.30641361727662009, ccdf);
            replacedert.AreEqual(0.27, icdf, 1e-10);
            replacedert.AreEqual("B(x; α = 0.42, β = 1.57)", str);

            replacedert.IsFalse(Double.IsNaN(median));

            var range1 = betaDistribution.GetRange(0.95);
            var range2 = betaDistribution.GetRange(0.99);
            var range3 = betaDistribution.GetRange(0.01);

            replacedert.AreEqual(0.00045925525776717733, range1.Min);
            replacedert.AreEqual(0.72381020663218609, range1.Max);
            replacedert.AreEqual(0.0000099485893745082635, range2.Min);
            replacedert.AreEqual(0.89625688707910811, range2.Max);
            replacedert.AreEqual(0.0000099485893745082432, range3.Min);
            replacedert.AreEqual(0.89625688707910811, range3.Max);

            replacedert.AreEqual(0, betaDistribution.Support.Min);
            replacedert.AreEqual(1, betaDistribution.Support.Max);

            replacedert.AreEqual(betaDistribution.InverseDistributionFunction(0), betaDistribution.Support.Min);
            replacedert.AreEqual(betaDistribution.InverseDistributionFunction(1), betaDistribution.Support.Max);
        }

19 View Source File : QuadraticObjectiveFunctionTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void replacedgeneousTest()
        {
            double[,] quadraticTerms =
            {
                {  8, 3, 1 },
                {  3, 4, 2 },
                {  1, 2, 6 },
            };

            double[] linearTerms = { 0, 0, 0 };

            var target = new QuadraticObjectiveFunction(quadraticTerms, linearTerms);

            var function = target.Function;
            var gradient = target.Gradient;

            FiniteDifferences fd = new FiniteDifferences(3, function);

            double[][] x =
            {
                new double[] { 1, 2, 3 },
                new double[] { 3, 1, 4 },
                new double[] { -6 , 5, 9 },
                new double[] { 31, 25, 246 },
                new double[] { -0.102, 0, 10 },
            };

            { // Gradient test
                for (int i = 0; i < x.Length; i++)
                {
                    double[] expected = fd.Compute(x[i]);
                    double[] actual = gradient(x[i]);

                    for (int j = 0; j < actual.Length; j++)
                        replacedert.AreEqual(expected[j], actual[j], 1e-6);
                }
            }
        }

19 View Source File : QuadraticObjectiveFunctionTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void replacedgeneousTest2()
        {
            double[,] quadraticTerms =
            {
                {  1, 0, 1 },
                {  0, 2, 0 },
                {  1, 0, 1 },
            };

            double[] linearTerms = { 0, 0, 0 };

            var target = new QuadraticObjectiveFunction(quadraticTerms, linearTerms);

            var function = target.Function;
            var gradient = target.Gradient;

            FiniteDifferences fd = new FiniteDifferences(3, function);

            double[][] x =
            {
                new double[] { 1, 2, 3 },
                new double[] { 3, 1, 4 },
                new double[] { -6 , 5, 9 },
                new double[] { 31, 25, 246 },
                new double[] { -0.102, 0, 10 },
            };

            { // Gradient test
                for (int i = 0; i < x.Length; i++)
                {
                    double[] expected = fd.Compute(x[i]);
                    double[] actual = gradient(x[i]);

                    for (int j = 0; j < actual.Length; j++)
                        replacedert.AreEqual(expected[j], actual[j], 1e-8);
                }
            }
        }

19 View Source File : QuadraticObjectiveFunctionTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void FunctionTest()
        {
            double x = 0;
            double y = 0;

            Func<double> expected = () => -2 * x * x + x * y - y * y + 5 * y;
            var actual = new QuadraticObjectiveFunction("-2x² + xy - y² + 5y");

            for (int i = 0; i < 10; i++)
            {
                for (int j = 0; j < 10; j++)
                {
                    x = (i - 5) / 10.0;
                    y = (j - 5) / 10.0;

                    double a = actual.Function(new[] { x, y });
                    double e = expected();

                    replacedert.AreEqual(e, a, 1e-10);
                    replacedert.IsFalse(double.IsNaN(a));
                    replacedert.IsFalse(double.IsNaN(e));
                }
            }
        }

19 View Source File : QuadraticObjectiveFunctionTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void FunctionTest2()
        {
            double x = 0;
            double y = 0;
            double z = 0;

            Func<double> expected = () => -2 * x * x + x * y - y * y - 10 * x * z + z * z;
            var actual = new QuadraticObjectiveFunction("-2x² + xy - y² - 10xz + z²");

            for (int i = 0; i < 10; i++)
            {
                for (int j = 0; j < 10; j++)
                {
                    for (int k = 0; k < 10; k++)
                    {
                        x = (i - 5) / 10.0;
                        y = (j - 5) / 10.0;
                        z = (k - 5) / 10.0;

                        double a = actual.Function(new[] { x, y, z });
                        double e = expected();

                        replacedert.AreEqual(e, a, 1e-10);
                        replacedert.IsFalse(double.IsNaN(a));
                        replacedert.IsFalse(double.IsNaN(e));
                    }
                }
            }
        }

19 View Source File : QuadraticObjectiveFunctionTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void FunctionTest3()
        {
            double x = 0;

            Func<double> expected = () => x * x + 1;
            var actual = new QuadraticObjectiveFunction("x² + 1");

            for (int i = 0; i < 10; i++)
            {
                x = (i - 5) / 10.0;

                double a = actual.Function(new[] { x });
                double e = expected();

                replacedert.AreEqual(e, a, 1e-10);
                replacedert.IsFalse(double.IsNaN(a));
                replacedert.IsFalse(double.IsNaN(e));
            }
        }

19 View Source File : QuadraticObjectiveFunctionTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void FunctionTest4()
        {
            double x = 0;
            double y = 0;
            double z = 0;

            Func<double> expected = () => -x * y + y * z;
            var actual = new QuadraticObjectiveFunction("-x*y + y*z");

            for (int i = 0; i < 10; i++)
            {
                for (int j = 0; j < 10; j++)
                {
                    for (int k = 0; k < 10; k++)
                    {
                        x = (i - 5) / 10.0;
                        y = (j - 5) / 10.0;
                        z = (k - 5) / 10.0;

                        double a = actual.Function(new[] { x, y, z });
                        double e = expected();

                        replacedert.AreEqual(e, a, 1e-10);
                        replacedert.IsFalse(double.IsNaN(a));
                        replacedert.IsFalse(double.IsNaN(e));
                    }
                }
            }
        }

19 View Source File : QuadraticObjectiveFunctionTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void FunctionTest5()
        {
            var f1 = new QuadraticObjectiveFunction("x² + 1");
            var f2 = new QuadraticObjectiveFunction("-x*y + y*z");
            var f3 = new QuadraticObjectiveFunction("-2x² + xy - y² - 10xz + z²");
            var f4 = new QuadraticObjectiveFunction("-2x² + xy - y² + 5y");
            var f5 = new QuadraticObjectiveFunction("2x² -5");

            double x = 0, y = 0, z = 0;
            var g1 = new QuadraticObjectiveFunction(() => x * x + 1);
            var g2 = new QuadraticObjectiveFunction(() => -x * y + y * z);
            var g3 = new QuadraticObjectiveFunction(() => -2 * x * x + x * y - y * y - 10 * x * z + z * z);
            var g4 = new QuadraticObjectiveFunction(() => -2 * x * x + x * y - y * y + 5 * y);
            var g5 = new QuadraticObjectiveFunction(() => 2 * x * x - 5);


            QuadraticObjectiveFunction[] f = { f1, f2, f3, f4, f5 };
            QuadraticObjectiveFunction[] g = { g1, g2, g3, g4, g5 };

            for (int l = 0; l < f.Length; l++)
            {
                var fl = f[l];
                var gl = g[l];

                replacedert.AreEqual(fl.NumberOfVariables, gl.NumberOfVariables);

                for (int i = 0; i < 10; i++)
                    for (int j = 0; j < 10; j++)
                        for (int k = 0; k < 10; k++)
                        {
                            x = (i - 5) / 10.0;
                            y = (j - 5) / 10.0;
                            z = (k - 5) / 10.0;

                            double a = fl.Function(new[] { x, y, z }.First(fl.NumberOfVariables));
                            double e = gl.Function(new[] { x, y, z }.First(fl.NumberOfVariables));

                            replacedert.AreEqual(e, a, 1e-10);
                            replacedert.IsFalse(double.IsNaN(a));
                            replacedert.IsFalse(double.IsNaN(e));
                        }
            }
        }

19 View Source File : QuadraticObjectiveFunctionTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void LambdaFunctionTest()
        {
            double x = 0;
            double y = 0;

            Func<double> expected = () => -2 * x * x + x * y - y * y + 5 * y;
            var actual = new QuadraticObjectiveFunction(() => -2 * x * x + x * y - y * y + 5 * y);

            for (int i = 0; i < 10; i++)
            {
                for (int j = 0; j < 10; j++)
                {
                    x = (i - 5) / 10.0;
                    y = (j - 5) / 10.0;

                    double a = actual.Function(new[] { x, y });
                    double e = expected();

                    replacedert.AreEqual(e, a, 1e-10);
                    replacedert.IsFalse(double.IsNaN(a));
                    replacedert.IsFalse(double.IsNaN(e));
                }
            }
        }

19 View Source File : QuadraticObjectiveFunctionTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void LambdaFunctionTest2()
        {
            double x = 0;
            double y = 0;
            double z = 0;

            Func<double> expected = () => -2 * x * x + x * y - y * y - 10 * x * z + z * z;
            var actual = new QuadraticObjectiveFunction(() => -2 * x * x + x * y - y * y - 10 * x * z + z * z);

            for (int i = 0; i < 10; i++)
                for (int j = 0; j < 10; j++)
                    for (int k = 0; k < 10; k++)
                    {
                        x = (i - 5) / 10.0;
                        y = (j - 5) / 10.0;
                        z = (k - 5) / 10.0;

                        double a = actual.Function(new[] { x, y, z });
                        double e = expected();

                        replacedert.AreEqual(e, a, 1e-10);
                        replacedert.IsFalse(double.IsNaN(a));
                        replacedert.IsFalse(double.IsNaN(e));
                    }
        }

19 View Source File : QuadraticObjectiveFunctionTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void LambdaFunctionTest3()
        {
            double x = 0;

            Func<double> expected = () => x * x + 1;
            var actual = new QuadraticObjectiveFunction(() => x * x + 1);

            for (int i = 0; i < 10; i++)
            {
                x = (i - 5) / 10.0;

                double a = actual.Function(new[] { x });
                double e = expected();

                replacedert.AreEqual(e, a, 1e-10);
                replacedert.IsFalse(Double.IsNaN(a));
                replacedert.IsFalse(Double.IsNaN(e));
            }
        }

19 View Source File : QuadraticObjectiveFunctionTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void LambdaFunctionTest4()
        {
            double x = 0;
            double y = 0;
            double z = 0;

            Func<double> expected = () => -x * y + y * z;
            var actual = new QuadraticObjectiveFunction(() => -x * y + y * z);

            for (int i = 0; i < 10; i++)
                for (int j = 0; j < 10; j++)
                    for (int k = 0; k < 10; k++)
                    {
                        x = (i - 5) / 10.0;
                        y = (j - 5) / 10.0;
                        z = (k - 5) / 10.0;

                        double a = actual.Function(new[] { x, y, z });
                        double e = expected();

                        replacedert.AreEqual(e, a, 1e-10);
                        replacedert.IsFalse(Double.IsNaN(a));
                        replacedert.IsFalse(Double.IsNaN(e));
                    }
        }

19 View Source File : QuadraticObjectiveFunctionTest.cs
License : MIT License
Project Creator : PacktPublishing

[Test]
        public void LambdaFunctionTest5()
        {
            double x = 0;
            double y = 0;
            double z = 0;

            Func<double> expected = () => 2 * y * x - x * y + y * z;
            var actual = new QuadraticObjectiveFunction(() => 2 * y * x - x * y + y * z);

            for (int i = 0; i < 10; i++)
                for (int j = 0; j < 10; j++)
                    for (int k = 0; k < 10; k++)
                    {
                        x = (i - 5) / 10.0;
                        y = (j - 5) / 10.0;
                        z = (k - 5) / 10.0;

                        double a = actual.Function(new[] { x, y, z });
                        double e = expected();

                        replacedert.AreEqual(e, a, 1e-10);
                        replacedert.IsFalse(Double.IsNaN(a));
                        replacedert.IsFalse(Double.IsNaN(e));
                    }
        }

See More Examples