Deji
Deji

Reputation: 777

PHP Bayesian Rating System (Based On Popular Vote)

I'm working on a Bayesian rating system in PHP, but it only half works. The idea is that a low rating is devalued if most of the other members are giving high ratings, etc. It's taken me ages to get to this point, but now I'm completely stumped.

This is just a test script to figure the math out (I'm not so good with math) before I go ahead and set up the database entries.

<?php

// Item 1 votes
$ratings[0][1] = 10;
$ratings[0][2] = 4;
$ratings[0][3] = 1;
$ratings[0][4] = 72;
$ratings[0][5] = 853;       // z0mg, lots of people think this is 5 star material!

// Item 2 votes - it's 50:50, rating should be 3
$ratings[1][1] = 1000;
$ratings[1][2] = 1;
$ratings[1][3] = 1;
$ratings[1][4] = 1;
$ratings[1][5] = 1000;

// Item 3 votes - should also be 3
$ratings[2][1] = 1000;
$ratings[2][2] = 1000;
$ratings[2][3] = 1000;
$ratings[2][4] = 1000;
$ratings[2][5] = 1000;

// Item 4 votes - obviously the best thing ever
$ratings[3][1] = 0;
$ratings[3][2] = 0;
$ratings[3][3] = 0;
$ratings[3][4] = 0;
$ratings[3][5] = 99999999999;

foreach($ratings as $rating)
{
    $total_votes = $rating[1] + $rating[2] + $rating[3] + $rating[4] + $rating[5];

    $weight[1] = $rating[1] / $total_votes;
    $weight[2] = $rating[2] / $total_votes;
    $weight[3] = $rating[3] / $total_votes;
    $weight[4] = $rating[4] / $total_votes;
    $weight[5] = $rating[5] / $total_votes;

    // 1.0 == $weight[5] + $weight[4] + $weight[3] + $weight[2] + $weight[1];

    $yay = $rating[1] * $weight[1];
    $yay += $rating[2] * $weight[2];
    $yay += $rating[3] * $weight[3];
    $yay += $rating[4] * $weight[4];
    $yay += $rating[5] * $weight[5];

    echo ($yay / $total_votes) * 5;
    echo "\n";
}

/*
    RESULTS
    4.1472951561793
    2.4925205800884
    1
    5
*/

?>

But of course, the rating of items 2 and 3 should both be 3.0...

Hope someone can help.

Upvotes: 1

Views: 679

Answers (1)

crazyphoton
crazyphoton

Reputation: 623

This is not really a php question. The mistake is with the algorithm.

Anyways, change to:

$yay = 1 * $weight[1];
$yay += 2 * $weight[2];
$yay += 3 * $weight[3];
$yay += 4 * $weight[4];
$yay += 5 * $weight[5];
echo $yay

Should work.

Upvotes: 1

Related Questions