Programing

LINQ의 표준 편차

crosscheck 2020. 10. 16. 07:09
반응형

LINQ의 표준 편차


LINQ는 집계 SQL 함수 STDDEV()(표준 편차)를 모델링합니까 ?

그렇지 않다면 계산하는 가장 간단하고 모범 사례는 무엇입니까?

예:

  SELECT test_id, AVERAGE(result) avg, STDDEV(result) std 
    FROM tests
GROUP BY test_id

당신은 그것을 계산하는 자신의 확장을 만들 수 있습니다

public static class Extensions
{
    public static double StdDev(this IEnumerable<double> values)
    {
       double ret = 0;
       int count = values.Count();
       if (count  > 1)
       {
          //Compute the Average
          double avg = values.Average();

          //Perform the Sum of (value-avg)^2
          double sum = values.Sum(d => (d - avg) * (d - avg));

          //Put it all together
          ret = Math.Sqrt(sum / count);
       }
       return ret;
    }
}

당신이있는 경우 샘플 인구보다는 전체 인구의를, 당신은 사용해야합니다 ret = Math.Sqrt(sum / (count - 1));.

Chris Bennett의 LINQ에 표준 편차 추가 에서 확장으로 변환되었습니다 .


Dynami의 답변은 작동하지만 결과를 얻기 위해 데이터를 여러 번 통과합니다. 다음은 표본 표준 편차 를 계산하는 단일 통과 방법입니다 .

public static double StdDev(this IEnumerable<double> values)
{
    // ref: http://warrenseen.com/blog/2006/03/13/how-to-calculate-standard-deviation/
    double mean = 0.0;
    double sum = 0.0;
    double stdDev = 0.0;
    int n = 0;
    foreach (double val in values)
    {
        n++;
        double delta = val - mean;
        mean += delta / n;
        sum += delta * (val - mean);
    }
    if (1 < n)
        stdDev = Math.Sqrt(sum / (n - 1));

    return stdDev;
}

나누기 때문에 표본 표준 편차n - 1 입니다. 정규 표준 편차의 경우 n대신 나눌 필요가 있습니다.

이것은 방법에 비해 수치 정확도가 더 높은 Welford의 방법사용합니다 Average(x^2)-Average(x)^2.


이렇게하면 David Clarke의 답변이 Average와 같은 다른 집계 LINQ 함수와 동일한 형식을 따르는 확장으로 변환 됩니다.

사용법은 다음과 같습니다. var stdev = data.StdDev(o => o.number)

public static class Extensions
{
    public static double StdDev<T>(this IEnumerable<T> list, Func<T, double> values)
    {
        // ref: https://stackoverflow.com/questions/2253874/linq-equivalent-for-standard-deviation
        // ref: http://warrenseen.com/blog/2006/03/13/how-to-calculate-standard-deviation/ 
        var mean = 0.0;
        var sum = 0.0;
        var stdDev = 0.0;
        var n = 0;
        foreach (var value in list.Select(values))
        {
            n++;
            var delta = value - mean;
            mean += delta / n;
            sum += delta * (value - mean);
        }
        if (1 < n)
            stdDev = Math.Sqrt(sum / (n - 1));

        return stdDev; 

    }
} 

var stddev = Math.Sqrt(data.Average(z=>z*z)-Math.Pow(data.Average(),2));

요점 (및 C #> 6.0)에 대한 Dynamis 답변은 다음과 같습니다.

    public static double StdDev(this IEnumerable<double> values)
    {
        var count = values?.Count() ?? 0;
        if (count <= 1) return 0;

        var avg = values.Average();
        var sum = values.Sum(d => Math.Pow(d - avg, 2));

        return Math.Sqrt(sum / count);
    }

public static double StdDev(this IEnumerable<int> values, bool as_sample = false)
{
    var count = values.Count();
    if (count > 0) // check for divide by zero
    // Get the mean.
    double mean = values.Sum() / count;

    // Get the sum of the squares of the differences
    // between the values and the mean.
    var squares_query =
        from int value in values
        select (value - mean) * (value - mean);
    double sum_of_squares = squares_query.Sum();
    return Math.Sqrt(sum_of_squares / (count - (as_sample ? 1 : 0)))
}

참고 URL : https://stackoverflow.com/questions/2253874/standard-deviation-in-linq

반응형