计算运行标准差

Calculate the running standard deviation

本文关键字:标准差 运行 计算      更新时间:2023-10-16

我正在将方程转换为c++。对于运行标准偏差,这是否正确?

this->runningStandardDeviation = (this->sumOfProcessedSquaredSamples - sumSquaredDividedBySampleCount) / (sampleCount - 1);

完整功能如下:

void BM_Functions::standardDeviationForRunningSamples (float samples [], int sampleCount)
{
    // update the running process samples count
    this->totalSamplesProcessed += sampleCount;
    // get the mean of the samples
    double mean = meanForSamples(samples, sampleCount);
    // sum the deviations
   // sum the squared deviations
   for (int i = 0; i < sampleCount; i++)
   {
        // update the deviation sum of processed samples
        double deviation = samples[i] - mean;
        this->sumOfProcessedSamples += deviation;
        // update the squared deviations sum
        double deviationSquared = deviation * deviation;
        this->sumOfProcessedSquaredSamples += deviationSquared;
    }
    // get the sum squared
    double sumSquared = this->sumOfProcessedSamples * this->sumOfProcessedSamples;
    // get the sum/N
    double sumSquaredDividedBySampleCount = sumSquared / this->totalSamplesProcessed;
    this->runningStandardDeviation = sqrt((this->sumOfProcessedSquaredSamples -     sumSquaredDividedBySampleCount) / (sampleCount - 1));
}

计算运行均值和方差/标准差的一种数值稳定且有效的算法是Welford算法。

一个c++实现是:

std::pair<double,double> getMeanVariance(const std::vector<double>& vec) {
    double mean = 0, M2 = 0, variance = 0;
    size_t n = vec.size();
    for(size_t i = 0; i < n; ++i) {
        double delta = vec[i] - mean;
        mean += delta / (i + 1);
        M2 += delta * (vec[i] - mean);
        variance = M2 / (i + 1);
        if (i >= 2) {
            // <-- You can use the running mean and variance here 
        }
    }
    return std::make_pair(mean, variance);
}

注意:要获得SD,只需取sqrt(variance)

您可以检查是否有足够的sampleSount(1将导致除零)

确保变量具有合适的数据类型(浮点数)