{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "b1c4e7a2",
      "metadata": {},
      "source": [
        "---\n",
        "title: Get started with Singularity Machine Learning - Classification by Multiverse Computing\n",
        "description: Load the Singularity Machine Learning - Classification function and use it to create, train, and run a hybrid quantum ensemble classifier.\n",
        "---\n",
        "\n",
        "{/* cspell:ignore Leclerc */}\n",
        "\n",
        "# Get started with Singularity Machine Learning - Classification by Multiverse Computing\n",
        "\n",
        "*See the [overview](/docs/functions/multiverse-computing-singularity) and the [API reference](/docs/functions/multiverse-computing-singularity/api-reference)*\n",
        "\n",
        "<Admonition type=\"note\" title=\"Note\">\n",
        "  * IBM Quantum® Functions are a beta feature available only to IBM Quantum Premium Plan, Flex Plan, and On-Prem (through the IBM Quantum Platform API) Plan users. Beta features are subject to change.\n",
        "</Admonition>\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "99db0bb4",
      "metadata": {
        "tags": [
          "version-info"
        ]
      },
      "source": [
        "{/*\n",
        "  DO NOT EDIT THIS CELL!!!\n",
        "  This cell's content is generated automatically by a script. Anything you add\n",
        "  here will be removed next time the notebook is run. To add new content, create\n",
        "  a new cell before or after this one.\n",
        "  */}\n",
        "\n",
        "<Accordion>\n",
        "  <AccordionItem title=\"Package versions\">\n",
        "    The code on this page was developed using the following requirements.\n",
        "    We recommend using these versions or newer.\n",
        "\n",
        "    ```\n",
        "    scikit-learn~=1.8.0\n",
        "    ```\n",
        "  </AccordionItem>\n",
        "</Accordion>\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "73390a19",
      "metadata": {},
      "source": [
        "## Set up and load the function\n",
        "\n",
        "Authenticate using your [IBM Quantum Platform API key](http://quantum.cloud.ibm.com/), and select the quantum function as follows:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "id": "95a715d2",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "[QiskitFunction(qunova/hivqe-chemistry),\n",
              " QiskitFunction(global-data-quantum/quantum-portfolio-optimizer),\n",
              " QiskitFunction(algorithmiq/tem),\n",
              " QiskitFunction(qedma/qesem),\n",
              " QiskitFunction(multiverse/singularity),\n",
              " QiskitFunction(ibm/circuit-function),\n",
              " QiskitFunction(q-ctrl/optimization-solver),\n",
              " QiskitFunction(colibritd/quick-pde),\n",
              " QiskitFunction(q-ctrl/performance-management),\n",
              " QiskitFunction(kipu-quantum/iskay-quantum-optimizer)]"
            ]
          },
          "execution_count": 6,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "from qiskit_ibm_catalog import FunctionsCatalog\n",
        "\n",
        "catalog = FunctionsCatalog(channel=\"ibm_quantum_platform\")\n",
        "\n",
        "# Verify that you have access to the function\n",
        "catalog.list()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "id": "b83c0077-412e-4f06-9e34-51599ffa7183",
      "metadata": {},
      "outputs": [],
      "source": [
        "# load function\n",
        "singularity = catalog.load(\"multiverse/singularity\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "e8837f5f",
      "metadata": {},
      "source": [
        "## Examples\n",
        "\n",
        "### Classify a dataset\n",
        "\n",
        "In this example, you'll use the \"Singularity Machine Learning - Classification\" function to classify a dataset consisting of two interleaving, moon-shaped half-circles. The dataset is synthetic, two-dimensional, and labeled with binary labels. It is created to be challenging for algorithms such as centroid-based clustering and linear classification.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "b12f9ee4",
      "metadata": {},
      "source": [
        "![Moons dataset](https://quantum.cloud.ibm.com/docs/images/guides/multiverse-computing-singularity/moon_shaped.avif)\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "b3cedca5",
      "metadata": {},
      "source": [
        "Through this process, you'll learn how to create the classifier, fit it to the training data, use it to predict on the test data, and delete the classifier when you're finished.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "dba5a40e",
      "metadata": {},
      "source": [
        "Before starting, you need to install [scikit-learn](https://scikit-learn.org/). Install it using the following command:\n",
        "\n",
        "```sh\n",
        "python3 -m pip install scikit-learn\n",
        "```\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "ba982810",
      "metadata": {},
      "source": [
        "Perform the following steps:\n",
        "\n",
        "1. Create the synthetic dataset using the [`make_moons`](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_moons.html) function from [scikit-learn](https://scikit-learn.org/).\n",
        "2. Upload the generated synthetic dataset to the [shared data directory](https://qiskit.github.io/qiskit-serverless/function_features/experimental/manage_data_directory.html).\n",
        "3. Create the quantum-enhanced classifier using the [`create`](/docs/functions/multiverse-computing-singularity/api-reference#create) action.\n",
        "4. Enlist your classifiers using the [`list`](/docs/functions/multiverse-computing-singularity/api-reference#list) action.\n",
        "5. Train the classifier on the train data using the [`fit`](/docs/functions/multiverse-computing-singularity/api-reference#fit) action.\n",
        "6. Use the trained classifier to predict on the test data using the [`predict`](/docs/functions/multiverse-computing-singularity/api-reference#predict) action.\n",
        "7. Delete the classifier using the [`delete`](/docs/functions/multiverse-computing-singularity/api-reference#delete) action.\n",
        "8. Clean up after you're done.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "c1877f96",
      "metadata": {},
      "source": [
        "**Step 1.** Import the necessary modules and generate the synthetic dataset, then split it into training and test datasets.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "id": "731db300",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Features: [[ 0.84757037 -0.48831433]\n",
            " [ 0.98132552  0.19235443]\n",
            " [-0.71626723  0.6978261 ]\n",
            " [ 1.18957848 -0.48186557]\n",
            " [ 0.52118982 -0.37791846]\n",
            " [ 0.81115408  0.58483251]\n",
            " [ 0.48706462  0.87336593]\n",
            " [-0.81880144  0.57407682]\n",
            " [ 1.67335408 -0.23932015]\n",
            " [ 0.50181306  0.8649761 ]]\n",
            "Targets: [1 0 0 1 1 0 0 0 1 0]\n"
          ]
        }
      ],
      "source": [
        "# import the necessary modules for this example\n",
        "import os\n",
        "import tarfile\n",
        "import numpy as np\n",
        "\n",
        "# Import the make_moons and the train_test_split functions from scikit-learn\n",
        "# to create a synthetic dataset and split it into training and test datasets\n",
        "from sklearn.datasets import make_moons\n",
        "from sklearn.model_selection import train_test_split\n",
        "\n",
        "# generate the synthetic dataset\n",
        "X, y = make_moons(n_samples=10000)\n",
        "\n",
        "# split the data into training and test datasets\n",
        "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n",
        "\n",
        "# print the first 10 samples of the training dataset\n",
        "print(\"Features:\", X_train[:10, :])\n",
        "print(\"Targets:\", y_train[:10])"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "639f459f",
      "metadata": {},
      "source": [
        "**Step 2.** Save the labeled training and test datasets on your local disk, and then upload them to the [shared data directory](https://qiskit.github.io/qiskit-serverless/function_features/experimental/manage_data_directory.html).\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "id": "7265965f",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "['X_test.npy.tar', 'X_train.npy.tar', 'y_test.npy.tar', 'y_train.npy.tar']\n"
          ]
        }
      ],
      "source": [
        "def make_tarfile(file_path, tar_file_name):\n",
        "    with tarfile.open(tar_file_name, \"w\") as tar:\n",
        "        tar.add(file_path, arcname=os.path.basename(file_path))\n",
        "\n",
        "\n",
        "# save the training and test datasets on your local disk\n",
        "np.save(\"X_train.npy\", X_train)\n",
        "np.save(\"y_train.npy\", y_train)\n",
        "np.save(\"X_test.npy\", X_test)\n",
        "np.save(\"y_test.npy\", y_test)\n",
        "\n",
        "# create tar files for the datasets\n",
        "make_tarfile(\"X_train.npy\", \"X_train.npy.tar\")\n",
        "make_tarfile(\"y_train.npy\", \"y_train.npy.tar\")\n",
        "make_tarfile(\"X_test.npy\", \"X_test.npy.tar\")\n",
        "make_tarfile(\"y_test.npy\", \"y_test.npy.tar\")\n",
        "\n",
        "# upload the datasets to the shared data directory\n",
        "catalog.file_upload(\"X_train.npy.tar\", singularity)\n",
        "catalog.file_upload(\"y_train.npy.tar\", singularity)\n",
        "catalog.file_upload(\"X_test.npy.tar\", singularity)\n",
        "catalog.file_upload(\"y_test.npy.tar\", singularity)\n",
        "\n",
        "# view/enlist the uploaded files in the shared data directory\n",
        "print(catalog.files(singularity))"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "f52caa63",
      "metadata": {},
      "source": [
        "**Step 3.** Create a quantum-enhanced classifier using the [`create`](/docs/functions/multiverse-computing-singularity/api-reference#create) action.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "id": "d56e1440",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "{'status': 'ok', 'message': 'Classifier created.', 'data': {}, 'metadata': {'resource_usage': {}}}\n"
          ]
        }
      ],
      "source": [
        "job = singularity.run(\n",
        "    action=\"create\",\n",
        "    name=\"my_classifier\",\n",
        "    num_learners=10,\n",
        "    learners_types=[\n",
        "        \"DecisionTreeClassifier\",\n",
        "        \"KNeighborsClassifier\",\n",
        "    ],\n",
        "    learners_proportions=[0.5, 0.5],\n",
        "    learners_options=[{}, {}],\n",
        "    regularization=0.01,\n",
        "    weight_update_method=\"logarithmic\",\n",
        "    sample_scaling=True,\n",
        "    optimizer_options={\"simulator\": True},\n",
        "    voting=\"soft\",\n",
        "    prob_threshold=0.5,\n",
        ")\n",
        "\n",
        "print(job.result())"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "id": "f5a54432",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "{'status': 'ok', 'message': 'Classifiers listed.', 'data': {'classifiers': ['my_classifier']}, 'metadata': {'resource_usage': {}}}\n"
          ]
        },
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "['X_test.npy.tar', 'X_train.npy.tar', 'my_classifier.pkl.tar', 'y_test.npy.tar', 'y_train.npy.tar']\n"
          ]
        }
      ],
      "source": [
        "# list available classifiers using the list action\n",
        "job = singularity.run(action=\"list\")\n",
        "\n",
        "print(job.result())\n",
        "\n",
        "# you can also find your classifiers in the shared data directory with a *.pkl.tar extension\n",
        "print(catalog.files(singularity))"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "504ddc09",
      "metadata": {},
      "source": [
        "**Step 4.** Train the quantum-enhanced classifier using the [`fit`](/docs/functions/multiverse-computing-singularity/api-reference#fit) action.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "id": "13699d25",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "{'status': 'ok', 'message': 'Classifier fitted.', 'data': {}, 'metadata': {'resource_usage': {'RUNNING: MAPPING': {'CPU_TIME': 13.655871629714966}, 'RUNNING: WAITING_QPU': {'CPU_TIME': 54.688621282577515}, 'RUNNING: POST_PROCESSING': {'CPU_TIME': 56.92286920547485}, 'RUNNING: EXECUTING_QPU': {'QPU_TIME': 57.92738223075867}}}}\n"
          ]
        }
      ],
      "source": [
        "job = singularity.run(\n",
        "    action=\"fit\",\n",
        "    name=\"my_classifier\",\n",
        "    X=\"X_train.npy\",  # you do not need to specify the tar extension\n",
        "    y=\"y_train.npy\",  # you do not need to specify the tar extension\n",
        ")\n",
        "\n",
        "print(job.result())"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "76ef149b",
      "metadata": {},
      "source": [
        "**Step 5.** Obtain predictions and probabilities from the quantum-enhanced classifier using the [`predict`](/docs/functions/multiverse-computing-singularity/api-reference#predict) action.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "id": "92f35d5a",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Action result status:  ok\n",
            "Action result message:  Classifier predicted.\n",
            "Predictions (first five results): [0, 0, 1, 0, 1]\n",
            "Probabilities (first five results): [[1.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 0.0], [0.0, 1.0]]\n"
          ]
        }
      ],
      "source": [
        "job = singularity.run(\n",
        "    action=\"predict\",\n",
        "    name=\"my_classifier\",\n",
        "    X=\"X_test.npy\",  # you do not need to specify the tar extension\n",
        ")\n",
        "\n",
        "result = job.result()\n",
        "\n",
        "print(\"Action result status: \", result[\"status\"])\n",
        "print(\"Action result message: \", result[\"message\"])\n",
        "print(\"Predictions (first five results):\", result[\"data\"][\"predictions\"][:5])\n",
        "print(\n",
        "    \"Probabilities (first five results):\", result[\"data\"][\"probabilities\"][:5]\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "1980104c",
      "metadata": {},
      "source": [
        "**Step 6.** Delete the quantum-enhanced classifier using the [`delete`](/docs/functions/multiverse-computing-singularity/api-reference#delete) action.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 8,
      "id": "c4705154",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "{'status': 'ok', 'message': 'Classifier deleted.', 'data': {}, 'metadata': {'resource_usage': {}}}\n"
          ]
        }
      ],
      "source": [
        "job = singularity.run(\n",
        "    action=\"delete\",\n",
        "    name=\"my_classifier\",\n",
        ")\n",
        "\n",
        "# or you can delete from the shared data directory\n",
        "# catalog.file_delete(\"my_classifier.pkl.tar\", singularity)\n",
        "\n",
        "print(job.result())"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "30b34179",
      "metadata": {},
      "source": [
        "**Step 7.** Clean up local and shared data directories.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 9,
      "id": "6c64ea2b",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "'Requested file was deleted.'"
            ]
          },
          "execution_count": 9,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# delete the numpy files from your local disk\n",
        "os.remove(\"X_train.npy\")\n",
        "os.remove(\"y_train.npy\")\n",
        "os.remove(\"X_test.npy\")\n",
        "os.remove(\"y_test.npy\")\n",
        "\n",
        "# delete the tar files from your local disk\n",
        "os.remove(\"X_train.npy.tar\")\n",
        "os.remove(\"y_train.npy.tar\")\n",
        "os.remove(\"X_test.npy.tar\")\n",
        "os.remove(\"y_test.npy.tar\")\n",
        "\n",
        "# delete the tar files from the shared data\n",
        "catalog.file_delete(\"X_train.npy.tar\", singularity)\n",
        "catalog.file_delete(\"y_train.npy.tar\", singularity)\n",
        "catalog.file_delete(\"X_test.npy.tar\", singularity)\n",
        "catalog.file_delete(\"y_test.npy.tar\", singularity)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "f25d06ee",
      "metadata": {},
      "source": [
        "### `create_fit_predict` example\n",
        "\n",
        "The following example demonstrates the [`create_fit_predict`](/docs/functions/multiverse-computing-singularity/api-reference#create_fit_predict) action.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 10,
      "id": "79cdedc0",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Job status:  QUEUED\n",
            "Action result status:  ok\n",
            "Action result message:  Classifier created, fitted, and predicted.\n",
            "Predictions (first five results):  [0, 0, 1, 0, 0]\n",
            "Probabilities (first five results):  [[0.87119766531518, 0.1288023346848197], [0.87119766531518, 0.1288023346848197], [0.24470328446479797, 0.7552967155352032], [0.820524432250189, 0.17947556774981072], [0.6847610293419495, 0.31523897065805173]]\n",
            "Usage metadata:  {'RUNNING: MAPPING': {'CPU_TIME': 10.967791318893433}, 'RUNNING: WAITING_QPU': {'CPU_TIME': 59.91712307929993}, 'RUNNING: POST_PROCESSING': {'CPU_TIME': 59.097386837005615}, 'RUNNING: EXECUTING_QPU': {'QPU_TIME': 56.93338203430176}}\n"
          ]
        }
      ],
      "source": [
        "# Import FunctionsCatalog to load the\n",
        "# \"Singularity Machine Learning - Classification\" function by Multiverse Computing\n",
        "from qiskit_ibm_catalog import FunctionsCatalog\n",
        "\n",
        "# Import the make_moons and the train_test_split functions from scikit-learn\n",
        "# to create a synthetic dataset and split it into training and test datasets\n",
        "from sklearn.datasets import make_moons\n",
        "from sklearn.model_selection import train_test_split\n",
        "\n",
        "# authentication\n",
        "# If you have not previously saved your credentials, follow instructions at\n",
        "# /docs/guides/functions\n",
        "# to authenticate with your API key.\n",
        "catalog = FunctionsCatalog(channel=\"ibm_quantum_platform\")\n",
        "\n",
        "# load \"Singularity Machine Learning - Classification\" function by Multiverse Computing\n",
        "singularity = catalog.load(\"multiverse/singularity\")\n",
        "\n",
        "# generate the synthetic dataset\n",
        "X, y = make_moons(n_samples=1000)\n",
        "\n",
        "# split the data into training and test datasets\n",
        "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n",
        "\n",
        "job = singularity.run(\n",
        "    action=\"create_fit_predict\",\n",
        "    num_learners=10,\n",
        "    regularization=0.01,\n",
        "    optimizer_options={\"simulator\": True},\n",
        "    X_train=X_train,\n",
        "    y_train=y_train,\n",
        "    X_test=X_test,\n",
        "    options={\"save\": False},\n",
        ")\n",
        "\n",
        "# get job status and result\n",
        "status = job.status()\n",
        "result = job.result()\n",
        "\n",
        "print(\"Job status: \", status)\n",
        "print(\"Action result status: \", result[\"status\"])\n",
        "print(\"Action result message: \", result[\"message\"])\n",
        "print(\"Predictions (first five results): \", result[\"data\"][\"predictions\"][:5])\n",
        "print(\n",
        "    \"Probabilities (first five results): \",\n",
        "    result[\"data\"][\"probabilities\"][:5],\n",
        ")\n",
        "print(\"Usage metadata: \", result[\"metadata\"][\"resource_usage\"])"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "e5a8c1d3",
      "metadata": {},
      "source": [
        "## Next steps\n",
        "\n",
        "<Admonition type=\"tip\" title=\"Recommendations\">\n",
        "  * Visit the [API reference](/docs/functions/multiverse-computing-singularity/api-reference) for this quantum function.\n",
        "  * Learn how to choose a [problem size](/docs/managed-workflows/managed-workflow-compute-profiles#match-sizes).\n",
        "  * Review [Leclerc, L., et al. (2023). Financial risk management on a neutral atom quantum processor. Physical Review Research, 5, 043117](https://journals.aps.org/prresearch/pdf/10.1103/PhysRevResearch.5.043117).\n",
        "</Admonition>\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "id": "a1b8767d",
      "source": "© IBM Corp., 2017-2026"
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}