PHPackages                             niiknow/bayes - 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. niiknow/bayes

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

niiknow/bayes
=============

a machine learning lib

1.1.4(4y ago)6950.0k—2.1%14[1 PRs](https://github.com/niiknow/bayes/pulls)MITPHPPHP &gt;=7.4CI passing

Since Sep 10Pushed 3mo ago4 watchersCompare

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

READMEChangelog (6)Dependencies (1)Versions (8)Used By (0)

`bayes`: A Naive-Bayes classifier for PHP
=========================================

[](#bayes-a-naive-bayes-classifier-for-php)

[![Build Status](https://camo.githubusercontent.com/5c4d5aa37c97b73637774800d6cb1f390b200b47a9d57bf9d3d59ebc94d2c005/68747470733a2f2f7472617669732d63692e6f72672f6e69696b6e6f772f62617965732e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/niiknow/bayes)

`bayes` takes a document (piece of text), and tells you what category that document belongs to.

This library was ported from a nodejs lib @

- Proven and popular classifier in nodejs -
- We kept the json serialization signature so you can simply use the learned/trained json output from both PHP and nodejs library.

What can I use this for?
------------------------

[](#what-can-i-use-this-for)

You can use this for categorizing any text content into any arbitrary set of **categories**. For example:

- is an email **spam**, or **not spam** ?
- is a news article about **technology**, **politics**, or **sports** ?
- is a piece of text expressing **positive** emotions, or **negative** emotions?

Installing
----------

[](#installing)

```
composer require niiknow/bayes

```

Usage
-----

[](#usage)

```
$classifier = new \Niiknow\Bayes();

// teach it positive phrases

$classifier->learn('amazing, awesome movie!! Yeah!! Oh boy.', 'positive');
$classifier->learn('Sweet, this is incredibly, amazing, perfect, great!!', 'positive');

// teach it a negative phrase

$classifier->learn('terrible, shitty thing. Damn. Sucks!!', 'negative');

// now ask it to categorize a document it has never seen before

$classifier->categorize('awesome, cool, amazing!! Yay.');
// => 'positive'

// serialize the classifier's state as a JSON string.
$stateJson = $classifier->toJson();

// load the classifier back from its JSON representation.
$classifier->fromJson($stateJson);
```

API
---

[](#api)

### `$classifier = new \Niiknow\Bayes([options])`

[](#classifier--new-niiknowbayesoptions)

Returns an instance of a Naive-Bayes Classifier.

Pass in an optional `options` object to configure the instance. If you specify a `tokenizer` function in `options`, it will be used as the instance's tokenizer.

### `$classifier->learn(text, category)`

[](#classifier-learntext-category)

Teach your classifier what `category` the `text` belongs to. The more you teach your classifier, the more reliable it becomes. It will use what it has learned to identify new documents that it hasn't seen before.

### `$classifier->categorize(text)`

[](#classifier-categorizetext)

Returns the `category` it thinks `text` belongs to. Its judgement is based on what you have taught it with **.learn()**.

### `$classifier->probabilities(text)`

[](#classifier-probabilitiestext)

Extract the probabilities for each known category.

### `$classifier->toJson()`

[](#classifier-tojson)

Returns the JSON representation of a classifier.

### `$classifier->fromJson(jsonStr)`

[](#classifier-fromjsonjsonstr)

Returns a classifier instance from the JSON representation. Use this with the JSON representation obtained from `$classifier->toJson()`

Stopwords
---------

[](#stopwords)

You can pass in your own tokenizer function in the constructor. Example:

```
// array containing stopwords
$stopwords = array("der", "die", "das", "the");

// escape the stopword array and implode with pipe
$s = '~^\W*('.implode("|", array_map("preg_quote", $stopwords)).')\W+\b|\b\W+(?1)\W*$~i';

$options['tokenizer'] = function($text) use ($s) {
            // convert everything to lowercase
            $text = mb_strtolower($text);

            // remove stop words
            $text = preg_replace($s, '', $text);

            // split the words
            preg_match_all('/[[:alpha:]]+/u', $text, $matches);

            // first match list of words
            return $matches[0];
        };

$classifier = new \niiknow\Bayes($options);

```

MIT
---

[](#mit)

###  Health Score

49

—

FairBetter than 95% of packages

Maintenance53

Moderate activity, may be stable

Popularity44

Moderate usage in the ecosystem

Community17

Small or concentrated contributor base

Maturity68

Established project with proven stability

 Bus Factor1

Top contributor holds 88.9% 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 ~339 days

Recently: every ~300 days

Total

6

Last Release

1476d ago

PHP version history (5 changes)1.0.0PHP &gt;=7.0

1.1.1PHP &gt;=7.1

1.1.2PHP &gt;=7.2

1.1.3PHP &gt;=7.3

1.1.4PHP &gt;=7.4

### Community

Maintainers

![](https://www.gravatar.com/avatar/54b78db0eb6f9982c3e1fc555963c13ed2d51587f003935554d88a2b4000fb85?d=identicon)[noogen](/maintainers/noogen)

---

Top Contributors

[![noogen](https://avatars.githubusercontent.com/u/95691?v=4)](https://github.com/noogen "noogen (24 commits)")[![brajnacs](https://avatars.githubusercontent.com/u/8384668?v=4)](https://github.com/brajnacs "brajnacs (1 commits)")[![DaveChild](https://avatars.githubusercontent.com/u/53308?v=4)](https://github.com/DaveChild "DaveChild (1 commits)")[![emilorol](https://avatars.githubusercontent.com/u/9518604?v=4)](https://github.com/emilorol "emilorol (1 commits)")

---

Tags

bayesclassifiermachine-learningmachine-learning-algorithmsnaivenaive-bayesnaive-bayes-algorithmnaive-bayes-classificationnaive-bayes-classifiernaivebayesphpphp-libraryphp-mlphplibrarymachine learningbayesclassifierPHP Librarylibnaive bayesphp mlnaiveniiknownaive-bayes-classifiernaive-bayes-algorithmnaivebayesmachine-learning-algorithmnaive-bayes-classification

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/niiknow-bayes/health.svg)

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

###  Alternatives

[rubix/ml

A high-level machine learning and deep learning library for the PHP language.

2.2k1.4M28](/packages/rubix-ml)[camspiers/statistical-classifier

A PHP implementation of Complement Naive Bayes and SVM statistical classifiers, including a structure for building other classifier, multiple data sources and multiple caching backends

17237.0k1](/packages/camspiers-statistical-classifier)[fieg/bayes

Implementation of Naive Bayes Classifier algorithm in PHP.

7394.1k](/packages/fieg-bayes)

PHPackages © 2026

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