php或mysql提供两列之间的相关系数

时间:2016-09-29 07:14:16

标签: php mysql

有人能指点我的方向或给我一个php中的函数或mysql查询的例子,它会返回mysql表中2列之间的相关系数吗?

2 个答案:

答案 0 :(得分:2)

根据在互联网上发现的类似问题进行改编,这可能是有用的吗?

select ( avg( `col1` * `col2` ) - avg( `col1` ) + avg( `col2` ) ) / ( stddev( `col1` ) * stddev(`col2`) ) as 'correlation'
from `table`;

答案 1 :(得分:1)

最终版本完成 - 可以帮助其他人     

mysql_connect($host,$username,$password);
mysql_select_db($db_name);
$array1 = mysql_query("SELECT totalgoals FROM stats");
$array2 = mysql_query("SELECT totalshotsrecieved FROM stats");
$query = "SELECT * FROM stats";      
$result = mysql_query($query) or die(mysql_error());
$array1 = array();
$array2 = array();
while($row = mysql_fetch_array($result)){
    $array1[] = $row['totalgoals'];
    $array2[] = $row['totalshots_made'];
}
$string_version = implode($array1);
echo $string_version.'<br>';
$string_version = implode($array2);
echo $string_version.'<br>';

$correlation = Correlation($array1, $array2);

//Displaying the calculated Correlation:
print $correlation;

//The functions that work behind the scene to calculate the
//correlation

function Correlation($arr1, $arr2)
{        
    $correlation = 0;

    $k = SumProductMeanDeviation($arr1, $arr2);
    $ssmd1 = SumSquareMeanDeviation($arr1);
    $ssmd2 = SumSquareMeanDeviation($arr2);

    $product = $ssmd1 * $ssmd2;

    $res = sqrt($product);

    $correlation = $k / $res;

    return $correlation;
}

function SumProductMeanDeviation($arr1, $arr2)
{
    $sum = 0;

    $num = count($arr1);

    for($i=0; $i<$num; $i++)
    {
        $sum = $sum + ProductMeanDeviation($arr1, $arr2, $i);
    }

    return $sum;
}

function ProductMeanDeviation($arr1, $arr2, $item)
{
    return (MeanDeviation($arr1, $item) * MeanDeviation($arr2, $item));
}

function SumSquareMeanDeviation($arr)
{
    $sum = 0;

    $num = count($arr);

    for($i=0; $i<$num; $i++)
    {
        $sum = $sum + SquareMeanDeviation($arr, $i);
    }

    return $sum;
}

function SquareMeanDeviation($arr, $item)
{
    return MeanDeviation($arr, $item) * MeanDeviation($arr, $item);
}

function SumMeanDeviation($arr)
{
    $sum = 0;

    $num = count($arr);

    for($i=0; $i<$num; $i++)
    {
        $sum = $sum + MeanDeviation($arr, $i);
    }

    return $sum;
}

function MeanDeviation($arr, $item)
{
    $average = Average($arr);

    return $arr[$item] - $average;
}    

function Average($arr)
{
    $sum = Sum($arr);
    $num = count($arr);

    return $sum/$num;
}

function Sum($arr)
{
    return array_sum($arr);
}

?>