Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Naive Bayes Laravel Package

assisted-mindfulness/naive-bayes

A lightweight Naive Bayes classifier for PHP and Laravel. Train on labeled text and classify new documents for spam detection, sentiment analysis, or category prediction with a simple, easy-to-use API.

View on GitHub
Deep Wiki
Context7

Getting Started

This is a small, framework-agnostic Naive Bayes text classifier — not a Laravel package with a service provider, config file or facade. Expect to wire it up yourself, which is usually 20 lines of code.

  • Install with composer require tabuna/naive-bayes. Version 2.x targets modern PHP (8.1+) and pulls in brick/math for the probability arithmetic — you do not interact with it directly.
  • Nothing to register. No config/naive-bayes.php, no migrations, no published assets. If you want container access, bind a configured classifier instance in a AppServiceProvider or a small dedicated service class.
  • First use case: a spam/not-spam or support-ticket triage classifier. The flow is always the same three steps — create a classifier, train() it with [label, text] pairs (or one label at a time), then call predict() / predictProba() with new text.
  • Look first at the README's quick-start block and the Classifier + tokenizer classes. The tokenizer is the single most influential knob; start with the bundled whitespace/regex tokenizer before writing your own.

Implementation Patterns

Train in a command, predict in a request. Training is CPU-bound and should never happen in an HTTP request. Put it in an artisan command or queued job that reads labeled rows from your database, and persist the trained model (the package serialises the classifier) to storage or a cache key. Controllers then load the model and only call predict().

Version your model artifacts. Because the model is a snapshot of your training corpus, store it with a hash or timestamp (e.g. storage/app/models/tickets-{corpus_hash}.model) and let deploys write a new one rather than mutating in place. This makes rollback trivial and keeps your predictions reproducible across environments.

Wrap it in one service. A TicketClassifier class with train(array $samples) and classify(string $text): string means the rest of the app never touches package classes. That makes swapping tokenizers, adding pre-processing (lowercasing, stripping emails/URLs), or replacing the library entirely a one-file change.

Feed it from an Eloquent query, not from fixtures. Ticket::whereNotNull('category_id')->get(['subject','body','category_id']) is your training set. Use a chunkById loop if the corpus is large so you do not hold everything in memory while tokenizing.

Seed-bootstrap for cold start. Ship a small curated dataset (a few hundred labeled examples per class) in a seeder so the classifier is useful on day one, then retrain from real data on a schedule. A nightly job that retrains on the last N months is the common production shape.

Test against a frozen corpus. Commit a small labeled fixture set and assert exact predictions plus relative confidence ordering. Naive Bayes is fast enough to train inside the test suite, so you get real regression coverage without mocking anything.

Gotchas and Tips

  • Class imbalance silently wrecks predictions. The prior probability of each label is baked in, so a corpus that is 90% "billing" will predict "billing" for almost everything. Balance your training data or discard the priors and inspect the per-token likelihoods instead.
  • The 2.0.2 change is a dependency constraint widening. brick/math now accepts ^0.18 || ^0.20 (previously effectively pinned to ^0.18). Nothing in the public API changed. The practical risk is Composer resolution: if another package of yours depends on brick/math, running composer update may now pull 0.20 where it previously couldn't, so re-run your test suite and check that any direct Brick\Math usage you have is unaffected. If you need to stay on 0.18, pin it explicitly in your root composer.json.
  • Tokenization dominates accuracy. Word order is discarded entirely — "not good" and "good not" are the same document. Negation handling requires you to pre-process (e.g. prefix not_ onto the following token) before training and predicting. Apply exactly the same pipeline in both paths; a mismatch here is the number one source of "it worked in training" bugs.
  • Unseen words: with smoothing enabled, unknown tokens are damped rather than fatal, but a classifier trained on English will still confidently mislabel French input. Detect out-of-domain text (high proportion of unseen tokens) and return "unclassified" rather than a low-quality guess.
  • Persisted models are PHP-serialised objects. Treat them as build artifacts: never commit them, never share them across differing PHP versions, and regenerate after upgrading the package or deploying to a different PHP minor version. A corrupt or stale model usually surfaces as confusing deserialization errors rather than a clean "model not found".
  • Probabilities underflow on long texts. If you are inspecting raw scores on long documents, work with log-probabilities (the library exposes the underlying scores) or normalise per label rather than multiplying many small numbers.
  • Extension points are just interfaces: a custom tokenizer (implements the tokenizer contract) for stemming/stopwords, and your own persistence layer if you would rather store the model in Redis or the database than on disk. Both are the intended way to adapt the package — there are no config switches to fight with.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log
gregsphotography/site-builder-components
io-digital/clickatell
snowsoft/laravel-admin
oxygen/auth
relicsoftware/barakah-payment-gateway
tobya/work-with-composer
equipc/laravel-email-validator
equipc/laravel-email-database-log
adedsec/nova-translated-labels
wazza/laravel-db-encryption
hokny/laravel-generator
vonsogt/backup
jengo/queues
jeremykenedy/laravel-observability
coleus/frame
thtg88/journalism
filagora/filagora-ai-forums