PHP code example of ankane / libmf

1. Go to this page and download the library: Download ankane/libmf 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/ */

    

ankane / libmf example snippets


$data = new Libmf\Matrix();
$data->push(0, 0, 5.0);
$data->push(0, 2, 3.5);
$data->push(1, 1, 4.0);

$model = new Libmf\Model();
$model->fit($data);

$model->predict($rowIndex, $columnIndex);

$model->p();
$model->q();

$model->bias();

$model->save('model.txt');

$model = Libmf\Model::load('model.txt');

$model->fit($data, $validSet);

$model->cv($data);

$model->cv($data, 5);

use Libmf\Loss;

new Libmf\Model(
    loss: Loss::RealL2,     // loss function
    factors: 8,             // number of latent factors
    threads: 12,            // number of threads used
    bins: 25,               // number of bins
    iterations: 20,         // number of iterations
    lambdaP1: 0,            // coefficient of L1-norm regularization on P
    lambdaP2: 0.1,          // coefficient of L2-norm regularization on P
    lambdaQ1: 0,            // coefficient of L1-norm regularization on Q
    lambdaQ2: 0.1,          // coefficient of L2-norm regularization on Q
    learningRate: 0.1,      // learning rate
    alpha: 1,               // importance of negative entries
    c: 0.0001,              // desired value of negative entries
    nmf: false,             // perform non-negative MF (NMF)
    quiet: false            // no outputs to stdout
);

$model->rmse($data);

$model->mae($data);

$model->gkl($data);

$model->logloss($data);

$model->accuracy($data);

$model->mpr($data, $transpose);

$model->auc($data, $transpose);

$trainSet = new Libmf\Matrix();
$validSet = new Libmf\Matrix();

if (($handle = fopen('u.data', 'r')) !== false) {
    $i = 0;
    while (($row = fgetcsv($handle, separator: "\t")) !== false) {
        $data = $i < 80000 ? $trainSet : $validSet;
        $data->push($row[0], $row[1], $row[2]);
        $i++;
    }
    fclose($handle);
}

$model = new Libmf\Model(factors: 20);
$model->fit($trainSet, $validSet);

echo $model->rmse($validSet), "\n";
sh
git clone https://github.com/ankane/libmf-php.git
cd libmf-php
composer install
composer test