2

MySQLとPHPを使用して、先週中に最も評価の高い写真を取得しようとしています。ベイズの定理が私に必要なものかもしれないことを私は見つけました、しかし私はそれをいじって無駄にしました。

次のコードはエラーを返さず、単一の「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を返す場合に取得するデータはありません。

4

1 に答える 1

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」を使用して(「日付」列に)保存する必要があります。
于 2013-01-20T05:49:42.087 に答える