首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >贝叶斯算法返回0

贝叶斯算法返回0
EN

Stack Overflow用户
提问于 2013-01-20 08:32:58
回答 1查看 293关注 0票数 2

我试着通过MySQL和PHP获取上周排名最靠前的照片。我发现贝叶斯公式可能就是我所需要的,但我一直在弄它,但却一无所获。

下面的代码不返回任何错误,它只返回一个'0‘。这就是为什么我一点也没有。

代码语言:javascript
复制
$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??

我的数据库如下所示:

代码语言:javascript
复制
photo_id | user_id | rating | date

其中所有字段都存储为INTs (我将date存储为UNIX时间戳)。

我太累了,编码也不计后果,正常情况下,如果有错误消息(或任何消息),我至少可以得到更多信息,但是如果我使用var_dump($all_bayesian_info),我得到的数据不可能返回0。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-01-20 13:49:42

让我们在mysql查询本身中进行复杂的贝叶斯计算!

代码可以像这样重写:

代码语言:javascript
复制
$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;
}

注意:

http://sqlfiddle.com/#!2/d4a71/1/0

  • I没有对你的公式做任何逻辑上的改变,这是一个有效的
  • 。因此,请确保您的公式是correct.
  • If/when UNIX时间戳转到64位数据类型,然后您将不得不使用MySQL "bigint“来存储它们(对于您的'date‘列)。
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14420494

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档