2013-01-20 27 views
2

我試圖通過MySQL和PHP在上週獲得最高評價的照片。我發現貝葉斯公式可能是我需要的,但我一直在搞這個無濟於事。貝葉斯算法返回0

以下代碼不返回任何錯誤,它只返回單個'0'。爲什麼這是我沒有絲毫的。

$bayesian_algo = "SELECT 
      photo_id, 
      (SELECT count(photo_id) FROM photo_ratings)/
(SELECT count(DISTINCT photo_id) FROM photo_ratings) AS avg_num_votes, 
      (SELECT avg(rating) FROM photo_ratings) AS avg_rating, 
      count(photo_id) as this_num_votes, 
      avg(rating) as this_rating 
      FROM photo_ratings 
      WHERE `date` > '$timeframe' 
      GROUP BY photo_id"; 

$bayesian_info = $mysqli->query($bayesian_algo); 

$all_bayesian_info = array(); 
while($row=$bayesian_info->fetch_assoc()) array_push($all_bayesian_info,$row); 

list($photo_id,$avg_num_votes,$avg_rating,$this_num_votes,$this_rating) = $all_bayesian_info; 
$photo_id = intval($photo_id); 
$avg_num_votes = intval($avg_num_votes); 
$avg_rating = intval($avg_rating); 
$this_num_votes = intval($this_num_votes); 
$this_rating = intval($this_rating); 

$bayesian_result = (($avg_num_votes * $avg_rating) + ($this_num_votes * $this_rating))/($avg_num_votes + $this_num_votes); 

echo $bayesian_result; // 0?? 

我的數據庫看起來是這樣的:

photo_id | user_id | rating | date 

所有字段存儲爲int(我存儲日期作爲UNIX時間戳)。

我累了,硬拼編碼,通常我至少可以得到一個遠一點,如果有錯誤信息(或任何東西!),但沒有辦法,我得到的數據,如果我var_dump($all_bayesian_info)將永遠返回0

+0

也許你以前錯了? – wildplasser

回答

2

讓我們在mysql查詢本身中做複雜的貝葉斯計算!

的代碼可以寫成這樣:

$bayesian_algo_result = "SELECT *, 
(((resultdata.avg_num_votes * resultdata.avg_rating) + (resultdata.this_num_votes * resultdata.this_rating))/(resultdata.avg_num_votes + resultdata.this_num_votes)) AS bayesian_result 
FROM 
( 
SELECT 
    photo_id, 
    (SELECT count(photo_id) FROM photo_ratings)/
     (SELECT count(DISTINCT photo_id) FROM photo_ratings) AS avg_num_votes, 
    (SELECT avg(rating) FROM photo_ratings) AS avg_rating, 
    count(photo_id) as this_num_votes, 
    avg(rating) as this_rating  
FROM photo_ratings 
WHERE `date` > '$timeframe' 
GROUP BY photo_id 
) AS resultdata; 
"; 

$bayesian_result_info = $mysqli->query($bayesian_algo_result); 

//loop through the rows. 
while($row = $bayesian_result_info->fetch_assoc()) { 
    list(
     $photo_id, 
     $avg_num_votes, 
     $avg_rating, 
     $this_num_votes, 
     $this_rating, 
     $bayesian_result 
    ) = $row; 

    echo 'Balesian rating for photo' . $photo_id . ' is: ' . $bayesian_result; 
} 

注:

  • 這裏是一個工作的SQL小提琴:http://sqlfiddle.com/#!2/d4a71/1/0

  • 我因此未作任何邏輯改變你公式。所以請確保你的公式是正確的。

  • 如果/當UNIX時間戳轉爲64位數據類型,那麼您將不得不使用MySQL「bigint」來存儲它們(用於'日期'列)。
+1

嗨@Jaxo請讓我知道這是否有幫助。 – OMG

+0

當然,我會在我的工作電腦上試用它!感謝你! – Scott

+0

它完美的作品,非常感謝你!我稍微修改它,所以它按貝葉斯結果排序,將其更改爲'AS resultdata ORDER BY bayesian_result DESC;' – Scott