C ++中的加权方差和加权标准差

时间:2013-05-26 17:41:27

标签: c++ templates variance weighted standard-deviation

您好我正在尝试计算一系列整数或浮点数的加权方差和加权标准差。我找到了这些链接:

http://math.tutorvista.com/statistics/standard-deviation.html#weighted-standard-deviation

http://www.itl.nist.gov/div898/software/dataplot/refman2/ch2/weightsd.pdf(警告pdf)

到目前为止,这是我的模板功能。方差和标准差工作正常,但对于我的生活,我无法得到加权版本以匹配pdf底部的测试用例:

template <class T>
inline float    Mean( T samples[], int count )
{
    float   mean = 0.0f;

    if( count >= 1 )
    {
        for( int i = 0; i < count; i++ )
            mean += samples[i];

        mean /= (float) count;
    }

    return mean;
}

template <class T>
inline float    Variance( T samples[], int count )
{
    float   variance = 0.0f;

    if( count > 1 )
    {
        float   mean = 0.0f;

        for( int i = 0; i < count; i++ )
            mean += samples[i];

        mean /= (float) count;

        for( int i = 0; i < count; i++ )
        {
            float   sum = (float) samples[i] - mean;

            variance += sum*sum;
        }

        variance /= (float) count - 1.0f;
    }

    return variance;
}

template <class T>
inline float    StdDev( T samples[], int count )
{
    return sqrtf( Variance( samples, count ) );
}

template <class T>
inline float    VarianceWeighted( T samples[], T weights[], int count )
{
    float   varianceWeighted = 0.0f;

    if( count > 1 )
    {
        float   sumWeights = 0.0f, meanWeighted = 0.0f;
        int     numNonzero = 0;

        for( int i = 0; i < count; i++ )
        {
            meanWeighted += samples[i]*weights[i];
            sumWeights += weights[i];

            if( ((float) weights[i]) != 0.0f ) numNonzero++;
        }

        if( sumWeights != 0.0f && numNonzero > 1 )
        {
            meanWeighted /= sumWeights;

            for( int i = 0; i < count; i++ )
            {
                float   sum = samples[i] - meanWeighted;

                varianceWeighted += weights[i]*sum*sum;
            }

            varianceWeighted *= ((float) numNonzero)/((float) count*(numNonzero - 1.0f)*sumWeights);    // this should be right but isn't?!
        }
    }

    return varianceWeighted;
}

template <class T>
inline float    StdDevWeighted( T samples[], T weights[], int count )
{
    return sqrtf( VarianceWeighted( samples, weights, count ) );
}

测试用例:

int     samples[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23 };

printf( "%.2f\n", StdDev( samples, 9 ) );

int     weights[] = { 1, 1, 0, 0, 4, 1, 2, 1, 0 };

printf( "%.2f\n", StdDevWeighted( samples, weights, 9 ) );

结果:

7.46
1.94

应该是:

7.46
5.82

我认为问题在于加权方差有一些不同的解释,我不知道哪一个是标准的。我发现了这种变化:

http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Weighted_incremental_algorithm

template <class T>
inline float    VarianceWeighted( T samples[], T weights[], int count )
{
    float   varianceWeighted = 0.0f;

    if( count > 1 )
    {
        float   sumWeights = 0.0f, meanWeighted = 0.0f, m2 = 0.0f;

        for( int i = 0; i < count; i++ )
        {
            float   temp = weights[i] + sumWeights,
                    delta = samples[i] - meanWeighted,
                    r = delta*weights[i]/temp;

            meanWeighted += r;
            m2 += sumWeights*delta*r;   // Alternatively, m2 += weights[i] * delta * (samples[i]−meanWeighted)
            sumWeights = temp;
        }

        varianceWeighted = (m2/sumWeights)*((float) count/(count - 1));
    }

    return varianceWeighted;
}

结果:

7.46
5.64

我也尝试过看看boost和esutil但是他们没有多大帮助:

http://www.boost.org/doc/libs/1_48_0/boost/accumulators/statistics/weighted_variance.hpp http://esutil.googlecode.com/svn-history/r269/trunk/esutil/stat/util.py

我不需要整个统计库,更重要的是,我想了解实现。

有人可以发布功能来正确计算这些吗?

奖励积分,如果您的功能可以一次性完成。

此外,是否有人知道加权方差是否与重复值的普通方差相同?例如,样本[] = {1,2,3,3}的方差是否与样本的加权方差相同[] = {1,2,3},权重[] = {1,1,2}吗

更新:这是我设置的谷歌文档电子表格,用于探索问题。不幸的是,我的答案与NIST pdf无关。我认为问题出在unbias步骤,但我看不出如何解决它。

https://docs.google.com/spreadsheet/ccc?key=0ApzPh5nRin0ldGNNYjhCUTlWTks2TGJrZW4wQUcyZnc&usp=sharing

结果的加权方差为3.77,这是我在c ++代码中得到的加权标准差为1.94的平方。

我正在尝试在我的Mac OS X设置上安装八度音,这样我就可以使用权重运行他们的var()函数,但是它需要永远用brew安装它。我现在已深入yak shaving

3 个答案:

答案 0 :(得分:3)

float mean(uint16_t* x, uint16_t n) {
    uint16_t sum_xi = 0;
    int i;
    for (i = 0; i < n; i++) {
        sum_xi += x[i];
    }
    return (float) sum_xi / n;
}

/**
 * http://www.itl.nist.gov/div898/software/dataplot/refman2/ch2/weigmean.pdf
 */
float weighted_mean(uint16_t* x, uint16_t* w, uint16_t n) {
    int sum_wixi = 0;
    int sum_wi = 0;
    int i;
    for (i = 0; i < n; i++) {
        sum_wixi += w[i] * x[i];
        sum_wi += w[i];
    }
    return (float) sum_wixi / (float) sum_wi;
}

float variance(uint16_t* x, uint16_t n) {
    float mean_x = mean(x, n);
    float dist, dist2;
    float sum_dist2 = 0;

    int i;
    for (i = 0; i < n; i++) {
        dist = x[i] - mean_x;
        dist2 = dist * dist;
        sum_dist2 += dist2;
    }

    return sum_dist2 / (n - 1);
}

/**
 * http://www.itl.nist.gov/div898/software/dataplot/refman2/ch2/weighvar.pdf
 */
float weighted_variance(uint16_t* x, uint16_t* w, uint16_t n) {
    float xw = weighted_mean(x, w, n);
    float dist, dist2;
    float sum_wi_times_dist2 = 0;
    int sum_wi = 0;
    int n_prime = 0;

    int i;
    for (i = 0; i < n; i++) {
        dist = x[i] - xw;
        dist2 = dist * dist;
        sum_wi_times_dist2 += w[i] * dist2;
        sum_wi += w[i];

        if (w[i] > 0)
            n_prime++;
    }

    if (n_prime > 1) {
        return sum_wi_times_dist2 / ((float) ((n_prime - 1) * sum_wi) / n_prime);
    } else {
        return 0.0f;
    }
}

/**
 * http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Weighted_incremental_algorithm
 */
float weighted_incremental_variance(uint16_t* x, uint16_t* w, uint16_t n) {
    uint16_t sumweight = 0;
    float mean = 0;
    float M2 = 0;
    int n_prime = 0;

    uint16_t temp;
    float delta;
    float R;

    int i;
    for (i = 0; i < n; i++) {
        if (w[i] == 0)
            continue;

        temp = w[i] + sumweight;
        delta = x[i] - mean;
        R = delta * w[i] / temp;
        mean += R;
        M2 += sumweight * delta * R;
        sumweight = temp;

        n_prime++;
    }

    if (n_prime > 1) {
        float variance_n = M2 / sumweight;
        return variance_n * n_prime / (n_prime - 1);
    } else {
        return 0.0f;
    }
}

void main(void) {
    uint16_t n = 9;
    uint16_t x[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23 };
    uint16_t w[] = { 1, 1, 0, 0,  4,  1,  2,  1,  0 };

    printf("%f\n", weighted_variance(x, w, n)); /* outputs: 33.900002 */
    printf("%f\n", weighted_incremental_variance(x, w, n)); /* outputs: 33.900005 */
}

答案 1 :(得分:0)

解决方案

您在方差更新字词的分母中意外添加了一个额外的术语“计数”。

使用下面的更正时,我会得到您预期的答案

5.82

仅供参考,在进行代码审查时,采用这种方法的一种方法是进行“维度分析”。等式的“单位”是错误的。当你应该是一个N阶项时,你实际上除以了一个N阶平方项。

之前

template <class T>
inline float    VarianceWeighted( T samples[], T weights[], int count )
{
    ...
            varianceWeighted *= ((float) numNonzero)/((float) count*(numNonzero - 1.0f)*sumWeights);    // this should be right but isn't?!
    ...
}

删除“计数”此行应替换为

template <class T>
inline float    VarianceWeighted( T samples[], T weights[], int count )
{
    ...
            varianceWeighted *= ((float) numNonzero)/((float) (numNonzero - 1.0f)*sumWeights);  // removed count term
    ...
}

答案 2 :(得分:0)

这是一个简短得多的版本,具有有效的 Demo

 #include <iostream>
 #include <vector>
 #include <boost/accumulators/accumulators.hpp>
 #include <boost/accumulators/statistics/stats.hpp>
 #include <boost/accumulators/statistics/weighted_variance.hpp>
 #include <boost/accumulators/statistics/variance.hpp>

 namespace ba = boost::accumulators;

 int main() {
     std::vector<double> numbers{2, 3, 5, 7, 11, 13, 17, 19, 23};
     std::vector<double> weights{1, 1, 0, 0,  4,  1,  2,  1, 0 };

     ba::accumulator_set<double, ba::stats<ba::tag::variance          >          > acc;
     ba::accumulator_set<double, ba::stats<ba::tag::weighted_variance > , double > acc_weighted;

     double n = numbers.size();
     double N = n;

     for(size_t i = 0 ; i<numbers.size() ; i++ ) {
         acc         ( numbers[i] );
         acc_weighted( numbers[i] ,   ba::weight = weights[i] );
         if(weights[i] == 0) {
             n=n-1;
         }
     };

     std::cout << "Sample Standard Deviation, s: "          << std::sqrt(ba::variance(acc)                  *N/(N-1))        << std::endl;
     std::cout << "Weighted Sample Standard Deviation, s: " << std::sqrt(ba::weighted_variance(acc_weighted)*n/(n-1))        << std::endl;
 }

请注意,n必须反映权重非零的样本数,因此要额外添加n=n-1;行。

Sample Standard Deviation, s: 7.45729
Weighted Sample Standard Deviation, s: 5.82237