{"id":22353996,"url":"https://github.com/rubixml/colors","last_synced_at":"2025-09-04T07:16:01.819Z","repository":{"id":62537977,"uuid":"162769571","full_name":"RubixML/Colors","owner":"RubixML","description":"Demonstrating unsupervised clustering using the K Means algorithm and synthetic color data.","archived":false,"fork":false,"pushed_at":"2022-04-29T03:59:58.000Z","size":257,"stargazers_count":17,"open_issues_count":0,"forks_count":3,"subscribers_count":4,"default_branch":"master","last_synced_at":"2024-11-24T20:47:06.771Z","etag":null,"topics":["clustering","contingency-table","cross-validation","k-means","k-means-clustering","k-means-plus-plus","kmeans","machine-learning","machine-learning-tutorial","php","php-machine-learning","php-ml","rubix-ml","synthetic-data","synthetic-dataset-generation","tutorial","unsupervised-learning"],"latest_commit_sha":null,"homepage":"https://rubixml.com","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/RubixML.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-12-22T00:35:40.000Z","updated_at":"2024-09-28T12:48:18.000Z","dependencies_parsed_at":"2022-11-02T16:15:23.049Z","dependency_job_id":null,"html_url":"https://github.com/RubixML/Colors","commit_stats":null,"previous_names":[],"tags_count":6,"template":true,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RubixML%2FColors","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RubixML%2FColors/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RubixML%2FColors/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RubixML%2FColors/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/RubixML","download_url":"https://codeload.github.com/RubixML/Colors/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":228114882,"owners_count":17871742,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["clustering","contingency-table","cross-validation","k-means","k-means-clustering","k-means-plus-plus","kmeans","machine-learning","machine-learning-tutorial","php","php-machine-learning","php-ml","rubix-ml","synthetic-data","synthetic-dataset-generation","tutorial","unsupervised-learning"],"created_at":"2024-12-04T13:10:46.673Z","updated_at":"2025-07-30T08:34:43.876Z","avatar_url":"https://github.com/RubixML.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Rubix ML - Color Clusterer\nThe K Means algorithm is a popular unsupervised learner for clustering samples. In this tutorial, we'll generate a synthetic dataset of colors so that we can demonstrate how K Means clusters them into groups.\n\n- **Difficulty**: Easy\n- **Training time**: Less than a minute\n\n## Installation\nClone the project locally using [Composer](https://getcomposer.org/):\n```sh\n$ composer create-project rubix/colors\n```\n\n## Requirements\n- [PHP](https://php.net) 7.4 or above\n\n## Tutorial\n\n### Introduction\nIn machine learning, synthetic data are often used for demonstration purposes or to augment a smaller dataset with more training samples. In this tutorial we'll use synthetic data to train and test a [K Means](https://rubixml.github.io/ML//latest/clusterers/k-means.html) clusterer to group samples by color. K Means is a highly-scalable algorithm that works by finding the center vectors (called *centroids*) for every *k* clusters of the training set. During inference, the distance from an unknown sample to each centroid is measured to determine the cluster it belongs to.\n\n\u003e **Note:** The source code for this example can be found in the [train.php](https://github.com/RubixML/Colors/blob/master/train.php) file in project root.\n\n### Generating the Data\nRubix ML provides a number of dataset [Generators](https://rubixml.github.io/ML//latest/datasets/generators/api.html) which output a dataset in a particular shape and dimensionality. For this example project, we are going to generate [Blobs](https://rubixml.github.io/ML//latest/datasets/generators/blob.html) of color channel data using red, green, and blue (RGB) values for the features. The [Agglomerate](https://rubixml.github.io/ML//latest/datasets/generators/agglomerate.html) will combine and label the individual color generators to form a [Labeled](https://rubixml.github.io/ML//latest/datasets/labeled.html) dataset consisting of all 10 colors weighted equally.\n\n```php\nuse Rubix\\ML\\Datasets\\Generators\\Agglomerate;\nuse Rubix\\ML\\Datasets\\Generators\\Blob;\n\n$generator = new Agglomerate([\n    'red' =\u003e new Blob([255, 0, 0], 20.0),\n    'orange' =\u003e new Blob([255, 128, 0], 10.0),\n    'yellow' =\u003e new Blob([255, 255, 0], 10.0),\n    'green' =\u003e new Blob([0, 128, 0], 20.0),\n    'blue' =\u003e new Blob([0, 0, 255], 20.0),\n    'aqua' =\u003e new Blob([0, 255, 255], 10.0),\n    'purple' =\u003e new Blob([128, 0, 255], 10.0),\n    'pink' =\u003e new Blob([255, 0, 255], 10.0),\n    'magenta' =\u003e new Blob([255, 0, 128], 10.0),\n    'black' =\u003e new Blob([0, 0, 0], 10.0),\n]);\n```\n\nTo generate the dataset, call the `generate()` method with the number of samples (*n*) to be generated as an argument. The return value is a [Dataset](https://rubixml.github.io/ML//latest/datasets/generators/api.html) object that allows you to process the data fluently using its methods if needed. For example we could stratify and split the dataset into a training and testing set such that each subset contains a proportion of the dataset and each color is represented fairly in each subset. The proportion of samples in the *left* (training) set to the *right* (testing) set is given by the *ratio* parameter of the `stratifiedSplit()` method. For this example, we'll choose to generate a set of 5,000 samples and then split it 80/20 (4000 for training and 1000 for testing).\n\n```php\n[$training, $testing] = $generator-\u003egenerate(5000)-\u003estratifiedSplit(0.8);\n```\n\nNow, let's take a look at the data we've generated using some plotting software such as [Plotly](https://plot.ly). You'll notice that each color forms a distinct blob in 3-dimensional space.\n\n![Synthetic Color Data](https://github.com/RubixML/Colors/blob/master/docs/images/samples-3d.png)\n\n### Instantiating the Learner\nNext, we'll instantiate our [K Means](https://rubixml.github.io/ML//latest/clusterers/k-means.html) clusterer by defining its hyper-parameters. K Means is a fast online clustering algorithm that minimizes the inertia cost function using Mini Batch Gradient Descent. The algorithm finds a set of *k* cluster centroids or multivariate means of the target cluster. The number of target clusters (k) is passes as a hyper-parameter to the learners constructor. For this example, we already know that the number of clusters should be 10 so we'll set k to 10.\n\n```php\nuse Rubix\\ML\\Clusterers\\KMeans;\n\n$estimator = new KMeans(10);\n```\n\n### Training\nOnce the learner has been instantiated, call the `train()` method with the training set we generated earlier as an argument.\n\n```php\n$estimator-\u003etrain($training);\n```\n\n### Training Loss\nK Means uses the inertia cost function to measure the goodness of fit of each of the k centroids. We can visualize the training progress by plotting the values of the cost function at each epoch. To obtain the training losses call the `steps()` method on the estimator. To save the progress to a file we can pass the iterator returned by the `steps()` method to the `export()` method of a [Writable](https://rubixml.github.io/ML//latest/extractors/api.html) extractor.\n\n```php\nuse Rubix\\ML\\Extractors\\CSV;\n\n$extractor = new CSV('progress.csv', true);\n\n$extractor-\u003eexport($estimator-\u003esteps());\n```\n\nNow, we can plot the values using our favorite plotting software. As you can see, the value of the cost function decreases at each epoch until it stops when K Means has met its stopping criteria.\n\n![Inertia Loss](https://raw.githubusercontent.com/RubixML/Colors/master/docs/images/training-loss.png)\n\n### Making Predictions\nTo make the predictions, pass the testing set to the `predict()` method on the estimator instance.\n\n```php\n$predictions = $estimator-\u003epredict($testing);\n```\n\n### Cross Validation\nLastly, to test the model we just created, let's generate a cross validation report that compares the predictions to some ground truth given by the labels we've assigned to the generators. A [Contingency Table](https://rubixml.github.io/ML//latest/cross-validation/reports/contingency-table.html) is a clustering report similar to a [Confusion Matrix](https://rubixml.github.io/ML//latest/cross-validation/reports/confusion-matrix.html) but for clustering instead of classification. It counts the number of times a particular cluster was assigned to a given label. A good clustering has a contingency table where each cluster contains samples with roughly the same label. We'll need the predictions we generated earlier as well as the labels from the testing set for the report's `generate()` method.\n\n```php\nuse Rubix\\ML\\CrossValidation\\Reports\\ContingencyTable;\n\n$report = new ContingencyTable();\n\n$results = $report-\u003egenerate($predictions, $testing-\u003elabels());\n```\n\nNow we're ready to run the training and validation script from the command line.\n```php\n$ php train.php\n```\n\nHere is an excerpt of the Contingency Report. You'll notice a misclustered magenta point within the red cluster. Not bad, nice work!\n\n```json\n{\n    \"8\": {\n        \"red\": 100,\n        \"orange\": 0,\n        \"yellow\": 0,\n        \"green\": 0,\n        \"blue\": 0,\n        \"aqua\": 0,\n        \"purple\": 0,\n        \"pink\": 0,\n        \"magenta\": 1,\n        \"black\": 0\n    },\n}\n```\n\n\u003e **Note:** Due to the stochastic nature of the K Means algorithm, each clustering will be a little different. If a particular clustering is poor, you can try retraining the learner.\n\n### Next Steps\nCongratulations on completing the tutorial on K Means and synthetic data generation. Try generating some more data in other shapes using the [Circle](https://rubixml.github.io/ML//latest/datasets/generators/circle.html) or [Half Moon](https://rubixml.github.io/ML//latest/datasets/generators/half-moon.html) generator. Is K Means able to detect clusters of different shapes and sizes?\n\n## License\nThe code is licensed [MIT](LICENSE) and the tutorial is licensed [CC BY-NC 4.0](https://creativecommons.org/licenses/by-nc/4.0/).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frubixml%2Fcolors","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frubixml%2Fcolors","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frubixml%2Fcolors/lists"}