PHP code example of assisted-mindfulness / bayesian-average

1. Go to this page and download the library: Download assisted-mindfulness/bayesian-average library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

assisted-mindfulness / bayesian-average example snippets


// Item with a large number of ratings
$itemLargeRating = collect(range(0, 500))->transform(fn () => random_int(4, 5));
$itemLargeRatingAverage = $itemLargeRating->avg();
$itemLargeRatingCount = $itemLargeRating->count();

$c = 100; // Confidence number
$m = 3.5; // Catalog average

$bayes = new BayesianAverage();
$bayes
    ->setConfidenceNumber($c)
    ->setAverageRatingOfAllElements($m);

$bayes->getAverage($itemLargeRatingAverage, $itemLargeRatingCount); // ~4.3

$data = collect([
    [
        'name'          => "Item A",
        "ratings"       => [5, 4, 3, 4, 3, 2, 4, 3],
        'ratings_count' => 8,
    ],
    [
        'name'          => "Item B",
        "ratings"       => [4, 5, 5, 5, 5, 5, 5, 5, 4],
        'ratings_count' => 9,
    ],
    [
        'name'          => "Item C",
        "ratings"       => [5],
        'ratings_count' => 1,
    ],
]);

$allRatingsCount = $data->sum('ratings_count');
$sum = $data->sum(fn($item) => array_sum($item['ratings']));

$bayes = new BayesianAverage($allRatingsCount, $sum);

$bayes->setConfidenceNumber(1);

$average = array_sum($data[0]['ratings']) / count($data[0]['ratings']); // 3.5
$bayes_avg = $bayes->getAverage($average, count($data[0]['ratings'])); // 3.5802469135802 

$bayes = new BayesianAverage($allRatingsCount, $sum);

$bayes->setConfidenceNumberForEvenOrOdd($data->count(), function ($position) use ($data) {
    $item = $data->sortBy('ratings_count')->values()->get($position / 2);

    return $item['ratings_count'];
}, function ($position) use ($data) {
    $item1 = $data->sortBy('ratings_count')->values()->get(($position + 1) / 2);
    $item2 = $data->sortBy('ratings_count')->values()->get(($position - 1) / 2);

    return ($item1['ratings_count'] + $item2['ratings_count']) / 2;
});

$data->each(function ($item) use ($bayes, $sum, $allRatingsCount) {
    $average = array_sum($item['ratings']) / count($item['ratings']);
    $bayes_avg = $bayes->getAverage($average, count($item['ratings']));
    
    printf('Average = %s, Bayesian  average = %s', $average, $bayes_avg);
});

/*
 *Average = 3.5, Bayesian  average = 3.5802469135802 
 *Average = 4.7777777777778, Bayesian  average = 4.7222222222222 
 *Average = 5, Bayesian  average = 4.6111111111111 
 */