gpt4 book ai didi

c# - 性能数组乘法 Pearson

转载 作者:行者123 更新时间:2023-11-30 20:36:35 24 4
gpt4 key购买 nike

我计算 Pearson correlation (平均用户/项目评级)很多次,使用我当前的代码性能非常糟糕:

public double ComputeCorrelation(double[] x, double[] y, double[] meanX, double[] meanY)
{
if (x.Length != y.Length)
throw new ArgumentException("values must be the same length");

double sumNum = 0;
double sumDenom = 0;
double denomX = 0;
double denomY = 0;

for (int a = 0; a < x.Length; a++)
{
sumNum += (x[a] - meanX[a]) * (y[a] - meanY[a]);
denomX += Math.Pow(x[a] - meanX[a], 2);
denomY += Math.Pow(y[a] - meanY[a], 2);
}

var sqrtDenomX = Math.Sqrt(denomX);
var sqrtDenomY = Math.Sqrt(denomY);

if (sqrtDenomX == 0 || sqrtDenomY == 0) return 0;

sumDenom = Math.Sqrt(denomX) * Math.Sqrt(denomY);

var correlation = sumNum / sumDenom;

return correlation;
}

我将标准 Pearson 相关系数与 MathNet.Numerics 一起使用,但这是对标准的修改,无法使用它。有没有办法加快速度?如何在时间复杂度方面对其进行优化?

最佳答案

添加一些关于 MSE 的答案——将 Pow(x,2) 更改为 diff*diff 绝对是您想要做的事情,您可能还想避免不必要的在最内层循环中进行边界检查。这可以使用 pointers in C# 来完成.

可以这样做:

    public unsafe double ComputeCorrelation(double[] x, double[] y, double[] meanX, double[] meanY)
{
if (x.Length != y.Length)
throw new ArgumentException("values must be the same length");

double sumNum = 0;
double sumDenom = 0;
double denomX = 0;
double denomY = 0;
double diffX;
double diffY;

int len = x.Length;

fixed (double* xptr = &x[0], yptr = &y[0], meanXptr = &meanX[0], meanYptr = &meanY[0])
{
for (int a = 0; a < len; a++)
{
diffX = (xptr[a] - meanXptr[a]);
diffY = (yptr[a] - meanYptr[a]);
sumNum += diffX * diffY;
denomX += diffX * diffX;
denomY += diffY * diffY;
}
}

var sqrtDenomX = Math.Sqrt(denomX);
var sqrtDenomY = Math.Sqrt(denomY);

if (sqrtDenomX == 0 || sqrtDenomY == 0) return 0;

sumDenom = sqrtDenomX * sqrtDenomY;

var correlation = sumNum / sumDenom;

return correlation;
}

关于c# - 性能数组乘法 Pearson,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36777383/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com