Browse Source

Calculate Standard Error of the Regression for a linear model (#464)

* Addd code to calculated Standard Error of the Regression for a linear model
* Added distinction between Standard Error calculations for populations vs. samples.
* Added copyright blurb to StandardErrorTest.cs
* Fixed filename in copyright blurb in StandardErrorTest.cs
pull/468/head
David Falkner 10 years ago
committed by Christoph Ruegg
parent
commit
d7e58a02a1
  1. 55
      src/Numerics/GoodnessOfFit.cs
  2. 9
      src/Numerics/Properties/Resources.Designer.cs
  3. 3
      src/Numerics/Properties/Resources.resx
  4. 86
      src/UnitTests/GoodnessOfFit/StandardErrorTest.cs
  5. 1
      src/UnitTests/UnitTests.csproj

55
src/Numerics/GoodnessOfFit.cs

@ -25,7 +25,9 @@
// OTHER DEALINGS IN THE SOFTWARE. // OTHER DEALINGS IN THE SOFTWARE.
// </copyright> // </copyright>
using System;
using System.Collections.Generic; using System.Collections.Generic;
using MathNet.Numerics.Properties;
using MathNet.Numerics.Statistics; using MathNet.Numerics.Statistics;
namespace MathNet.Numerics namespace MathNet.Numerics
@ -33,7 +35,7 @@ namespace MathNet.Numerics
public static class GoodnessOfFit public static class GoodnessOfFit
{ {
/// <summary> /// <summary>
/// Calculated the R-Squared value, also known as coefficient of determination, /// Calculates the R-Squared value, also known as coefficient of determination,
/// given modelled and observed values /// given modelled and observed values
/// </summary> /// </summary>
/// <param name="modelledValues">The values expected from the modelled</param> /// <param name="modelledValues">The values expected from the modelled</param>
@ -46,7 +48,7 @@ namespace MathNet.Numerics
} }
/// <summary> /// <summary>
/// Calculated the R value, also known as linear correlation coefficient, /// Calculates the R value, also known as linear correlation coefficient,
/// given modelled and observed values /// given modelled and observed values
/// </summary> /// </summary>
/// <param name="modelledValues">The values expected from the modelled</param> /// <param name="modelledValues">The values expected from the modelled</param>
@ -56,5 +58,54 @@ namespace MathNet.Numerics
{ {
return Correlation.Pearson(modelledValues, observedValues); return Correlation.Pearson(modelledValues, observedValues);
} }
/// <summary>
/// Calculates the Standard Error of the regression, given a sequence of
/// modeled/predicted values, and a sequence of actual/observed values
/// </summary>
/// <param name="modelledValues">The modelled/predicted values</param>
/// <param name="observedValues">The observed/actual values</param>
/// <returns>The Standard Error of the regression</returns>
public static double PopulationStandardError(IEnumerable<double> modelledValues, IEnumerable<double> observedValues)
{
return SampleStandardError(modelledValues, observedValues, 0);
}
/// <summary>
/// Calculates the Standard Error of the regression, given a sequence of
/// modeled/predicted values, and a sequence of actual/observed values
/// </summary>
/// <param name="modelledValues">The modelled/predicted values</param>
/// <param name="observedValues">The observed/actual values</param>
/// <param name="degreesOfFreedom">The degrees of freedom by which the
/// number of samples is reduced for performing the Standard Error calculation</param>
/// <returns>The Standard Error of the regression</returns>
public static double SampleStandardError(IEnumerable<double> modelledValues, IEnumerable<double> observedValues, int degreesOfFreedom)
{
using (IEnumerator<double> ieM = modelledValues.GetEnumerator())
using (IEnumerator<double> ieO = observedValues.GetEnumerator())
{
double n = 0;
double accumulator = 0;
while (ieM.MoveNext())
{
if (!ieO.MoveNext())
{
throw new ArgumentOutOfRangeException("modelledValues", Resources.ArgumentArraysSameLength);
}
double currentM = ieM.Current;
double currentO = ieO.Current;
var diff = currentM - currentO;
accumulator += diff * diff;
n++;
}
if (degreesOfFreedom >= n)
{
throw new ArgumentOutOfRangeException("degreesOfFreedom", Resources.DegreesOfFreedomMustBeLessThanSampleSize);
}
return Math.Sqrt(accumulator / (n - degreesOfFreedom));
}
}
} }
} }

9
src/Numerics/Properties/Resources.Designer.cs

@ -602,6 +602,15 @@ namespace MathNet.Numerics.Properties {
} }
} }
/// <summary>
/// Looks up a localized string similar to The sample size must be larger than the given degrees of freedom..
/// </summary>
public static string DegreesOfFreedomMustBeLessThanSampleSize {
get {
return ResourceManager.GetString("DegreesOfFreedomMustBeLessThanSampleSize", resourceCulture);
}
}
/// <summary> /// <summary>
/// Looks up a localized string similar to This feature is not implemented yet (but is planned).. /// Looks up a localized string similar to This feature is not implemented yet (but is planned)..
/// </summary> /// </summary>

3
src/Numerics/Properties/Resources.resx

@ -445,4 +445,7 @@
<data name="SampleVectorsSameLength" xml:space="preserve"> <data name="SampleVectorsSameLength" xml:space="preserve">
<value>All sample vectors must have the same length. However, vectors with disagreeing length {0} and {1} have been provided. A sample with index i is given by the value at index i of each provided vector.</value> <value>All sample vectors must have the same length. However, vectors with disagreeing length {0} and {1} have been provided. A sample with index i is given by the value at index i of each provided vector.</value>
</data> </data>
<data name="DegreesOfFreedomMustBeLessThanSampleSize" xml:space="preserve">
<value>The sample size must be larger than the given degrees of freedom.</value>
</data>
</root> </root>

86
src/UnitTests/GoodnessOfFit/StandardErrorTest.cs

@ -0,0 +1,86 @@
// <copyright file="StandardErrorTest.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2013 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
using System;
using System.Linq;
using NUnit.Framework;
namespace MathNet.Numerics.UnitTests.GoodnessOfFit
{
[TestFixture, Category("Regression")]
public class StandardErrorTest
{
[Test]
public void ComputesPopulationStandardErrorOfTheRegression()
{
// Definition as described at: http://onlinestatbook.com/lms/regression/accuracy.html
var xes = new[] { 1.0, 2, 3, 4, 5 };
var ys = new[] { 1, 2, 1.3, 3.75, 2.25 };
var fit = Fit.Line(xes, ys);
var a = fit.Item1;
var b = fit.Item2;
var predictedYs = xes.Select(x => a + b * x);
var standardError = Numerics.GoodnessOfFit.PopulationStandardError(predictedYs, ys);
Assert.AreEqual(0.747, standardError, 1e-3);
}
[Test]
public void ComputesSampleStandardErrorOfTheRegression()
{
// Definition as described at: http://onlinestatbook.com/lms/regression/accuracy.html
var xes = new[] { 1.0, 2, 3, 4, 5 };
var ys = new[] { 1, 2, 1.3, 3.75, 2.25 };
var fit = Fit.Line(xes, ys);
var a = fit.Item1;
var b = fit.Item2;
var predictedYs = xes.Select(x => a + b * x);
var standardError = Numerics.GoodnessOfFit.SampleStandardError(predictedYs, ys, degreesOfFreedom: 2);
Assert.AreEqual(0.964, standardError, 1e-3);
}
[Test]
public void PopulationStandardErrorShouldThrowIfInputsSequencesDifferInLength()
{
var y1 = new[] { 0.0, 1 };
var y2 = new[] { 1.0 };
Assert.Throws<ArgumentOutOfRangeException>(() => Numerics.GoodnessOfFit.PopulationStandardError(y1, y2));
}
[Test]
public void SampleStandardErrorShouldThrowIfSampleSizeIsSmallerThanGivenDegreesOfFreedom()
{
var modelled = new[] { 1.0 };
var observed = new[] { 1.0 };
Assert.Throws<ArgumentOutOfRangeException>(() => Numerics.GoodnessOfFit.SampleStandardError(modelled, observed, 2));
}
}
}

1
src/UnitTests/UnitTests.csproj

@ -142,6 +142,7 @@
<Compile Include="FinancialTests\SemiDeviationTests.cs" /> <Compile Include="FinancialTests\SemiDeviationTests.cs" />
<Compile Include="GenerateTests.cs" /> <Compile Include="GenerateTests.cs" />
<Compile Include="GoodnessOfFit\RSquaredTest.cs" /> <Compile Include="GoodnessOfFit\RSquaredTest.cs" />
<Compile Include="GoodnessOfFit\StandardErrorTest.cs" />
<Compile Include="Providers\FourierTransform\FourierTransformProviderTests.cs" /> <Compile Include="Providers\FourierTransform\FourierTransformProviderTests.cs" />
<Compile Include="IntegralTransformsTests\FourierTest.cs" /> <Compile Include="IntegralTransformsTests\FourierTest.cs" />
<Compile Include="IntegralTransformsTests\HartleyTest.cs" /> <Compile Include="IntegralTransformsTests\HartleyTest.cs" />

Loading…
Cancel
Save