php - 我的 PHP PIL 逊相关系数代码有什么问题

标签 php algorithm math correlation

所以我试图在 PHP 中实现样本 Pearson 相关系数:

(转到 http://en.wikipedia.org/wiki/Pearson_correlation_coefficient 并搜索“样本 Pearson 相关系数的替代公式也可用”以获取我尝试实现的特定公式)

   $sum = 0;
   $TF1 = 0;
   $TF2 = 0;
   $wSquare1 = 0;
   $wSquare2 = 0;
   $m = sizeof($sample);
   foreach($sample as $x){
      if(!isset($obj1[$x])){
         $obj1[$x]['count'] = 0;
      }
      if(!isset($obj2[$x])){
         $obj2[$x]['count'] = 0;
      }
      $sum += $obj1[$x]['count'] * $obj2[$x]['count'];
      $TF1 += $obj1[$x]['count'];
      $TF2 += $obj2[$x]['count'];
      $wSquare1 += $obj1[$x]['count']^2;
      $wSquare2 += $obj2[$x]['count']^2;
   }
   $numer = $sum * $m - $TF1 * $TF2;
   $denom_left = $m*$wSquare1 - $TF1^2;
   $denom_right = $m*$wSquare2 - $TF2^2;
   $denom = sqrt($denom_left) * sqrt($denom_right);
   $pears = $numer / $denom;
   return $pears;

但有时我的代码会返回一个大于 1 的值,而 PCC 不应超过 1....

我做错了什么吗?

最佳答案

我还没有完全检查你的数学,但我突然想到的一件事是 $TF1^2$obj1[$x]['count']^2。他们正在使用 bitwise XOR operator .

我相信你想要 pow($TF1, 2)pow($obj1[$x]['count'], 2)

或者: $TF1 * $TF1$obj1[$x]['count'] * $obj1[$x]['count']

这是一个常见的错误。

另请注意文章中的免责声明:

The above formula suggests a convenient single-pass algorithm for calculating sample correlations, but, depending on the numbers involved, it can sometimes be numerically unstable.

关于php - 我的 PHP PIL 逊相关系数代码有什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7440810/

相关文章:

php - 在php中登录后重定向页面

PHP - MySQL IF( bool )条件

php mysql 查询输出文件

c# - 获得最大的不重叠对象算法(x,y,宽度,高度)

c - 一种在两个 10 位数字之间找到正交路径的算法

c - 完美数字错误?

php - fatal error : Allowed memory size of 134217728 bytes exhausted (tried to allocate 87 bytes)

algorithm - 找到最接近其他点的点

Python - 计算形式 1/r 总和为 1 的 k 个分数的算法

math - 使用 SVG 渐变为三角形 "naturally"着色