### Install CapyMOA Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/docs/installation.rst Installs the CapyMOA package using pip. This command should be run after setting up the necessary dependencies and activating the virtual environment. ```bash pip install capymoa ``` -------------------------------- ### Install Pandoc on Ubuntu Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/docs/installation.rst Installs the Pandoc document converter on Ubuntu systems using apt-get. Pandoc is a dependency for CapyMOA development. ```bash sudo apt-get install -y pandoc ``` -------------------------------- ### Verify CapyMOA Installation Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/docs/installation.rst Checks if CapyMOA has been installed correctly by importing the package and printing its version. This is a verification step after installation. ```python import capymoa; print(capymoa.__version__) ``` -------------------------------- ### Clone CapyMOA Repository Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/docs/installation.rst Clones the CapyMOA Git repository from GitHub. This is the first step for setting up an editable installation for development. ```bash git clone https://github.com/adaptive-machine-learning/CapyMOA.git ``` -------------------------------- ### Run CapyMOA Docker Container Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/docs/docker.md This command starts the CapyMOA Jupyter notebook container, mapping ports and mounting local directories for data and work. Ensure Docker is installed and accessible. ```bash mkdir data work docker run \ -p 8888:8888 \ -v ./work:/home/jovyan/work \ -v ./data:/home/jovyan/data \ tachyonic/jupyter-capymoa ``` -------------------------------- ### List Invoke Tasks Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/docs/installation.rst Lists all available tasks defined in the 'tasks.py' file using the invoke tool. This is useful for managing common development tasks. ```bash python -m invoke --list ``` -------------------------------- ### Install CapyMOA in Editable Mode Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/docs/installation.rst Installs CapyMOA in editable mode with development and documentation dependencies. This command should be run from the root of the cloned repository. ```bash cd CapyMOA pip install --editable "".[dev,doc]" ``` -------------------------------- ### Install PyTorch for CPU Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/docs/installation.rst Installs PyTorch, torchvision, and torchaudio for CPU-only usage. This is required for CapyMOA algorithms that utilize deep learning. ```bash pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu ``` -------------------------------- ### Install Pandoc on macOS Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/docs/installation.rst Installs the Pandoc document converter on macOS systems using Homebrew. Pandoc is a dependency for CapyMOA development. ```bash sudo brew install pandoc ``` -------------------------------- ### Mock Datasets for CapyMOA Examples Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/notebooks/00_getting_started.ipynb This Python snippet imports and calls functions to mock datasets, likely for testing or demonstration purposes within a Jupyter Notebook environment. It checks if the notebook is running in a fast mode before executing the mocking logic. ```python # This cell is hidden on capymoa.org. See docs/contributing/docs.rst from util.nbmock import mock_datasets, is_nb_fast if is_nb_fast(): mock_datasets() ``` -------------------------------- ### Start Docker Compose Services Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/docs/docker.md This command initiates the services defined in the docker-compose.yml file, launching the CapyMOA Jupyter notebook environment. ```bash docker-compose up ``` -------------------------------- ### Install CapyMOA and Dependencies (Bash) Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/docs/index.rst This snippet shows how to install CapyMOA and its prerequisites. It includes checking for Java, installing the CPU version of PyTorch, installing CapyMOA itself, and verifying the installation by printing the version. Ensure Java is installed before proceeding. ```bash # CapyMOA requires Java. This checks if you have it installed java -version # CapyMOA requires PyTorch. This installs the CPU version pip install torch torchvision --index-url https://download.pytorch.org/whl/cpu # Install CapyMOA and its dependencies pip install capymoa # Check that the install worked python -c "import capymoa; print(capymoa.__version__)" ``` -------------------------------- ### Setup CapyMOA Environment Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/notebooks/09_automl.ipynb Initializes mock datasets for testing if the notebook is running in a fast mode. This setup is crucial for efficient development and testing of CapyMOA features. ```python # This cell is hidden on capymoa.org. See docs/contributing/docs.rst from util.nbmock import mock_datasets, is_nb_fast if is_nb_fast(): mock_datasets() ``` -------------------------------- ### Check Java Installation Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/docs/installation.rst Verifies if Java is installed on the system by printing the Java version. This is a required dependency for CapyMOA. ```bash java -version ``` -------------------------------- ### Install CapyMOA and Dependencies (Bash) Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/README.md This snippet shows the necessary commands to install CapyMOA. It includes checking for Java, installing the CPU version of PyTorch, and finally installing CapyMOA itself. It also includes a command to verify the installation by printing the CapyMOA version. ```bash java -version pip install torch torchvision --index-url https://download.pytorch.org/whl/cpu pip install capymoa python -c "import capymoa; print(capymoa.__version__)" ``` -------------------------------- ### Create and Evaluate Regression Pipeline Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/notebooks/07_pipelines.ipynb Demonstrates the setup of a regression pipeline using `RegressorPipeline`, adding a transformer and a regressor (AdaptiveRandomForestRegressor). It then evaluates the pipeline using `RegressionEvaluator` and prints the RMSE. ```python from capymoa.regressor import AdaptiveRandomForestRegressor from capymoa.stream.preprocessing import RegressorPipeline from capymoa.evaluation import RegressionEvaluator from capymoa.datasets import Fried from capymoa.moa.filters import NormalisationFilter fried_stream = Fried() # Creating a transformer normalisation_transformer = MOATransformer( schema=fried_stream.get_schema(), moa_filter=NormalisationFilter() ) arfreg = AdaptiveRandomForestRegressor( schema=normalisation_transformer.get_schema(), ensemble_size=5 ) # Creating and populating the pipeline pipeline_arfreg = RegressorPipeline() pipeline_arfreg.add_transformer(normalisation_transformer) pipeline_arfreg.add_regressor(arfreg) # Creating the evaluator arfreg_evaluator = RegressionEvaluator(schema=fried_stream.get_schema()) while fried_stream.has_more_instances(): instance = fried_stream.next_instance() prediction = pipeline_arfreg.predict(instance) arfreg_evaluator.update(instance.y_value, prediction) pipeline_arfreg.train(instance) print(arfreg_evaluator.rmse()) ``` -------------------------------- ### Classification with OnlineBagging in CapyMOA Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/notebooks/00_getting_started.ipynb Demonstrates a basic classification task using CapyMOA. It initializes an Electricity data stream, an OnlineBagging classifier, and a ClassificationEvaluator. The code iterates through the stream, making predictions, training the model, and updating the evaluator, finally printing the accuracy. ```python from capymoa.datasets import Electricity from capymoa.evaluation import ClassificationEvaluator from capymoa.classifier import OnlineBagging elec_stream = Electricity() ob_learner = OnlineBagging(schema=elec_stream.get_schema(), ensemble_size=5) ob_evaluator = ClassificationEvaluator(schema=elec_stream.get_schema()) for instance in elec_stream: prediction = ob_learner.predict(instance) ob_learner.train(instance) ob_evaluator.update(instance.y_index, prediction) print(ob_evaluator.accuracy()) ``` -------------------------------- ### Create and Activate Conda Virtual Environment Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/docs/installation.rst Installs a new Conda virtual environment named 'capymoa' with Python 3.11 and activates it. This is an optional but recommended step for managing Python dependencies. ```bash conda create -n capymoa python=3.11 conda activate capymoa ``` -------------------------------- ### Simulate and Visualize Concept Drift with DriftStream in Python Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/notebooks/00_getting_started.ipynb This example showcases CapyMOA's DriftStream API for simulating concept drifts. It defines a stream with abrupt and gradual drifts using SEA generators and specific drift objects. The snippet then trains an OnlineBagging classifier and evaluates it using prequential evaluation, visualizing the results. Key components include capymoa.classifier, capymoa.stream.generator, capymoa.stream.drift, and plotting functions. ```python from capymoa.classifier import OnlineBagging from capymoa.stream.generator import SEA from capymoa.stream.drift import AbruptDrift, GradualDrift, DriftStream # Generating a synthetic stream with 1 abrupt drift and 1 gradual drift. stream_sea2drift = DriftStream( stream=[ SEA(function=1), AbruptDrift(position=5000), SEA(function=3), GradualDrift(start=9000, end=12000), SEA(function=1), ] ) OB = OnlineBagging(schema=stream_sea2drift.get_schema(), ensemble_size=10) # Since this is a synthetic stream, max_instances is needed to determine the amount of instances to be generated. results_sea2drift_OB = prequential_evaluation( stream=stream_sea2drift, learner=OB, window_size=100, max_instances=15000 ) # print(stream_sea2drift.drifts) plot_windowed_results(results_sea2drift_OB, metric="accuracy") ``` -------------------------------- ### Building Documentation Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/docs/contributing/faq.md Provides the command to build the project's documentation. This process verifies that the documentation can be generated successfully and checks for any build errors. ```bash invoke docs.build ``` -------------------------------- ### Install Pandoc using Conda Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/docs/installation.rst Installs the Pandoc document converter using the Conda package manager from the conda-forge channel. Pandoc is a dependency for CapyMOA development. ```bash conda install -c conda-forge pandoc ``` -------------------------------- ### Prequential Evaluation with HoeffdingTree in CapyMOA Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/notebooks/00_getting_started.ipynb This Python snippet illustrates how to use the `prequential_evaluation` function from CapyMOA for evaluating a HoeffdingTree classifier on the Electricity data stream. It demonstrates obtaining both cumulative and windowed metrics by specifying a window size. ```python from capymoa.evaluation import prequential_evaluation from capymoa.classifier import HoeffdingTree ht = HoeffdingTree(schema=elec_stream.get_schema(), grace_period=50) # Obtain the results from the high-level function. # Note that we need to specify a window_size as we obtain both windowed and cumulative results. ``` -------------------------------- ### Install TensorBoard using pip Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/notebooks/06_advanced_API.ipynb Installs the TensorBoard library, a visualization tool for machine learning experiments. This command requires pip to be installed and accessible in the environment. It does not take any inputs and its output indicates the installation status. ```python !pip install tensorboard ``` -------------------------------- ### Running Documentation Tests with Doctest Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/docs/contributing/faq.md Shows the command to run documentation tests, ensuring that code examples within the documentation are correct and functional. This command is part of the automated checks for documentation integrity. ```bash invoke test.doctest ``` -------------------------------- ### Perform Regression with MOARegressor and KNNRegressor in Python Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/notebooks/00_getting_started.ipynb This snippet demonstrates how to use CapyMOA's MOARegressor and KNNRegressor for regression tasks. It involves initializing learners with a dataset schema, performing prequential evaluation, and plotting the windowed results. Dependencies include capymoa.datasets, moa.classifiers, capymoa.base, capymoa.regressor, and prequential_evaluation and plot_windowed_results functions. ```python from capymoa.datasets import Fried from moa.classifiers.trees import FIMTDD from capymoa.base import MOARegressor from capymoa.regressor import KNNRegressor fried_stream = ( Fried() ) # Downloads the Fried dataset into the data dir in case it is not there yet. fimtdd = MOARegressor(schema=fried_stream.get_schema(), moa_learner=FIMTDD()) knnreg = KNNRegressor(schema=fried_stream.get_schema(), k=3, window_size=1000) results_fimtdd = prequential_evaluation( stream=fried_stream, learner=fimtdd, window_size=5000 ) results_knnreg = prequential_evaluation( stream=fried_stream, learner=knnreg, window_size=5000 ) results_fimtdd.windowed.metrics_per_window() # Note that the metric is different from the ylabel parameter, which just overrides the y-axis label. plot_windowed_results( results_fimtdd, results_knnreg, metric="rmse", ylabel="root mean squared error" ) ``` -------------------------------- ### Prequential Evaluation and Result Display in Python Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/notebooks/00_getting_started.ipynb This snippet demonstrates how to perform prequential evaluation using the `prequential_evaluation` function and display the cumulative accuracy and wall-clock time. It also shows how to access and display windowed metrics using a pandas DataFrame. ```python from capymoa.evaluation import prequential_evaluation # Assuming elec_stream and ht are defined elsewhere # results_ht = prequential_evaluation(stream=elec_stream, learner=ht, window_size=4500) # print( # f"Cumulative accuracy = {results_ht.cumulative.accuracy()}, wall-clock time: {results_ht.wallclock()}" # ) # display(results_ht.windowed.metrics_per_window()) ``` -------------------------------- ### Create and Configure ML Pipelines in Python Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/notebooks/07_pipelines.ipynb Demonstrates the creation and configuration of various machine learning pipelines using CapyMoA. This includes a transformation pipeline, a prediction pipeline with a classifier, and a drift detection pipeline. ```python # Creating and populating the transformation pipeline trafo_pipeline = ( BasePipeline() .add_transformer(normalisation_transformer) .add_transformer(add_noise_transformer) ) # Creating and populating the prediction pipeline prediction_pipeline = ClassifierPipeline().add_classifier(ob_learner) # Creating and populating the drift detection pipeline drift_pipeline = BasePipeline().add_drift_detector( drift_detector, get_drift_detector_input_func=label_equals_prediction, ) ``` -------------------------------- ### Clone Fork and Add Upstream Remote Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/docs/contributing/git.md Clones your forked repository to your local machine and sets up a remote connection to the original project ('upstream') for fetching updates. This is the initial setup for contributing. ```bash git clone https://github.com/$USER/$FORK_MAME.git # Or using SSH (preferable if you have SSH keys set up): # git clone git@github.com:$USER/$FORK_NAME.git cd CapyMOA # Add a reference to the original repository (this is the 'upstream') git remote add upstream https://github.com/adaptive-machine-learning/CapyMOA.git # Or using SSH: # git remote add upstream git@github.com:adaptive-machine-learning/CapyMOA.git ``` -------------------------------- ### Run Doctest Examples Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/docs/contributing/tests.md Tests code examples written directly within Python docstrings. This ensures documentation remains synchronized with code functionality. Use 'pytest --doctest-modules' to run doctests. ```python def hello_world(): """ >>> hello_world() Hello, World! """ print("Hello, World!") ``` -------------------------------- ### Comparing Classifiers with Windowed Results Plotting in Python Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/notebooks/00_getting_started.ipynb This code demonstrates how to compare multiple classifiers (HoeffdingAdaptiveTree, HoeffdingTree, AdaptiveRandomForestClassifier) by performing prequential evaluation for each and then visualizing their windowed accuracy using `plot_windowed_results`. It also prints the cumulative accuracy for each classifier. ```python from capymoa.evaluation.visualization import plot_windowed_results from capymoa.base import MOAClassifier from moa.classifiers.trees import HoeffdingAdaptiveTree from capymoa.classifier import HoeffdingTree from capymoa.classifier import AdaptiveRandomForestClassifier from capymoa.evaluation import prequential_evaluation # Assuming elec_stream is defined elsewhere # HAT = MOAClassifier( # schema=elec_stream.get_schema(), moa_learner=HoeffdingAdaptiveTree, CLI="-g 50" # ) # HT = HoeffdingTree(schema=elec_stream.get_schema(), grace_period=50) # ARF = AdaptiveRandomForestClassifier( # schema=elec_stream.get_schema(), ensemble_size=10, number_of_jobs=4 # ) # results_HAT = prequential_evaluation(stream=elec_stream, learner=HAT, window_size=4500) # results_HT = prequential_evaluation(stream=elec_stream, learner=HT, window_size=4500) # results_ARF = prequential_evaluation(stream=elec_stream, learner=ARF, window_size=4500) # print(f"HAT accuracy = {results_HAT.cumulative.accuracy()}") # print(f"HT accuracy = {results_HT.cumulative.accuracy()}") # print(f"ARF accuracy = {results_ARF.cumulative.accuracy()}") # plot_windowed_results( # results_HAT, # results_HT, # results_ARF, # metric="accuracy", # xlabel="# Instances (window)", # ) ``` -------------------------------- ### Composition of Pipelines Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/notebooks/07_pipelines.ipynb This snippet illustrates the concept of composing multiple pipelines together, building upon previous examples. It sets up transformers, a learner, and a drift detector, laying the groundwork for nesting pipelines within each other. ```python from capymoa.drift.detectors import ADWIN from capymoa.instance import LabeledInstance from capymoa.type_alias import LabelIndex from capymoa.datasets import Electricity from capymoa.transformers import MOATransformer, NormalisationFilter, AddNoiseFilter from capymoa.learners import OnlineBagging elec_stream = Electricity() # Creating the transformers normalisation_transformer = MOATransformer( schema=elec_stream.get_schema(), moa_filter=NormalisationFilter() ) add_noise_transformer = MOATransformer( schema=normalisation_transformer.get_schema(), moa_filter=AddNoiseFilter() ) # Creating a learner ob_learner = OnlineBagging(schema=add_noise_transformer.get_schema(), ensemble_size=5) # Creating a drift detector drift_detector = ADWIN() ``` -------------------------------- ### Create and Update Classification Pipeline with Evaluator Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/notebooks/07_pipelines.ipynb Demonstrates the creation of a classification evaluator, processing instances from a stream, making predictions, updating the evaluator, and training the pipeline. It also shows how to retrieve the accuracy. ```python from capymoa.stream import Electricity from capymoa.evaluation import ClassificationEvaluator from capymoa.pipeline import ClassifierPipeline ob_evaluator = ClassificationEvaluator(schema=elec_stream.get_schema()) while elec_stream.has_more_instances(): instance = elec_stream.next_instance() prediction = pipeline.predict(instance) ob_evaluator.update(instance.y_index, prediction) pipeline.train(instance) ob_evaluator.accuracy() ``` -------------------------------- ### Executing Notebook Tests Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/docs/contributing/faq.md Details the command to execute all notebooks located in the '/notebooks' directory. This verifies that the notebooks run without errors and are up-to-date with the project's code. ```bash invoke test.nb ``` -------------------------------- ### Run All Tests using Invoke Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/docs/contributing/tests.md This command executes all defined tests within the project using the invoke task runner. Ensure development dependencies are installed before running. ```bash invoke test ``` -------------------------------- ### Docker Compose for CapyMOA Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/docs/docker.md This YAML configuration defines a Docker Compose service for CapyMOA, simplifying the management of container startup, port mapping, and volume mounts. Use 'docker-compose up' to launch. ```yaml services: jupyter-capymoa: image: tachyonic/jupyter-capymoa ports: - "8888:8888" volumes: - ./work:/home/jovyan/work - ./data:/home/jovyan/data ``` -------------------------------- ### Integrate Pipelines into Classifier Pipeline in Python Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/notebooks/07_pipelines.ipynb Shows how to integrate multiple pre-configured pipelines (transformation, prediction, drift detection) into a main Classifier Pipeline. This allows for a sequential execution of different pipeline stages. ```python # Since pipelines themselves are pipeline elements, we can pass them to the initializer of an overall pipeline object pipeline = ClassifierPipeline([trafo_pipeline, prediction_pipeline, drift_pipeline]) # An alternative syntax would be # pipeline = ( # ClassifierPipeline() # .add_pipeline_element(trafo_pipeline) # .add_pipeline_element(prediction_pipeline) # .add_pipeline_element(drift_pipeline) # ) ``` -------------------------------- ### Python Package Initialization for New Learners Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/docs/contributing/faq.md Demonstrates how to add a new learner to a Python package structure. It shows the creation of a learner file prefixed with '_' and its import within the package's __init__.py file, along with the update of the __all__ list for public access. ```python from ._my_new_learner import MyNewLearner ... __all__ = [ 'MyNewLearner', ... ] ``` -------------------------------- ### Get Textual Representation of Pipeline Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/notebooks/07_pipelines.ipynb Shows how to obtain a string representation of a CapyMOA pipeline, detailing the sequence of transformations and classifiers within it. ```python str(pipeline) ``` -------------------------------- ### Display Help for Prequential SSL Evaluation Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/notebooks/SSL_example.ipynb This code snippet displays the help documentation for the `prequential_ssl_evaluation` function in CapyMOA. It helps users understand the function's parameters, their types, default values, and descriptions. ```python help(prequential_ssl_evaluation) ``` -------------------------------- ### Prepare Input for Drift Detector in Pipeline Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/notebooks/07_pipelines.ipynb Shows the steps to integrate a drift detector (ADWIN) into a pipeline. This includes creating the detector, defining a helper function to format instance and prediction data for the detector, and setting up transformers and a learner. ```python from capymoa.drift.detectors import ADWIN from capymoa.instance import LabeledInstance from capymoa.type_alias import LabelIndex from capymoa.stream import Electricity from capymoa.moa.filters import NormalisationFilter, AddNoiseFilter from capymoa.classifier import OnlineBagging elec_stream = Electricity() # Creating the transformers normalisation_transformer = MOATransformer( schema=elec_stream.get_schema(), moa_filter=NormalisationFilter() ) add_noise_transformer = MOATransformer( schema=normalisation_transformer.get_schema(), moa_filter=AddNoiseFilter() ) # Creating a learner ob_learner = OnlineBagging(schema=add_noise_transformer.get_schema(), ensemble_size=5) # Creating a drift detector drift_detector = ADWIN() # Define a function that prepares the input of the drift detector def label_equals_prediction( instance: LabeledInstance, prediction: LabelIndex ) -> LabelIndex: label = instance.y_index return int(label == prediction) ``` -------------------------------- ### Import CapyMOA Evaluation and Dataset Modules Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/notebooks/SSL_example.ipynb Imports necessary functions and classes from the CapyMOA library for evaluation and dataset handling. This includes plotting functions, the prequential SSL evaluation function, and the Electricity dataset. ```python from capymoa.evaluation.visualization import plot_windowed_results from capymoa.evaluation import prequential_ssl_evaluation from capymoa.datasets import Electricity ``` -------------------------------- ### Run TensorBoard for Monitoring Training Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/notebooks/06_advanced_API.ipynb This command starts TensorBoard, a visualization tool for machine learning experiments. It requires a log directory where TensorBoard will find event files. TensorBoard recursively searches the specified directory for files matching the pattern '.*tfevents.*' to display metrics like accuracy, training speed, and learning rate over time. ```sh tensorboard --logdir=runs ``` -------------------------------- ### Example Classifier Docstring (Python) Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/docs/contributing/docs.rst An example of a well-formed reStructuredText docstring for a classifier in CapyMOA. It demonstrates single-line and multi-line descriptions, usage examples, citations, and the structure for 'see also' sections, adhering to Sphinx parsing requirements. ```python from capymoa.base import Classifier from capymoa.stream import Schema class ExampleClassifier(Classifier): """One line docstring. You may add a multi-line detailed description of the classifier. You should include a citation [#example25]_ to the source paper. You may include an example of how to use the classifier. This example is serves as both documentation and a test for the classifier. Keep in mind that these are run as part of the test suite, so they should be kept simple, deterministic, and fast. >>> from capymoa.datasets import ElectricityTiny >>> from capymoa.classifier import ExampleClassifier >>> from capymoa.evaluation import prequential_evaluation >>> stream = ElectricityTiny() >>> learner = ExampleClassifier(stream.get_schema()) >>> results = prequential_evaluation(stream, learner, max_instances=1000) >>> results["cumulative"].accuracy() 87.9 You may include a see also section with links to related classes or functions. This is useful for users to find related functionality in the library. .. seealso:: :func:`capymoa.evaluation.prequential_evaluation` .. [#example25] Example, A., Author, B., & Researcher, C. (2025). Example Classifier. """ class_attr = None """One-line docstring for ``class_attr``.""" def __init__(self, schema: Schema): """Construct a new ExampleClassifier. :param schema: Describes the structure of the data stream. """ super().__init__(schema) #: One-line docstring for ``attr_a``. self.attr_a = None self.attr_b = None """Another syntax for a one-line docstring.""" self.attr_c = None """Multi-line docstring for ``attr_c`` attribute. It can include multiple lines and is useful for providing detailed information about the attribute's purpose and usage. """ ``` -------------------------------- ### Run SSL Evaluation with OSNN Classifier in Python Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/notebooks/SSL_example.ipynb This example demonstrates running a semi-supervised learning evaluation using the OSNN algorithm from CapyMOA. It initializes the Electricity stream and the OSNN classifier, then uses `prequential_ssl_evaluation` with specific parameters for label probability, window size, and maximum instances. The results are stored and displayed. ```python from capymoa.ssl import OSNN stream = Electricity() osnn = OSNN(schema=stream.get_schema(), optim_steps=10) results_osnn = prequential_ssl_evaluation( stream=stream, learner=osnn, label_probability=0.01, window_size=100, max_instances=2000, ) # The results are stored in a dictionary. display(results_osnn) print( results_osnn["cumulative"].accuracy() # Test-then-train accuracy, i.e. cumulatively, not windowed. ) # Plotting over time (default: classifications correct (percent) i.e. accuracy) results_osnn.learner = "OSNN" plot_windowed_results(results_osnn, metric="accuracy") ``` -------------------------------- ### Compare SSL and Supervised Classifiers Visualization Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/notebooks/SSL_example.ipynb This snippet prepares results from different learners (OSNN, SRP10, SLEADE) by assigning learner names and then visualizes their performance using `plot_windowed_results` based on accuracy. ```python # Plotting all the results together # Adding an experiment_id to the results dictionary allows controlling the legend of each learner. results_osnn.learner = "OSNN" results_srp10.learner = "SRP10" results_sleade.learner = "SLEADE" plot_windowed_results(results_osnn, results_srp10, results_sleade, metric="accuracy") ``` -------------------------------- ### Drift Detection Output in Python Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/notebooks/07_pipelines.ipynb Example output indicating detected changes in the data stream during the adaptive learning process. Each 'Detected change at index X' message signifies a point where the drift detector identified a significant shift. ```text Detected change at index 3487 Detected change at index 8735 Detected change at index 10399 Detected change at index 10559 Detected change at index 10751 Detected change at index 11039 Detected change at index 13343 Detected change at index 13855 Detected change at index 17247 Detected change at index 17343 Detected change at index 18623 Detected change at index 18719 Detected change at index 18975 Detected change at index 19295 Detected change at index 21215 Detected change at index 21375 Detected change at index 23359 Detected change at index 23391 Detected change at index 24127 Detected change at index 25023 Detected change at index 25119 Detected change at index 35327 Detected change at index 35487 Detected change at index 39999 Detected change at index 40127 Detected change at index 40991 Detected change at index 41439 ``` -------------------------------- ### Monitor Input Feature Drift with Custom Detector Function Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/notebooks/07_pipelines.ipynb This example demonstrates how to monitor a specific input feature for drift by customizing the drift detector's input function. It defines a function `first_feature_is_gt_zero` to check if the first feature's value is greater than zero and integrates it into the pipeline after the normalization step. ```python from capymoa.drift.detectors import ADWIN from capymoa.instance import LabeledInstance from capymoa.type_alias import LabelIndex from capymoa.datasets import Electricity from capymoa.transformers import MOATransformer, NormalisationFilter, AddNoiseFilter from capymoa.learners import OnlineBagging from capymoa.pipelines import ClassifierPipeline from capymoa.evaluators import ClassificationEvaluator elec_stream = Electricity() # Creating the transformers normalisation_transformer = MOATransformer( schema=elec_stream.get_schema(), moa_filter=NormalisationFilter() ) add_noise_transformer = MOATransformer( schema=normalisation_transformer.get_schema(), moa_filter=AddNoiseFilter() ) # Creating a learner ob_learner = OnlineBagging(schema=add_noise_transformer.get_schema(), ensemble_size=5) # Creating a drift detector drift_detector = ADWIN() # Define a function that prepares the input of the drift detector def first_feature_is_gt_zero( instance: LabeledInstance, prediction: LabelIndex ) -> LabelIndex: feature_val = instance.x[0] return int(feature_val > 0.0) # Creating and populating the pipeline pipeline = ( ClassifierPipeline() .add_transformer(normalisation_transformer) # here, we add the drift detector after the normalization step .add_drift_detector( drift_detector, get_drift_detector_input_func=first_feature_is_gt_zero ) .add_transformer(add_noise_transformer) .add_classifier(ob_learner) ) # Creating the evaluator ob_evaluator = ClassificationEvaluator(schema=elec_stream.get_schema()) i = 0 while elec_stream.has_more_instances(): instance = elec_stream.next_instance() prediction = pipeline.predict(instance) ob_evaluator.update(instance.y_index, prediction) pipeline.train(instance) if drift_detector.detected_change(): print(f"Detected change at index {i}") i += 1 ob_evaluator.accuracy() ``` -------------------------------- ### Initialize ABCD Detector and ElectricityTiny Dataset Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/notebooks/drift_detection.ipynb Initializes the ABCD drift detector and the `ElectricityTiny` dataset from CapyMOA. This setup is used for stream-based drift detection. ```python from capymoa.drift.detectors import ABCD from capymoa.datasets import ElectricityTiny detector = ABCD() ## Opening a file as a stream stream = ElectricityTiny() ``` -------------------------------- ### Create Drift Stream and Evaluate Hoeffding Trees with Delay Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/notebooks/SSL_example.ipynb Demonstrates creating a stream with abrupt drifts using `DriftStream` and `AbruptDrift`. It then evaluates a `HoeffdingTree` both immediately and with a delay, comparing their accuracies and visualizing the results. ```python from capymoa.stream.generator import SEA from capymoa.stream.drift import DriftStream, AbruptDrift from capymoa.classifier import HoeffdingTree ## Creating a stream with drift sea2drifts = DriftStream( stream=[ SEA(function=1), AbruptDrift(position=25000), SEA(function=2), AbruptDrift(position=50000), SEA(function=3), ] ) ht_immediate = HoeffdingTree(schema=sea2drifts.get_schema()) ht_delayed = HoeffdingTree(schema=sea2drifts.get_schema()) results_ht_immediate = prequential_ssl_evaluation( stream=sea2drifts, learner=ht_immediate, label_probability=0.1, window_size=1000, max_instances=100000, ) results_ht_delayed_1000 = prequential_ssl_evaluation( stream=sea2drifts, learner=ht_delayed, label_probability=0.01, delay_length=1000, # adding the delay window_size=1000, max_instances=100000, ) results_ht_immediate.learner = "HT_immediate" results_ht_delayed_1000.learner = "HT_delayed_1000" print(f"Accuracy immediate: {results_ht_immediate['cumulative'].accuracy()}") print( f"Accuracy delayed by 1000 instances: {results_ht_delayed_1000['cumulative'].accuracy()}" ) plot_windowed_results(results_ht_immediate, results_ht_delayed_1000, metric="accuracy") ``` -------------------------------- ### Run Doctest Modules with PyTest Source: https://github.com/adaptive-machine-learning/capymoa/blob/main/docs/contributing/tests.md Executes doctests embedded in Python modules. This command checks the interactive examples within docstrings to verify code correctness and documentation consistency. ```bash pytest --doctest-modules path/to/your/module.py ``` ```bash invoke test.doctest ```