PHP NlpTools
repository·master·Indexed 20 days ago
https://github.com/angeloskath/php-nlp-toolsA library of PHP 5.3+ classes for natural language processing tasks. It provides tools for classification (Multinomial Naive Bayes, Maximum Entropy), topic modeling (Latent Dirichlet Allocation), clustering (K-Means, Hierarchical Agglomerative Clustering), and tokenization. The library includes components for similarity measures, stemmers, feature factories, and frequency distribution analysis.
What's inside PHP NlpTools
- PHP NlpTools is a collection of PHP 5.3+ classes designed for beginner to semi-advanced natural language processing (NLP) tasks. It provides a suite of tools for classification, topic modeling, clustering, tokenization, and more.
Use the Lda class for topic modeling
masterThe
Ldaclass implements Latent Dirichlet Allocation (LDA) using Gibbs sampling for topic discovery in a collection of documents. It uses aFeatureFactoryInterfaceto transform documents into feature arrays before processing.use NlpTools\ Models\\Lda; use NlpTools\\Documents\\TrainingSet; // $ff must implement FeatureFactoryInterface // $ntopics is the number of topics to discover $lda = new Lda($ff, $ntopics); // $tset is a TrainingSet instance $lda->train($tset, $iterations);Simhash implementation details
masterThe
Simhashimplementation uses a vector of length$length(initialized to 0). For each member in the set, it computes a bit vector via the provided$hashfunction. It then increments or decrements the corresponding dimension in the vector based on whether the bit is '1' or '0'. The final hash is determined by the sign of each dimension in the vector.Note on Weights:
- The implementation supports feature duplication as a way to add weight (if the input array contains duplicate values).
- It does not support explicit weighted features via a separate weight parameter.
Configure LancasterStemmer with a custom ruleset
masterThe
LancasterStemmerconstructor accepts an optional$ruleSetarray. If an empty array is provided, the class defaults to its internal English ruleset.Each rule in the array is an associative array containing the following keys:
lookup_char: The character used to index the rule for faster lookup.ending_string: The suffix string to match.intact_flag: A flag (e.g.,*) indicating if the rule should only apply if the word remains 'intact'.remove_total: The number of characters to remove from the end of the word.append_string: The string to append after removal.continue_flag: Controls the loop behavior (e.g.,.to stop or>to continue).
use NlpTools\Stemmers\LancasterStemmer; // Example of a custom rule set $customRules = [ [ 'lookup_char' => 'x', 'ending_string' => 'xyz', 'intact_flag' => '*', 'remove_total' => '3', 'append_string' => 'abc', 'continue_flag' => '.' ] ]; $stemmer = new LancasterStemmer($customRules);Available NLP components in PHP NlpTools
masterPHP NlpTools provides several categories of tools for NLP workflows:
Classification Models
- Multinomial Naive Bayes
- Maximum Entropy (Conditional Exponential model)
Topic Modeling
- Latent Dirichlet Allocation (Lda): Note that Lda is currently experimental and can be slow.
Clustering
- K-Means
- Hierarchical Agglomerative Clustering (supports
SingleLink,CompleteLink, andGroupAverage)
Tokenizers
WhitespaceTokenizerWhitespaceAndPunctuationTokenizerPennTreebankTokenizerRegexTokenizerClassifierBasedTokenizer: Used for building complex, custom tokenizers.
Documents
TokensDocument: Represents a bag of words model.WordDocument: Represents a single word within the context of a larger document.TrainingDocument: Represents a document with a known class.TrainingSet: A collection ofTrainingDocumentobjects.
Feature Factories
FunctionFeatures: Creates a feature factory from multiple callables.DataAsFeatures: Returns raw data as features.
Similarity Measures
JaccardIndexCosineSimilaritySimhashEuclideanHammingDistance
Stemmers
PorterStemmerRegexStemmerLancasterStemmerGreekStemmer
Optimizers (MaxEnt only)
- Gradient Descent: A simple PHP implementation for educational purposes.
- External Maxent Optimizer: A high-performance, parallel gradient descent optimizer written in Go, used via the
ExternalMaxentOptimizerclass.
Add features to FunctionFeatures using add()
masterYou can dynamically add new feature-generating callables to an existing
FunctionFeaturesinstance using theadd($feature)method. The$featureparameter must be acallable.$factory = new FunctionFeatures(); $factory->add(function($class, $document) { return 'new_feature_from_closure'; });Use PennTreeBankTokenizer for text segmentation
masterThe
PennTreeBankTokenizeris used to segment text into tokens following the Penn Treebank conventions. It implements specific regex-based rules to handle punctuation, contractions (e.g., convertingn'tor'llinto separate tokens), and special characters. It extendsWhitespaceTokenizer, meaning after applying the Penn Treebank rules, it splits the resulting string based on whitespace.use NlpTools\Tokenizers\PennTreeBankTokenizer; $tokenizer = new PennTreeBankTokenizer(); $tokens = $tokenizer->tokenize("I'm gonna go to the store, isn't it?"); // Returns an array of tokens segmented according to Penn Treebank rulesCalculate class probability with P()
masterThe
P()method calculates the probability that a specific document$dbelongs to a given$class, relative to a set of all possible$classes. This calculation uses the model's learned weights and the provided feature factory.Parameters:
array $classes: The set of all possible classes.FeatureFactoryInterface $ff: The feature factory used to extract features from the document.DocumentInterface $d: The document being evaluated.string $class: The specific class for which you want to calculate the probability.
Returns:
float: The calculated probability (0.0 to 1.0).
// Returns the probability of $class given the document $d $probability = $model->P($classes, $ff, $d, $targetClass);Get the model log-likelihood
masterThe
getLogLikelihood()method returns the log-likelihood of the model having generated the provided data. This value can be used to evaluate the quality of the model or compare different LDA configurations./** * @return float The log likelihood of the model. */ public function getLogLikelihood()Use RegexTokenizer for text segmentation
masterThe
RegexTokenizerclass implementsTokenizerInterfaceand allows you to segment text using a sequence of regular expressions. It processes patterns iteratively: the output of one pattern becomes the input for the next.There are three modes of operation based on the structure of the pattern provided in the constructor array:
- Split Mode: If a pattern is provided as a single element (e.g.,
['/pattern/']), it usespreg_splitto break strings into smaller tokens. Empty results are discarded. - Match Mode: If a pattern is provided with an integer (e.g.,
['/pattern/', 1]), it usespreg_match_allto extract specific capture groups. The integer specifies which index of the match array to keep. - Transform Mode: If a pattern is provided with a string (e.g.,
['/pattern/', '/replacement/']), it usespreg_replaceto transform existing tokens.
use NlpTools\Tokenizers\RegexTokenizer; // Example: Splitting by whitespace, then matching words, then transforming $patterns = [ '/\s+/', // Split mode: split by whitespace ['/(\w+)/', 0], // Match mode: keep the whole match (index 0) ['/\w/', 'X'] // Transform mode: replace characters with 'X' ]; $tokenizer = new RegexTokenizer($patterns); $tokens = $tokenizer->tokenize("Hello world");- Split Mode: If a pattern is provided as a single element (e.g.,
Use FunctionFeatures to generate features from callables
masterThe
FunctionFeaturesclass implementsFeatureFactoryInterfaceand allows you to generate features by executing a collection of callables (closures, function names, or array-based callables like[$object, 'method']).Each callable is passed two arguments: the
$class(a string representing the category/class) and the$d(aDocumentInterfaceinstance).Feature Extraction Logic:
- If a callable returns a
string, that string is added as a feature. - If a callable returns an
array, every element in that array is added as an individual feature. - Return values that evaluate to
falseare ignored.
Modeling Frequency vs. Presence:
- By default, the factory models presence (returning a list of unique feature strings).
- You can switch to modeling frequency (returning an associative array where keys are feature strings and values are their counts) using
modelFrequency().
use NlpTools\FeatureFactories\FunctionFeatures; // Initialize with an array of callables $factory = new FunctionFeatures([ function($class, $document) { return 'some_feature'; }, [$myObject, 'extractFeatures'] ]); // To return counts instead of just unique keys: $factory->modelFrequency(); // To return only unique keys (presence): $factory->modelPresence(); // Get the features for a specific class and document $features = $factory->getFeatureArray('my_class_name', $document);- If a callable returns a
Configure TrainingSet iteration keys
masterThe
TrainingSetallows you to define what value is returned by thekey()method during iteration usingsetAsKey(). This is useful when you need to loop over documents based on their category versus their position in the collection.Available constants:
TrainingSet::CLASS_AS_KEY: Returns the class label of the current document. This is the default behavior.TrainingSet::OFFSET_AS_KEY: Returns the integer offset of the document in the internal collection.
// To iterate using the integer index instead of the class label: $trainingSet->setAsKey(\NlpTools\\Documents\\TrainingSet::OFFSET_AS_KEY); foreach ($trainingSet as $index => $trainingDocument) { // $index will be 0, 1, 2, etc. }