概要
閲覧数:1382
投稿日:2015-12-31
更新日:2016-01-02
P1とP2のピアソン相関係数を返す
リンク先からの変更点
・'Michael Phillips' の 'The Night Listener' 評価を 3.0 から 4.0 へ変更
コード
$critics = array( 'Lisa Rose' => array( 'Lady in the Water' => 2.5, 'Snakes on a Plane' => 3.5, 'Just My Luck' => 3.0, 'Superman Returns' => 3.5, 'You, Me and Dupree' => 2.5, 'The Night Listener' => 3.0, ), 'Gene Seymour' => array( 'Lady in the Water' => 3.0, 'Snakes on a Plane' => 3.5, 'Just My Luck' => 1.5, 'Superman Returns' => 5.0, 'You, Me and Dupree' => 3.5, 'The Night Listener' => 3.0, ), 'Michael Phillips' => array( 'Lady in the Water' => 2.5, 'Snakes on a Plane' => 3.0, 'Superman Returns' => 3.5, 'The Night Listener' => 4.0, ), 'Claudia Puig' => array( 'Snakes on a Plane' => 3.5, 'Just My Luck' => 3.0, 'Superman Returns' => 4.0, 'You, Me and Dupree' => 2.5, 'The Night Listener' => 4.5, ), 'Mick LaSalle' => array( 'Lady in the Water' => 3.0, 'Snakes on a Plane' => 4.0, 'Just My Luck' => 2.0, 'Superman Returns' => 3.0, 'You, Me and Dupree' => 2.0, 'The Night Listener' => 3.0, ), 'Jack Matthews' => array( 'Lady in the Water' => 3.0, 'Snakes on a Plane' => 4.0, 'Superman Returns' => 5.0, 'You, Me and Dupree' => 3.5, 'The Night Listener' => 3.0, ), 'Toby' => array( 'Snakes on a Plane' => 4.5, 'Superman Returns' => 4.0, 'You, Me and Dupree' => 1.0, ), ); //P1とP2のピアソン相関係数を返す。 function sim_pearson($prefs,$p1,$p2){ //両者が互いに評価しているアイテムのリストを取得 $si = array(); foreach($prefs["$p1"] as $item => $val){ if(isset($prefs["$p2"]["$item"])){ $si["$item"] = 1; } } //要素の数を調べる。 $n = count($si); //すべての嗜好,平方,積を合計する //嗜好の合計 $sum1 = 0; $sum2 = 0; //平方の合計 $sum1Sq = 0; $sum2Sq = 0; //積の合計 $pSum = 0; foreach($si as $item => $val){ $sum1 += $prefs["$p1"]["$item"]; $sum2 += $prefs["$p2"]["$item"]; $sum1Sq += pow($prefs["$p1"]["$item"],2); $sum2Sq += pow($prefs["$p2"]["$item"],2); $pSum += $prefs["$p1"]["$item"] * $prefs["$p2"]["$item"]; } //ピアソンスコアを計算する $num = $pSum - ($sum1 * $sum2 / $n); $den = sqrt(($sum1Sq - pow($sum1,2) / $n) * ($sum2Sq - pow($sum2,2) / $n)); if($den == 0){ return 0;} $r = $num / $den; return $r; } var_dump( sim_pearson($critics,'Lisa Rose','Gene Seymour') ); //float(0.39605901719067) var_dump( sim_pearson($critics,'Lisa Rose','Lisa Rose') ); //float(1) var_dump( sim_pearson($critics,'Lisa Rose','Toby') ); //float(0.99124070716193)
結果
float(0.39605901719067) float(1) float(0.99124070716193)