PHPackages                             assisted-mindfulness/naive-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. assisted-mindfulness/naive-bayes

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

assisted-mindfulness/naive-bayes
================================

A fluent Naive Bayes classifier for PHP and Laravel with normalized arbitrary-precision probabilities.

2.0.1(2w ago)45536.3k↓90.1%3MITPHPPHP ^8.2CI passing

Since Mar 11Pushed 2w ago1 watchersCompare

[ Source](https://github.com/Assisted-Mindfulness/naive-bayes)[ Packagist](https://packagist.org/packages/assisted-mindfulness/naive-bayes)[ Docs](https://github.com/Assisted-Mindfulness/naive-bayes)[ RSS](/packages/assisted-mindfulness-naive-bayes/feed)WikiDiscussions master Synced 2w ago

READMEChangelog (10)Dependencies (14)Versions (12)Used By (0)

Naive Bayes
===========

[](#naive-bayes)

[![Tests](https://github.com/Assisted-Mindfulness/naive-bayes/actions/workflows/tests.yml/badge.svg)](https://github.com/Assisted-Mindfulness/naive-bayes/actions/workflows/tests.yml)

This PHP package for Naive Bayes works by looking at a training set and making a guess based on that set. It uses simple statistics and a bit of math to calculate the result.

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?

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

[](#installation)

You may install Naive Bayes into your project using the Composer package manager:

```
composer require assisted-mindfulness/naive-bayes
```

Learning
--------

[](#learning)

Before the algorithm can do anything, it requires a training set with historical information. To teach your classifier which category the text belongs to, call the `learn` method:

```
$classifier = new Classifier();

$classifier
    ->learn('I love sunny days', 'positive')
    ->learn('I hate rain', 'negative');
```

Categories may be strings, integers, backed enums, or pure enums. Enum cases are normalized to their backing value or, for pure enums, their case name:

```
enum Sentiment: int
{
    case Negative = 0;
    case Positive = 1;
}

$classifier->learn('I love sunny days', Sentiment::Positive);
```

The keys returned by `guess()` and the value returned by `most()` use the normalized string or integer identifier. As with native PHP arrays, integer-like string keys such as `"10"` are normalized to the integer `10`.

Guessing
--------

[](#guessing)

After you have trained the classifier, you can use the prediction of which category the transmitted text belongs to, for example:

```
$classifier->most('is a sunny days'); // positive
$classifier->most('there will be rain'); // negative
```

To inspect the score for every category, use:

```
$classifier->guess('is a sunny days');

/*
items: array:2 [
  "negative" => 0.2461538461538462
  "positive" => 0.7538461538461538
]
*/
```

Probabilities are returned as `Brick\Math\BigDecimal` values and always add up to exactly `1` at the configured decimal scale. Any rounding remainder is assigned deterministically to the highest-ranked categories. The classifier applies Laplace smoothing to words learned in other categories and ignores words that do not occur anywhere in the training data.

Uneven
------

[](#uneven)

Categories have equal prior probabilities by default. If the number of learned documents should influence the result, enable uneven mode to calculate Laplace-smoothed priors from the training distribution.

```
$classifier
   ->uneven()
   ->guess('is a sunny days');
```

Precision
---------

[](#precision)

Returned probabilities use 16 decimal places by default. You can increase or reduce the precision through the fluent `scale` method:

```
$classifier
    ->scale(32)
    ->learn('I love sunny days', 'positive')
    ->guess('A sunny day');
```

The scale must be a positive integer.

Tokenizer
---------

[](#tokenizer)

The algorithm utilizes a tokenizer to segment text into words. By default, it extracts Unicode letters, converts them to lowercase, and includes words longer than three characters. You can also define a custom tokenizer:

```
$classifier = new Classifier();

$classifier
    ->setTokenizer(function (string $string) {
        return Str::of($string)
            ->lower()
            ->matchAll('/[[:alpha:]]+/u')
            ->filter(fn (string $word) => Str::length($word) > 3);
    })
    ->learn('I love sunny days', 'positive');
```

The tokenizer may return any iterable of strings.

Development
-----------

[](#development)

Run the complete fast quality suite:

```
composer check
```

Run mutation testing with a required MSI of 90%:

```
composer mutation
```

The mutation suite measures observable behavior. Protected visibility changes are excluded, while subclass customization is covered by a dedicated behavioral test.

Wrapping up
-----------

[](#wrapping-up)

There you have it! Even with a **very** small training set the algorithm can still return some decent results. For example, [Naive Bayes has been proven to give decent results in sentiment analyses](http://www-nlp.stanford.edu/courses/cs224n/2009/fp/3.pdf).

Moreover, Naive Bayes can be applied to more than just text. If you have other ways of calculating the probabilities of your metrics, you can plug those in as well.

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

60

—

FairBetter than 98% of packages

Maintenance96

Actively maintained with recent releases

Popularity43

Moderate usage in the ecosystem

Community14

Small or concentrated contributor base

Maturity69

Established project with proven stability

 Bus Factor1

Top contributor holds 83.3% 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 ~160 days

Recently: every ~202 days

Total

11

Last Release

19d ago

Major Versions

0.0.8 → 1.0.02025-09-21

1.0.0 → 2.0.02026-07-29

PHP version history (3 changes)0.0.1PHP ^8.0

0.0.2PHP ^8.1

2.0.0PHP ^8.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/3c47797b11041f37c2eec74b09bc6619c8997467d690797ebad0e6ab7cb232b7?d=identicon)[tabuna](/maintainers/tabuna)

---

Top Contributors

[![tabuna](https://avatars.githubusercontent.com/u/5102591?v=4)](https://github.com/tabuna "tabuna (30 commits)")[![bdelespierre](https://avatars.githubusercontent.com/u/1086339?v=4)](https://github.com/bdelespierre "bdelespierre (3 commits)")[![TheDigitalOrchard](https://avatars.githubusercontent.com/u/3195423?v=4)](https://github.com/TheDigitalOrchard "TheDigitalOrchard (2 commits)")[![SadElephant](https://avatars.githubusercontent.com/u/7434276?v=4)](https://github.com/SadElephant "SadElephant (1 commits)")

---

Tags

classifiermachine-learninglaravelclassificationnlpmachine learningbayesclassifierprobabilitynaive bayes

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan, Rector

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/assisted-mindfulness-naive-bayes/health.svg)

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

###  Alternatives

[illuminate/database

The Illuminate Database package.

2.8k55.8M13.1k](/packages/illuminate-database)[rubix/ml

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

2.2k1.6M30](/packages/rubix-ml)[illuminate/validation

The Illuminate Validation package.

18838.8M2.0k](/packages/illuminate-validation)[emargareten/inertia-modal

Inertia Modal is a Laravel package that lets you implement backend-driven modal dialogs for Inertia apps.

90157.6k](/packages/emargareten-inertia-modal)[niiknow/bayes

a machine learning lib

6958.0k](/packages/niiknow-bayes)[forjedio/inertia-table

Backend-driven dynamic tables for Laravel + Inertia.js

272.0k](/packages/forjedio-inertia-table)

PHPackages © 2026

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