PHPackages                             ankane/libmf - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. ankane/libmf

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

ankane/libmf
============

Large-scale sparse matrix factorization for PHP

v0.2.0(1y ago)638521BSD-3-ClausePHPPHP &gt;= 8.1CI passing

Since Aug 8Pushed 2mo ago1 watchersCompare

[ Source](https://github.com/ankane/libmf-php)[ Packagist](https://packagist.org/packages/ankane/libmf)[ RSS](/packages/ankane-libmf/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (1)Versions (9)Used By (1)

LIBMF PHP
=========

[](#libmf-php)

[LIBMF](https://github.com/cjlin1/libmf) - large-scale sparse matrix factorization - for PHP

Check out [Disco](https://github.com/ankane/disco-php) for higher-level collaborative filtering

[![Build Status](https://github.com/ankane/libmf-php/actions/workflows/build.yml/badge.svg)](https://github.com/ankane/libmf-php/actions)

Installation
------------

[](#installation)

Run:

```
composer require ankane/libmf
```

Add scripts to `composer.json` to download the shared library:

```
    "scripts": {
        "post-install-cmd": "Libmf\\Vendor::check",
        "post-update-cmd": "Libmf\\Vendor::check"
    }
```

And run:

```
composer install
```

Getting Started
---------------

[](#getting-started)

Prep your data in the format `rowIndex, columnIndex, value`

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

Create a model

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

Make predictions

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

Get the latent factors (these approximate the training matrix)

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

Get the bias (average of all elements in the training matrix)

```
$model->bias();
```

Save the model to a file

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

Load the model from a file

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

Pass a validation set

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

Cross-Validation
----------------

[](#cross-validation)

Perform cross-validation

```
$model->cv($data);
```

Specify the number of folds

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

Parameters
----------

[](#parameters)

Pass parameters - default values below

```
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
);
```

### Loss Functions

[](#loss-functions)

For real-valued matrix factorization

- `Loss::RealL2` - squared error (L2-norm)
- `Loss::RealL1` - absolute error (L1-norm)
- `Loss::RealKL` - generalized KL-divergence

For binary matrix factorization

- `Loss::BinaryLog` - logarithmic error
- `Loss::BinaryL2` - squared hinge loss
- `Loss::BinaryL1` - hinge loss

For one-class matrix factorization

- `Loss::OneClassRow` - row-oriented pair-wise logarithmic loss
- `Loss::OneClassCol` - column-oriented pair-wise logarithmic loss
- `Loss::OneClassL2` - squared error (L2-norm)

Metrics
-------

[](#metrics)

Calculate RMSE (for real-valued MF)

```
$model->rmse($data);
```

Calculate MAE (for real-valued MF)

```
$model->mae($data);
```

Calculate generalized KL-divergence (for non-negative real-valued MF)

```
$model->gkl($data);
```

Calculate logarithmic loss (for binary MF)

```
$model->logloss($data);
```

Calculate accuracy (for binary MF)

```
$model->accuracy($data);
```

Calculate MPR (for one-class MF)

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

Calculate AUC (for one-class MF)

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

Example
-------

[](#example)

Download the [MovieLens 100K dataset](https://grouplens.org/datasets/movielens/100k/) and use:

```
$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";
```

Resources
---------

[](#resources)

- [LIBMF: A Library for Parallel Matrix Factorization in Shared-memory Systems](https://www.csie.ntu.edu.tw/~cjlin/papers/libmf/libmf_open_source.pdf)

History
-------

[](#history)

View the [changelog](https://github.com/ankane/libmf-php/blob/master/CHANGELOG.md)

Contributing
------------

[](#contributing)

Everyone is encouraged to help improve this project. Here are a few ways you can help:

- [Report bugs](https://github.com/ankane/libmf-php/issues)
- Fix bugs and [submit pull requests](https://github.com/ankane/libmf-php/pulls)
- Write, clarify, or fix documentation
- Suggest or add new features

To get started with development:

```
git clone https://github.com/ankane/libmf-php.git
cd libmf-php
composer install
composer test
```

###  Health Score

39

—

LowBetter than 86% of packages

Maintenance60

Regular maintenance activity

Popularity24

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~133 days

Recently: every ~162 days

Total

6

Last Release

714d ago

PHP version history (2 changes)v0.1.0PHP &gt;= 8.0

v0.2.0PHP &gt;= 8.1

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/220358?v=4)[Andrew Kane](/maintainers/ankane)[@ankane](https://github.com/ankane)

---

Top Contributors

[![ankane](https://avatars.githubusercontent.com/u/220358?v=4)](https://github.com/ankane "ankane (48 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/ankane-libmf/health.svg)

```
[![Health](https://phpackages.com/badges/ankane-libmf/health.svg)](https://phpackages.com/packages/ankane-libmf)
```

###  Alternatives

[inc2734/wp-breadcrumbs

A library for WordPress breadcrumbs.

1543.1k1](/packages/inc2734-wp-breadcrumbs)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
