### Example: Setting and Using Screen Logger Source: https://github.com/rubixml/ml/blob/master/docs/verbose.md This example demonstrates how to instantiate an Adaline regressor, set a Screen logger for real-time output, and then train the estimator. The output shows the logger capturing initialization, training progress, and completion messages. ```php use Rubix\ML\Regressors\Adaline; use Rubix\ML\Loggers\Screen; $estimator = new Adaline(); $estimator->setLogger(new Screen('example')); $estimator->train($dataset); ``` ```text [2020-08-05 04:26:11] INFO: Learner init Adaline {batch_size: 128, optimizer: Adam {rate: 0.01, momentum_decay: 0.1, norm_decay: 0.001}, alpha: 0.0001, epochs: 100, min_change: 0.001, window: 5, cost_fn: Huber Loss {alpha: 1}} [2020-08-05 04:26:11] INFO: Training started [2020-08-05 04:26:11] example.INFO: Epoch 1 - Huber Loss {alpha: 1}: 0.36839299586132 [2020-08-05 04:26:11] example.INFO: Epoch 2 - Huber Loss {alpha: 1}: 0.0018235958273629 [2020-08-05 04:26:11] example.INFO: Epoch 3 - Huber Loss {alpha: 1}: 0.0017358090553563 [2020-08-05 04:26:11] example.INFO: Training complete ``` -------------------------------- ### Install Python Dependencies for Docs Source: https://github.com/rubixml/ml/blob/master/CONTRIBUTING.md Install necessary Python packages for compiling and managing documentation with Mkdocs and Mike. ```sh $ pip install mike mkdocs mkdocs-material mkdocs-git-revision-date-localized-plugin ``` -------------------------------- ### Training Progress Output Example Source: https://github.com/rubixml/ml/blob/master/docs/training.md Example output from the Screen logger during the training of a Logistic Regression model, showing epoch-wise loss progression and final training completion. ```text [2020-09-04 08:39:04] INFO: Logistic Regression (batch_size: 128, optimizer: Adam (rate: 0.01, momentum_decay: 0.1, norm_decay: 0.001), alpha: 0.0001, epochs: 1000, min_change: 0.0001, window: 5, cost_fn: Cross Entropy) initialized [2020-09-04 08:39:04] INFO: Epoch 1 - Cross Entropy: 0.16895133388673 [2020-09-04 08:39:04] INFO: Epoch 2 - Cross Entropy: 0.16559247705179 [2020-09-04 08:39:04] INFO: Epoch 3 - Cross Entropy: 0.16294448401323 [2020-09-04 08:39:04] INFO: Epoch 4 - Cross Entropy: 0.16040135038265 [2020-09-04 08:39:04] INFO: Epoch 5 - Cross Entropy: 0.15786801071483 [2020-09-04 08:39:04] INFO: Epoch 6 - Cross Entropy: 0.1553151426337 [2020-09-04 08:39:04] INFO: Epoch 7 - Cross Entropy: 0.15273253982757 [2020-09-04 08:39:04] INFO: Epoch 8 - Cross Entropy: 0.15011771931339 [2020-09-04 08:39:04] INFO: Epoch 9 - Cross Entropy: 0.14747194148672 [2020-09-04 08:39:04] INFO: Epoch 10 - Cross Entropy: 0.14479847759871 ... [2020-09-04 08:39:04] INFO: Epoch 77 - Cross Entropy: 0.0082096137827592 [2020-09-04 08:39:04] INFO: Epoch 78 - Cross Entropy: 0.0081004235278088 [2020-09-04 08:39:04] INFO: Epoch 79 - Cross Entropy: 0.0079956096838174 [2020-09-04 08:39:04] INFO: Epoch 80 - Cross Entropy: 0.0078948616067878 [2020-09-04 08:39:04] INFO: Epoch 81 - Cross Entropy: 0.0077978960869396 [2020-09-04 08:39:04] INFO: Training complete ``` -------------------------------- ### Representing Samples and Labels in PHP Source: https://github.com/rubixml/ml/blob/master/docs/basic-introduction.md This example shows how to structure your data for machine learning tasks in PHP using a 2-d array for samples and a 1-d array for labels. ```php $samples = [ [3, 4, 50.5], [1, 5, 24.7], [4, 4, 62.0], [3, 2, 31.1], ]; $labels = ['married', 'divorced', 'married', 'divorced']; ``` -------------------------------- ### Initialize MultibyteTextNormalizer Source: https://github.com/rubixml/ml/blob/master/docs/transformers/multibyte-text-normalizer.md Instantiate the MultibyteTextNormalizer to convert text to lowercase. Ensure the mbstring extension is installed for best performance. ```php use Rubix\ML\Transformers\MultibyteTextNormalizer; $transformer = new MultibyteTextNormalizer(false); ``` -------------------------------- ### Instantiate a K-Nearest Neighbors Classifier Source: https://github.com/rubixml/ml/blob/master/docs/choosing-an-estimator.md Instantiate a KNearestNeighbors classifier with custom hyper-parameters. This example shows how to set the number of neighbors, enable/disable probability estimation, and specify a distance kernel. ```php use Rubix\ML\Classifiers\KNearestNeighbors; use Rubix\ML\Kernels\Distance\Minkowski; $estimator = new KNearestNeighbors(10, false, new Minkowski(2.5)); ``` -------------------------------- ### Initialize PlusPlus Seeder with Minkowski Kernel Source: https://github.com/rubixml/ml/blob/master/docs/clusterers/seeders/plus-plus.md Instantiate the PlusPlus seeder with a custom distance kernel. This example uses the Minkowski distance with a power of 5.0. ```php use Rubix\ML\Clusterers\Seeders\PlusPlus; use Rubix\ML\Kernels\Distance\Minkowski; $seeder = new PlusPlus(new Minkowski(5.0)); ``` -------------------------------- ### Set Parallel Backend Source: https://github.com/rubixml/ml/blob/master/docs/parallel.md Configure a parallelizable object to use a specific backend for parallel processing. This example demonstrates setting the Amp backend with 16 processes. ```php public setBackend(Backend $backend) : void ``` ```php use Rubix\ML\Classifiers\RandomForest; use Rubix\ML\Backends\Amp; $estimator = new RandomForest(); $estimator->setBackend(new Amp(16)); ``` -------------------------------- ### Example Predictions Output Source: https://github.com/rubixml/ml/blob/master/docs/basic-introduction.md The output of the predict() method are the predicted class labels for the provided unknown samples. ```php Array ( [0] => married [1] => divorced [2] => divorced [3] => married ) ``` -------------------------------- ### Instantiate RadiusNeighborsRegressor Source: https://github.com/rubixml/ml/blob/master/docs/regressors/radius-neighbors-regressor.md Instantiates the RadiusNeighborsRegressor with custom parameters. This example shows how to set the radius, disable weighted averaging, and specify a BallTree with a maximum leaf size of 30 and a Diagonal distance kernel. ```php use Rubix\ML\Regressors\RadiusNeighborsRegressor; use Rubix\ML\Graph\Trees\BallTree; use Rubix\ML\Kernels\Distance\Diagonal; $estimator = new RadiusNeighborsRegressor(0.5, false, new BallTree(30, new Diagonal())); ``` -------------------------------- ### Initialize K Nearest Neighbors Classifier Source: https://github.com/rubixml/ml/blob/master/docs/classifiers/k-nearest-neighbors.md Instantiate the KNearestNeighbors classifier with custom parameters for k, weighting, and the distance kernel. This example uses the Manhattan distance kernel. ```php use Rubix\ML\Classifiers\KNearestNeighbors; use Rubix\ML\Kernels\Distance\Manhattan; $estimator = new KNearestNeighbors(3, false, new Manhattan()); ``` -------------------------------- ### PHP Constant Initializer Example Source: https://github.com/rubixml/ml/blob/master/docs/neural-network/initializers/constant.md Instantiates the Constant initializer with a specific float value. This is used to set the initial weights or biases of a neural network layer. ```php use Rubix\ML\NeuralNet\Initializers\Constant; $initializer = new Constant(1.0); ``` -------------------------------- ### Run PHP Script from Command Line Source: https://github.com/rubixml/ml/blob/master/docs/faq.md Execute a PHP script using the command line interface. Ensure the PHP interpreter is installed and in your system's PATH. ```sh $ php example.php ``` -------------------------------- ### Instantiate KDTree with Euclidean Kernel Source: https://github.com/rubixml/ml/blob/master/docs/graph/trees/k-d-tree.md Creates a new KDTree instance with a maximum leaf size of 30 and the Euclidean distance kernel. This is a common starting point for using the KDTree for spatial data. ```php use Rubix\ML\Graph\Trees\KDTree; use Rubix\ML\Kernels\Distance\Euclidean; $tree = new KDTree(30, new Euclidean()); ``` -------------------------------- ### Instantiate ReLU Activation Function Source: https://github.com/rubixml/ml/blob/master/docs/neural-network/activation-functions/relu.md Instantiates the ReLU activation function. Note that the constructor signature in the example might differ from the actual implementation if default parameters are not explicitly shown. ```php use Rubix\ML\NeuralNet\ActivationFunctions\ReLU; $activationFunction = new ReLU(0.1); ``` -------------------------------- ### Install Rubix ML with Composer Source: https://github.com/rubixml/ml/blob/master/README.md Install Rubix ML into your project using Composer. Ensure you have PHP 7.4 or above installed. ```sh composer require rubix/ml ``` -------------------------------- ### Transformer Pipeline for Sequential Transformations Source: https://github.com/rubixml/ml/blob/master/docs/preprocessing.md Automate a series of transformations using the Pipeline meta-estimator. This example sets up a pipeline with imputation, encoding, and standardization before passing data to a KMeans clusterer. ```php use Rubix\ML\Pipeline; use Rubix\ML\Transformers\HotDeckImputer; use Rubix\ML\Transformers\OneHotEncoder; use Rubix\ML\Transformers\ZScaleStandardizer; use Rubix\ML\Clusterers\KMeans; $estimator = new Pipeline([ new HotDeckImputer(5), new OneHotEncoder(), new ZScaleStandardizer(), ], new KMeans(10)); ``` -------------------------------- ### Deploy and Serve Documentation Source: https://github.com/rubixml/ml/blob/master/CONTRIBUTING.md Deploy documentation for a specific version and serve the documentation site locally for development. ```sh $ mike deploy 'VERSION' ``` ```sh $ mike serve ``` -------------------------------- ### Get Class Revision Hash Source: https://github.com/rubixml/ml/blob/master/docs/persistable.md Call the revision method on a Persistable object to get its current class revision hash. ```php echo $persistable->revision(); ``` -------------------------------- ### Initialize Grid Search with KNearestNeighbors Source: https://github.com/rubixml/ml/blob/master/docs/grid-search.md Instantiate Grid Search with a base learner class, parameter combinations, a validation metric, and a validator. ```php use Rubix\ML\GridSearch; use Rubix\ML\Classifiers\KNearestNeighbors; use Rubix\ML\Kernels\Distance\Euclidean; use Rubix\ML\Kernels\Distance\Manhattan; use Rubix\ML\CrossValidation\Metrics\FBeta; use Rubix\ML\CrossValidation\KFold; $params = [ [1, 3, 5, 10], [true, false], [new Euclidean(), new Manhattan()], ]; $estimator = new GridSearch(KNearestNeighbors::class, $params, new FBeta(), new KFold(5)); ``` -------------------------------- ### Example Accuracy Score Source: https://github.com/rubixml/ml/blob/master/docs/basic-introduction.md This is an example of the accuracy score returned by the test method, indicating the model's performance on unseen data. ```text 0.88 ``` -------------------------------- ### Initialize Word Tokenizer Source: https://github.com/rubixml/ml/blob/master/docs/tokenizers/word.md Instantiate the Word tokenizer. This tokenizer does not accept any parameters. ```php use Rubix\ML\Tokenizers\Word; $tokenizer = new Word(); ``` -------------------------------- ### Advanced Preprocessing with Column Pickers and Pipelines Source: https://github.com/rubixml/ml/blob/master/docs/preprocessing.md Extract specific features using Column Pickers, apply distinct transformations to different feature sets, and then join them. This example preprocesses text reviews and categorical features separately before joining and applying a standardizer. ```php use Rubix\ML\Dataset\Labeled; use Rubix\ML\Extractors\ColumnPicker; use Rubix\ML\Extractors\NDJSON; use Rubix\ML\Dataset\Unlabeled; use Rubix\ML\Transformers\TextNormalizer; use Rubix\ML\Transformers\WordCountVectorizer; use Rubix\ML\Transformers\TfIdfTransformer; use Rubix\ML\Transformers\OneHotEncoder; use Rubix\ML\Transformers\ZScaleStandardizer; $extractor1 = new ColumnPicker(new NDJSON('example.ndjson'), [ 'review', 'sentiment', ]); $extractor2 = new ColumnPicker(new NDJSON('example.ndjson'), [ 'category', 'clicks', 'rating', ]); $dataset1 = Labeled::fromIterator($extractor1) ->apply(new TextNormalizer()) ->apply(new WordCountVectorizer(5000)) ->apply(new TfIdfTransformer()); $dataset2 = Unlabeled::fromIterator($extractor2) ->apply(new OneHotEncoder()); $dataset = $dataset1->join($dataset2) ->apply(new ZScaleStandardizer()); ``` -------------------------------- ### Instantiate Screen Logger Source: https://github.com/rubixml/ml/blob/master/docs/loggers/screen.md Create a new instance of the Screen logger. You can specify a channel name and a timestamp format. ```php use Rubix\ML\Loggers\Screen; $logger = new Screen('mlp', 'Y-m-d H:i:s'); ``` -------------------------------- ### Contingency Table JSON Output Example Source: https://github.com/rubixml/ml/blob/master/docs/cross-validation/reports/contingency-table.md Example of the JSON output format for a Contingency Table report, illustrating the frequency distribution of class labels (e.g., 'lamb', 'wolf') across different clusters. ```json [ { "lamb": 11, "wolf": 2 }, { "lamb": 1, "wolf": 5 } ] ``` -------------------------------- ### Instantiate Softmax Activation Function Source: https://github.com/rubixml/ml/blob/master/docs/neural-network/activation-functions/softmax.md Learn how to create an instance of the Softmax activation function. No parameters are required for initialization. ```php use Rubix\ML\NeuralNet\ActivationFunctions\Softmax; $activationFunction = new Softmax(); ``` -------------------------------- ### Instantiate Serial Backend Source: https://github.com/rubixml/ml/blob/master/docs/backends/serial.md Create an instance of the Serial backend. This backend is suitable for sequential task execution and is often the default choice for small datasets due to its zero overhead. ```php use Rubix\ML\Backends\Serial; $backend = new Serial(); ``` -------------------------------- ### Get Labels Source: https://github.com/rubixml/ml/blob/master/docs/datasets/labeled.md Retrieves all the labels from the dataset as an array. ```APIDOC ## labels() ### Description Return the labels of the dataset in an array. ### Method `public labels() : array` ### Parameters None ### Request Example ```php $dataset->labels(); ``` ### Response #### Success Response (200) An array containing all labels. #### Response Example ```php [ 'not monster', 'monster', 'not monster' ] ``` ``` -------------------------------- ### Get Label Type Source: https://github.com/rubixml/ml/blob/master/docs/datasets/labeled.md Returns the data type of the labels in the dataset. ```APIDOC ## labelType() ### Description Return the data type of the label. ### Method `public labelType() : Rubix\ML\DataType` ### Parameters None ### Request Example ```php echo $dataset->labelType(); ``` ### Response #### Success Response (200) The data type of the label. #### Response Example ```sh continuous ``` ``` -------------------------------- ### Get Possible Outcomes Source: https://github.com/rubixml/ml/blob/master/docs/datasets/labeled.md Returns an array of all unique labels present in the dataset. ```APIDOC ## possibleOutcomes() ### Description Return all of the possible outcomes i.e. the unique labels in an array. ### Method `public possibleOutcomes() : array` ### Parameters None ### Request Example ```php $dataset->possibleOutcomes(); ``` ### Response #### Success Response (200) An array of unique labels. #### Response Example ```php [ 'female', 'male' ] ``` ``` -------------------------------- ### Run Benchmarking Suite Source: https://github.com/rubixml/ml/blob/master/CONTRIBUTING.md Execute the benchmarking suite using Composer to assess performance. ```sh $ composer benchmark ``` -------------------------------- ### Get Label by Offset Source: https://github.com/rubixml/ml/blob/master/docs/datasets/labeled.md Retrieves a single label at a specified row offset. ```APIDOC ## label() ### Description Return a single label at the given row offset. ### Method `public label(int $offset) : mixed` ### Parameters #### Path Parameters * **offset** (int) - Required - The row offset of the label to retrieve. ### Request Example ```php $dataset->label(1); ``` ### Response #### Success Response (200) The label at the specified offset. #### Response Example ```php 'monster' ``` ``` -------------------------------- ### Initialize HotDeckImputer Source: https://github.com/rubixml/ml/blob/master/docs/transformers/hot-deck-imputer.md Instantiates the HotDeckImputer with specified parameters including k, weighted, categoricalPlaceholder, and a BallTree with a Gower distance kernel. ```php use Rubix\ML\Transformers\HotDeckImputer; use Rubix\ML\Graph\Trees\BallTree; use Rubix\ML\Kernels\Distance\Gower; $transformer = new HotDeckImputer(20, false, '?', new BallTree(50, new Gower(1.0))); ``` -------------------------------- ### Get Descriptive Statistics Source: https://github.com/rubixml/ml/blob/master/docs/datasets/api.md Retrieves descriptive statistics for continuous and categorical features in the dataset. ```php echo $dataset->describe(); ``` ```json [ { "offset": 0, "type": "categorical", "num categories": 2, "probabilities": { "friendly": 0.6666666666666666, "loner": 0.3333333333333333 } }, { "offset": 1, "type": "continuous", "mean": 0.3333333333333333, "standard deviation": 3.129252661934191, "skewness": -0.4481030843690633, "kurtosis": -1.1330702741786107, "min": -5, "25%": -1.375, "median": 0.8, "75%": 2.825, "max": 4 } ] ``` -------------------------------- ### splice Source: https://github.com/rubixml/ml/blob/master/docs/datasets/api.md Removes a size *n* chunk of the dataset starting at *offset* and returns it in a new dataset. ```APIDOC ## splice(int $offset, int $n) ### Description Remove a size *n* chunk of the dataset starting at *offset* and return it in a new dataset. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **offset** (int) - Required - The starting offset of the chunk to remove. - **n** (int) - Required - The size of the chunk to remove. ### Response #### Success Response (200) - **return value** (self) - A new dataset object containing the removed chunk. ``` -------------------------------- ### Instantiate Pipeline with Transformers and Estimator Source: https://github.com/rubixml/ml/blob/master/docs/pipeline.md Instantiate a Pipeline with a list of transformers, a base estimator, and the elastic mode setting. This is useful for creating a preprocessing and modeling workflow. ```php use Rubix\ML\Pipeline; use Rubix\ML\Transformers\MissingDataImputer; use Rubix\ML\Transformers\OneHotEncoder; use Rubix\ML\Transformers\PrincipalComponentAnalysis; use Rubix\ML\Classifiers\SoftmaxClassifier; $estimator = new Pipeline([ new MissingDataImputer(), new OneHotEncoder(), new PrincipalComponentAnalysis(20), ], new SoftmaxClassifier(128), true); ``` -------------------------------- ### Instantiate Softsign Activation Function Source: https://github.com/rubixml/ml/blob/master/docs/neural-network/activation-functions/softsign.md This snippet shows how to create an instance of the Softsign activation function using PHP. No parameters are required for initialization. ```php use Rubix\ML\NeuralNet\ActivationFunctions\Softsign; $activationFunction = new Softsign(); ``` -------------------------------- ### Get Number of Imported Records Source: https://github.com/rubixml/ml/blob/master/docs/extracting-data.md Check the total number of records imported into the dataset object after extraction. ```php echo $dataset->numSamples(); ``` -------------------------------- ### Instantiate Accuracy Metric Source: https://github.com/rubixml/ml/blob/master/docs/cross-validation/metrics/accuracy.md Learn how to create an instance of the Accuracy metric. This is the first step before using it to evaluate models. ```php use Rubix\ML\CrossValidation\Metrics\Accuracy; $metric = new Accuracy(); ``` -------------------------------- ### Initialize Uniform Distribution Source: https://github.com/rubixml/ml/blob/master/docs/neural-network/initializers/uniform.md Instantiate the Uniform initializer with a beta value to set the bounds for the random weight distribution. ```php use Rubix\ML\NeuralNet\Initializers\Uniform; $initializer = new Uniform(1e-3); ``` -------------------------------- ### Instantiate SiLU Activation Function Source: https://github.com/rubixml/ml/blob/master/docs/neural-network/activation-functions/silu.md This snippet shows how to create an instance of the SiLU activation function. No parameters are required. ```php use Rubix\ML\NeuralNet\ActivationFunctions\SiLU; $activationFunction = new SiLU(); ``` -------------------------------- ### Get Feature Importances Source: https://github.com/rubixml/ml/blob/master/docs/ranks-features.md Retrieves the importance scores for each feature column from the training set. This method is called after the model has been trained. ```php public featureImportances() : array ``` ```php $estimator->train($dataset); $importances = $estimator->featureImportances(); print_r($importances); ``` ```php Array ( [0] => 0.04757 [1] => 0.37948 [2] => 0.53170 [3] => 0.04123 ) ``` -------------------------------- ### Instantiate TruncatedSVD Transformer Source: https://github.com/rubixml/ml/blob/master/docs/transformers/truncated-svd.md Instantiate the TruncatedSVD transformer with a specified number of dimensions. The Tensor extension must be installed to use this transformer. ```php use Rubix\ML\Transformers\TruncatedSVD; $transformer = new TruncatedSVD(100); ``` -------------------------------- ### Initialize Preset Seeder Source: https://github.com/rubixml/ml/blob/master/docs/clusterers/seeders/preset.md Instantiate the Preset seeder with an array of predefined centroids. Each centroid can be an array of values representing its features. ```php use Rubix\ML\Clusterers\Seeders\Preset; $seeder = new Preset([ ['foo', 14, 0.72], ['bar', 16, 0.92], ]); ``` -------------------------------- ### Score a Dataset Source: https://github.com/rubixml/ml/blob/master/docs/scoring.md Returns the anomaly scores assigned to the samples in a dataset. Use this method to get anomaly scores for each data point. ```php public score(Dataset $dataset) : array ``` ```php $scores = $estimator->score($dataset); print_r($scores); ``` ```php Array ( [0] => 0.35033 [1] => 0.40992 [2] => 1.68153 ) ``` -------------------------------- ### Get Label Type Source: https://github.com/rubixml/ml/blob/master/docs/datasets/labeled.md Determine and display the data type of the labels in the dataset. This helps in understanding how labels are treated by the ML algorithms. ```php echo $dataset->labelType(); ``` -------------------------------- ### Get Unique Labels Source: https://github.com/rubixml/ml/blob/master/docs/datasets/labeled.md Retrieve an array containing all unique class labels present in the dataset. This is useful for understanding the distribution of outcomes. ```php print_r($dataset->possibleOutcomes()); ``` -------------------------------- ### Instantiate Amp Backend Source: https://github.com/rubixml/ml/blob/master/docs/backends/amp.md Instantiates the Amp backend with a specified number of workers. The number of workers can be auto-detected if not provided. ```php use Rubix\ML\Backends\Amp; $backend = new Amp(16); ``` -------------------------------- ### Apply a Transformer to a Dataset Source: https://github.com/rubixml/ml/blob/master/docs/transformers/api.md Pass a transformer object to the apply() method on a Dataset object to transform its features. This example uses MinMaxNormalizer. ```php use Rubix\ML\Transformers\MinMaxNormalizer; $dataset->apply(new MinMaxNormalizer()); ``` -------------------------------- ### Instantiate He Initializer Source: https://github.com/rubixml/ml/blob/master/docs/neural-network/initializers/he.md This snippet shows how to instantiate the He initializer. It does not require any parameters. ```php use Rubix\ML\NeuralNet\Initializers\He; $initializer = new He(); ``` -------------------------------- ### Initialize PReLU Layer Source: https://github.com/rubixml/ml/blob/master/docs/neural-network/hidden-layers/prelu.md Instantiate a PReLU layer with a custom initializer for the leakage parameter. This example uses the Normal initializer with a mean of 0.5. ```php use Rubix\ML\NeuralNet\Layers\PReLU; use Rubix\ML\NeuralNet\Initializers\Normal; $layer = new PReLU(new Normal(0.5)); ``` -------------------------------- ### Batch vs. Online Learning Source: https://github.com/rubixml/ml/blob/master/docs/training.md Demonstrates batch learning using `train()` followed by online learning updates using `partial()` with subsequent datasets. Online learning is useful for large datasets or streaming data. ```php $estimator->train($dataset1); $estimator->partial($dataset2); $estimator->partial($dataset3); ``` -------------------------------- ### Get First N Rows Source: https://github.com/rubixml/ml/blob/master/docs/datasets/api.md Extract the first 'n' rows from the dataset, returning them as a new dataset object. This is useful for previewing the beginning of the data. ```php $subset = $dataset->head(10); ``` -------------------------------- ### Instantiate Vantage Tree Source: https://github.com/rubixml/ml/blob/master/docs/graph/trees/vantage-tree.md Instantiates a new Vantage Tree with a specified maximum leaf size and a Euclidean distance kernel. Ensure the Euclidean kernel is imported. ```php use Rubix\ML\Graph\Trees\VantageTree; use Rubix\ML\Kernels\Distance\Euclidean; $tree = new VantageTree(30, new Euclidean()); ``` -------------------------------- ### Initialize Sparse Cosine Kernel Source: https://github.com/rubixml/ml/blob/master/docs/kernels/distance/sparse-cosine.md Instantiate the SparseCosine kernel. This kernel is optimized for sparse vectors and requires no parameters. ```php use Rubix\ML\Kernels\Distance\SparseCosine; $kernel = new SparseCosine(); ``` -------------------------------- ### Get Feature Type by Offset Source: https://github.com/rubixml/ml/blob/master/docs/datasets/api.md Retrieve the data type for a specific feature column using its offset. This helps in understanding the nature of the data in that column. ```php echo $dataset->featureType(15); ``` -------------------------------- ### Get Dataset Shape Source: https://github.com/rubixml/ml/blob/master/docs/datasets/api.md Retrieve the dimensions (number of rows and columns) of the samples matrix within the dataset. This is useful for understanding the dataset's size. ```php [$m, $n] = $dataset->shape(); echo "$m x $n"; ``` -------------------------------- ### Initialize KNNImputer Source: https://github.com/rubixml/ml/blob/master/docs/transformers/knn-imputer.md Instantiates the KNNImputer with specified parameters for k, weighting, categorical placeholder, and a BallTree with a SafeEuclidean distance kernel. ```php use Rubix\ML\Transformers\KNNImputer; use Rubix\ML\Graph\Trees\BallTee; use Rubix\ML\Kernels\Distance\SafeEuclidean; $transformer = new KNNImputer(10, false, '?', new BallTree(30, new SafeEuclidean())); ``` -------------------------------- ### Multiclass Breakdown Report JSON Output Source: https://github.com/rubixml/ml/blob/master/docs/cross-validation/reports/multiclass-breakdown.md An example of the JSON output from the MulticlassBreakdown report, showing overall metrics and per-class metrics for a classification task. ```json { "overall": { "accuracy": 0.6, "accuracy balanced": 0.5833333333333333, "f1 score": 0.5833333333333333, "precision": 0.5833333333333333, "recall": 0.5833333333333333, "specificity": 0.5833333333333333, "negative predictive value": 0.5833333333333333, "false discovery rate": 0.4166666666666667, "miss rate": 0.4166666666666667, "fall out": 0.4166666666666667, "false omission rate": 0.4166666666666667, "mcc": 0.16666666666666666, "informedness": 0.16666666666666652, "markedness": 0.16666666666666652, "true positives": 3, "true negatives": 3, "false positives": 2, "false negatives": 2, "cardinality": 5 }, "classes": { "wolf": { "accuracy": 0.6, "accuracy balanced": 0.5833333333333333, "f1 score": 0.6666666666666666, "precision": 0.6666666666666666, "recall": 0.6666666666666666, "specificity": 0.5, "negative predictive value": 0.5, "false discovery rate": 0.33333333333333337, "miss rate": 0.33333333333333337, "fall out": 0.5, "false omission rate": 0.5, "informedness": 0.16666666666666652, "markedness": 0.16666666666666652, "mcc": 0.16666666666666666, "true positives": 2, "true negatives": 1, "false positives": 1, "false negatives": 1, "cardinality": 3, "proportion": 0.6 }, "lamb": { "accuracy": 0.6, "accuracy balanced": 0.5833333333333333, "f1 score": 0.5, "precision": 0.5, "recall": 0.5, "specificity": 0.6666666666666666, "negative predictive value": 0.6666666666666666, "false discovery rate": 0.5, "miss rate": 0.5, "fall out": 0.33333333333333337, "false omission rate": 0.33333333333333337, "informedness": 0.16666666666666652, "markedness": 0.16666666666666652, "mcc": 0.16666666666666666, "true positives": 1, "true negatives": 2, "false positives": 1, "false negatives": 1, "cardinality": 2, "proportion": 0.4 } } } ``` -------------------------------- ### Instantiate Linear SVM Kernel Source: https://github.com/rubixml/ml/blob/master/docs/kernels/svm/linear.md Learn how to create an instance of the Linear kernel for SVM models. This kernel requires no parameters. ```php use Rubix\ML\Kernels\SVM\Linear; $kernel = new Linear(); ``` -------------------------------- ### Instantiate Step Decay Optimizer Source: https://github.com/rubixml/ml/blob/master/docs/neural-network/optimizers/step-decay.md Initializes the Step Decay optimizer with a learning rate of 0.1, a step interval of 50, and a decay factor of 1e-3. ```php use Rubix\ML\NeuralNet\Optimizers\StepDecay; $optimizer = new StepDecay(0.1, 50, 1e-3); ``` -------------------------------- ### Get Metric Score Range Source: https://github.com/rubixml/ml/blob/master/docs/cross-validation/metrics/api.md Retrieve the minimum and maximum possible values for a validation score. The output is a 2-tuple containing the minimum and maximum float values. ```php public range() : Rubix\ML\Tuple{float, float} ``` ```php [$min, $max] = $metric->range()->list(); echo "min: $min, max: $max"; ``` ```text min: 0.0, max: 1.0 ``` -------------------------------- ### Initialize Labeled Dataset Source: https://github.com/rubixml/ml/blob/master/docs/datasets/labeled.md Create a new Labeled dataset instance by providing a 2D array of samples and a 1D array of corresponding labels. The 'verify' parameter can be set to false to skip data validation. ```php use Rubix\ML\Datasets\Labeled; $samples = [ [0.1, 20, 'furry'], [2.0, -5, 'rough'], [0.01, 5, 'furry'], ]; $labels = ['not monster', 'monster', 'not monster']; $dataset = new Labeled($samples, $labels); ``` -------------------------------- ### Chain Multiple Transformers Source: https://github.com/rubixml/ml/blob/master/docs/preprocessing.md Apply multiple transformers sequentially to a dataset by fluently calling the apply() method. This example chains imputation, one-hot encoding, and normalization. ```php use Rubix\ML\Transformers\HotDeckImputer; use Rubix\ML\Transformers\OneHotEncoder; use Rubix\ML\Transformers\MinMaxNormalizer; $dataset->apply(new HotDeckImputer(5)) ->apply(new OneHotEncoder()) ->apply(new MinMaxNormalizer()); ``` -------------------------------- ### Instantiate Sigmoid Activation Function Source: https://github.com/rubixml/ml/blob/master/docs/neural-network/activation-functions/sigmoid.md Demonstrates how to create an instance of the Sigmoid activation function. This function has no configurable parameters. ```php use Rubix\ML\NeuralNet\ActivationFunctions\Sigmoid; $activationFunction = new Sigmoid(); ``` -------------------------------- ### Initialize Stochastic Optimizer Source: https://github.com/rubixml/ml/blob/master/docs/neural-network/optimizers/stochastic.md Instantiate the Stochastic optimizer with a specified learning rate. This optimizer is suitable for basic gradient descent applications. ```php use Rubix\ML\NeuralNet\Optimizers\Stochastic; $optimizer = new Stochastic(0.01); ``` -------------------------------- ### Initialize ImageResizer Transformer Source: https://github.com/rubixml/ml/blob/master/docs/transformers/image-resizer.md Instantiate the ImageResizer transformer with the desired width and height. The GD extension must be enabled. ```php use Rubix\ML\Transformers\ImageResizer; $transformer = new ImageResizer(28, 28); ``` -------------------------------- ### Get Feature Importances from a Trained Ridge Regressor Source: https://github.com/rubixml/ml/blob/master/docs/training.md Train a Ridge regressor and then retrieve the importance scores for each feature. This is useful for feature selection and understanding model behavior. ```php use Rubix\ML\Regressors\Ridge; $estimator = new Ridge(); $estimator->train($dataset); $importances = $estimator->featureImportances(); print_r($importances); ``` ```sh Array ( [0] => 0.04757 [1] => 0.37948 [2] => 0.53170 [3] => 0.04123 ) ``` -------------------------------- ### Get Dropped Record Count Source: https://github.com/rubixml/ml/blob/master/docs/extractors/deduplicator.md Retrieve the total number of records that have been dropped by the Deduplicator due to being identified as duplicates. This method is useful for monitoring the effectiveness of the deduplication process. ```php public function dropped() : int ``` -------------------------------- ### Initialize KMostFrequent Strategy Source: https://github.com/rubixml/ml/blob/master/docs/strategies/k-most-frequent.md Instantiates the KMostFrequent strategy with a specified number of top classes to consider. This strategy is suitable for categorical data. ```php use Rubix\ML\Strategies\KMostFrequent; $strategy = new KMostFrequent(5); ``` -------------------------------- ### Predicting with a Dataset Source: https://github.com/rubixml/ml/blob/master/docs/estimator.md Use the `predict()` method to get predictions for unknown samples in a dataset. The return value is an array of predictions corresponding to the dataset's indexed order. ```php public predict(Dataset $dataset) : array ``` ```php $predictions = $estimator->predict($dataset); print_r($predictions); ``` ```text Array ( [0] => married [1] => divorced [2] => divorced [3] => married ) ``` -------------------------------- ### Update Stateful Transformer Fitting Source: https://github.com/rubixml/ml/blob/master/docs/transformers/api.md Elastic transformers can adapt to new data using the update() method after being fitted. This example updates a ZScaleStandardizer with new data folds. ```php use Rubix\ML\Transformers\ZScaleStandardizer; $transformer = new ZScaleStandardizer(); $folds = $dataset->fold(3); $transformer->fit($folds[0]); $transformer->update($folds[1]); $transformer->update($folds[2]); ``` -------------------------------- ### Instantiate Completeness Metric Source: https://github.com/rubixml/ml/blob/master/docs/cross-validation/metrics/completeness.md Instantiates the Completeness metric. This metric does not require any parameters. ```php use Rubix\ML\CrossValidation\Metrics\Completeness; $metric = new Completeness(); ``` -------------------------------- ### Fit a Stateful Transformer to a Dataset Source: https://github.com/rubixml/ml/blob/master/docs/transformers/api.md Stateful transformers require fitting before transformation. The fit() method takes a Dataset and pre-computes necessary information. This example uses OneHotEncoder. ```php use Rubix\ML\Transformers\OneHotEncoder; $transformer = new OneHotEncoder(); $transformer->fit($dataset); var_dump($transformer->fitted()); ``` -------------------------------- ### Instantiate Native Serializer Source: https://github.com/rubixml/ml/blob/master/docs/serializers/native.md This snippet shows how to create an instance of the Native serializer. No parameters are required for initialization. ```php use Rubix\ML\Serializers\Native; $serializer = new Native(); ``` -------------------------------- ### Instantiate a Labeled Dataset Source: https://github.com/rubixml/ml/blob/master/docs/datasets/api.md Create a new Labeled dataset object by passing samples and their corresponding labels to the constructor. Ensure labels are provided as a separate array. ```php use Rubix\ML\Datasets\Labeled; $samples = [ [0.1, 20, 'furry'], [2.0, -5, 'rough'], ]; $labels = ['not monster', 'monster']; $dataset = new Labeled($samples, $labels); ``` -------------------------------- ### Making Predictions with an Estimator Source: https://github.com/rubixml/ml/blob/master/docs/inference.md Use the `predict()` method on a trained estimator to get predictions for a dataset. Ensure the inference dataset has the same number and order of feature columns as the training data. ```php $predictions = $estimator->predict($dataset); print_r($predictions); ``` ```plaintext Array ( [0] => cat [1] => dog [2] => frog ) ``` -------------------------------- ### Instantiate SparseRandomProjector Source: https://github.com/rubixml/ml/blob/master/docs/transformers/sparse-random-projector.md Instantiate the SparseRandomProjector transformer with a specified number of target dimensions and automatic sparsity selection. ```php use Rubix\ML\Transformers\SparseRandomProjector; $transformer = new SparseRandomProjector(30, null); ``` -------------------------------- ### Instantiate Gradient Boost Regressor Source: https://github.com/rubixml/ml/blob/master/docs/regressors/gradient-boost.md Instantiates a GradientBoost regressor with specified parameters. This includes the base learner, learning rate, subsampling ratio, maximum epochs, minimum change threshold, early stopping window, hold-out ratio for validation, and the evaluation metric. ```php use Rubix\ML\Regressors\GradientBoost; use Rubix\ML\Regressors\RegressionTree; use Rubix\ML\CrossValidation\Metrics\SMAPE; $estimator = new GradientBoost(new RegressionTree(3), 0.1, 0.8, 1000, 1e-4, 10, 0.1, new SMAPE()); ``` -------------------------------- ### Instantiate RMSProp Optimizer Source: https://github.com/rubixml/ml/blob/master/docs/neural-network/optimizers/rms-prop.md Instantiate the RMSProp optimizer with a specified learning rate and decay rate. ```php use Rubix\ML\NeuralNet\Optimizers\RMSProp; $optimizer = new RMSProp(0.01, 0.1); ``` -------------------------------- ### Instantiate LambdaFunction Transformer Source: https://github.com/rubixml/ml/blob/master/docs/transformers/lambda-function.md This snippet shows how to create a LambdaFunction transformer. It defines a callback function that adds a transformed value to the sample and then instantiates the transformer with the callback and an example context. ```php use Rubix\ML\Transformers\LambdaFunction; $callback = function (&$sample, $offset, $context) { $sample[] = log1p($sample[3]); }; $transformer = new LambdaFunction($callback, 'example context'); ``` -------------------------------- ### Instantiate Min Max Normalizer Source: https://github.com/rubixml/ml/blob/master/docs/transformers/min-max-normalizer.md Instantiate the MinMaxNormalizer with custom minimum and maximum values for the transformation range. ```php use Rubix\ML\Transformers\MinMaxNormalizer; $transformer = new MinMaxNormalizer(-5.0, 5.0); ``` -------------------------------- ### Initialize Gaussian Mixture Model Source: https://github.com/rubixml/ml/blob/master/docs/clusterers/gaussian-mixture.md Instantiate a Gaussian Mixture model with specified parameters including the number of clusters, smoothing, epochs, minimum change, and a seeder. ```php use Rubix\ML\Clusterers\GaussianMixture; use Rubix\ML\Clusterers\Seeders\KMC2; $estimator = new GaussianMixture(5, 1e-6, 100, 1e-4, new KMC2(50)); ``` -------------------------------- ### Initialize K-Means Estimator Source: https://github.com/rubixml/ml/blob/master/docs/clusterers/k-means.md Instantiate the KMeans estimator with custom parameters for the number of clusters, batch size, epochs, minimum change threshold, early stopping window, distance kernel, and seeder. ```php use Rubix\ML\Clusterers\KMeans; use Rubix\ML\Kernels\Distance\Euclidean; use Rubix\ML\Clusterers\Seeders\PlusPlus; $estimator = new KMeans(3, 128, 300, 10.0, 10, new Euclidean(), new PlusPlus()); ``` -------------------------------- ### Instantiate Concatenator with Multiple CSV Iterators Source: https://github.com/rubixml/ml/blob/master/docs/extractors/concatenator.md Instantiates the Concatenator extractor by providing an array of CSV iterators. This setup is ideal for merging data from several CSV files into one. ```php use Rubix\ML\Extractors\Concatenator; use Rubix\ML\Extractors\CSV; $extractor = new Concatenator([ new CSV('dataset1.csv'), new CSV('dataset2.csv'), new CSV('dataset3.csv'), ]); ``` -------------------------------- ### Get Joint Probability Estimates Source: https://github.com/rubixml/ml/blob/master/docs/probabilistic.md Use the `proba()` method to retrieve joint probability estimates from a dataset. This method is useful for understanding the estimator's certainty about each possible class or cluster. ```php public proba(Dataset $dataset) : array ``` ```php $probabilities = $estimator->proba($dataset); print_r($probabilities); ``` ```php Array ( [0] => Array ( [monster] => 0.6 [not monster] => 0.4 ) [1] => Array ( [monster] => 0.5 [not monster] => 0.5 ) [2] => Array ( [monster] => 0.2 [not monster] => 0.8 ) ) ``` -------------------------------- ### Instantiate Normal Initializer Source: https://github.com/rubixml/ml/blob/master/docs/neural-network/initializers/normal.md Instantiate the Normal initializer with a custom standard deviation for the Gaussian distribution. ```php use Rubix\ML\NeuralNet\Initializers\Normal; $initializer = new Normal(0.1); ``` -------------------------------- ### Getting Anomaly Scores with a Scoring Estimator Source: https://github.com/rubixml/ml/blob/master/docs/inference.md Anomaly detectors implementing the `Scoring` interface can use the `score()` method to output anomaly scores for samples. Higher scores indicate greater abnormality. ```php $scores = $estimator->score($dataset); print_r($scores); ``` ```plaintext Array ( [0] => 0.35033 [1] => 0.40992 [2] => 1.68153 ) ``` -------------------------------- ### Initialize Swish Layer Source: https://github.com/rubixml/ml/blob/master/docs/neural-network/hidden-layers/swish.md Instantiate a Swish activation layer with a Constant initializer for the beta parameter. ```php use Rubix\ML\NeuralNet\Layers\Swish; use Rubix\ML\NeuralNet\Initializers\Constant; $layer = new Swish(new Constant(1.0)); ``` -------------------------------- ### Instantiate Bootstrap Aggregator Source: https://github.com/rubixml/ml/blob/master/docs/bootstrap-aggregator.md Instantiate the BootstrapAggregator with a base learner, number of estimators, and sample ratio. This is useful for creating an ensemble of models to reduce variance. ```php use Rubix\ML\BootstrapAggregator; use Rubix\ML\Regressors\RegressionTree; $estimator = new BootstrapAggregator(new RegressionTree(10), 300, 0.2); ``` -------------------------------- ### Instantiate KSkipNGram Tokenizer Source: https://github.com/rubixml/ml/blob/master/docs/tokenizers/k-skip-n-gram.md Instantiates the KSkipNGram tokenizer with minimum token length 2, maximum token length 3, and a skip value of 2. ```php use Rubix\ML\Tokenizers\KSkipNGram; $tokenizer = new KSkipNGram(2, 3, 2); ``` -------------------------------- ### Example Confusion Matrix JSON Output Source: https://github.com/rubixml/ml/blob/master/docs/cross-validation/reports/confusion-matrix.md A sample JSON structure representing a confusion matrix. Keys represent actual labels, and nested keys represent predicted labels with their corresponding counts. ```json { "dog": { "dog": 12, "cat": 3, "turtle": 0 }, "cat": { "dog": 2, "cat": 9, "turtle": 1 }, "turtle": { "dog": 1, "cat": 0, "turtle": 11 } } ``` -------------------------------- ### Instantiate a Dense Layer Source: https://github.com/rubixml/ml/blob/master/docs/neural-network/hidden-layers/dense.md Instantiates a Dense layer with a specified number of neurons, L2 penalty, bias inclusion, and weight/bias initializers. Ensure the necessary classes are imported before use. ```php use Rubix\ML\NeuralNet\Layers\Dense; use Rubix\ML\NeuralNet\Initializers\He; use Rubix\ML\NeuralNet\Initializers\Constant; $layer = new Dense(100, 1e-4, true, new He(), new Constant(0.0)); ``` -------------------------------- ### Export Neural Network Architecture to Image Source: https://github.com/rubixml/ml/blob/master/docs/classifiers/multilayer-perceptron.md Exports the neural network architecture as a Graphviz "dot" encoding and then converts it to a PNG image saved to 'network.png'. Ensure Graphviz is installed and accessible. ```php use Rubix\ML\Helpers\Graphviz; use Rubix\ML\Persisters\Filesystem; $dot = $estimator->exportGraphviz(); Graphviz::dotToImage($dot)->saveTo(new Filesystem('network.png')); ``` -------------------------------- ### Instantiate Wild Guess Strategy Source: https://github.com/rubixml/ml/blob/master/docs/strategies/wild-guess.md Instantiates the WildGuess strategy. This strategy does not require any parameters. ```php use Rubix\ML\Strategies\WildGuess; $strategy = new WildGuess(); ```