Free cookie consent management tool by TermsFeed Policy Generator

Ignore:
Timestamp:
03/05/15 10:22:03 (10 years ago)
Author:
gkronber
Message:

#2351 added kernel density calculation

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/sources/HeuristicLab.Analysis/3.3/Statistics/NormalDistribution.cs

    r12012 r12134  
    2828  public static class NormalDistribution {
    2929    public static double[] Density(double[] x, double mean, double stdDev) {
    30       double[] result = new double[x.Length];
     30      return x.Select(xi => Density(xi, mean, stdDev)).ToArray();
     31    }
    3132
    32       for (int i = 0; i < x.Length; i++) {
    33         result[i] = (1.0 / (stdDev * Math.Sqrt(2.0 * Math.PI))) *
    34                     Math.Exp(-((Math.Pow(x[i] - mean, 2.0)) /
    35                                (2.0 * Math.Pow(stdDev, 2.0))));
    36       }
    37 
    38       return result;
     33    public static double Density(double x, double mean, double stdDev) {
     34      return (1.0 / (stdDev * Math.Sqrt(2.0 * Math.PI))) *
     35                  Math.Exp(-((Math.Pow(x - mean, 2.0)) /
     36                             (2.0 * Math.Pow(stdDev, 2.0))));
    3937    }
    4038
    4139    // based on the idea from http://www.statmethods.net/graphs/density.html
    4240    public static List<Tuple<double, double>> Density(double[] x, int nrOfPoints, double stepWidth) {
     41      // calculate grid for which to estimate the density
    4342      double[] newX = new double[nrOfPoints];
    44       double mean = x.Average();
    45       double stdDev = x.StandardDeviation();
    4643      double margin = stepWidth * 2;
    4744
     
    5653      }
    5754
    58       var y = Density(newX, mean, stdDev).Select(k => k * stepWidth * x.Length).ToList();
     55      // the scale (std.-dev. of the kernel is a parameter)
     56      var sigma = 1.0; // TODO allow configuration in the view
     57      // for each of the points for which we want to calculate the density
     58      // we sum up all the densities of the observed points assuming they are at the center of a normal distribution
     59      var y = from xi in newX
     60              select (from obsX in x
     61                      select Density(xi, obsX, sigma)).Sum();
    5962
    60       var points = new List<Tuple<double, double>>();
    61       for (int i = 0; i < newX.Length; i++) {
    62         points.Add(new Tuple<double, double>(newX[i], y[i]));
    63       }
    64 
    65       return points;
     63      return newX.Zip(y, Tuple.Create).ToList();
    6664    }
    6765  }
Note: See TracChangeset for help on using the changeset viewer.