{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "fe74e692",
      "metadata": {},
      "source": [
        "---\n",
        "title: \"シンギュラリティ Machine Learning - マルチバース・コンピューティングによる分類\"\n",
        "description: \"複数の学習器からハイブリッド量子アンサンブル分類器を作成・訓練し、多様性と汎化性能を最適化するQiskit関数（QAOAを用いた）\"\n",
        "---\n",
        "\n",
        "{/* cspell:ignore hyperparameters, sparsify, sparsification, Leclerc */}\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "dde95705",
      "metadata": {},
      "source": [
        "<span id=\"singularity-machine-learning---classification-a-qiskit-function-by-multiverse-computing\" />\n",
        "\n",
        "# 特異点 Machine Learning - 分類: Multiverse Computing による Qiskit 関数\n",
        "\n",
        "*[APIリファレンス](/docs/api/functions/multiverse-computing-singularity)を参照してください*\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=\"パッケージ・バージョン\">\n",
        "    このページのコードは、以下の要件に基づいて開発されました。\n",
        "    これらのバージョン以降のご利用をお勧めします。\n",
        "\n",
        "    ```\n",
        "    scikit-learn~=1.8.0\n",
        "    ```\n",
        "  </AccordionItem>\n",
        "</Accordion>\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "9985b8f4",
      "metadata": {},
      "source": [
        "<Admonition type=\"note\" title=\"注\">\n",
        "  * Qiskit 関数は、 IBM Quantum® Premium Plan、Flex Plan、およびオンプレム ( IBM Quantum Platform API 経由) Plan ユーザーだけが利用できる実験的な機能です。 これらはプレビューリリースの状態であり、変更される可能性がある。\n",
        "</Admonition>\n",
        "\n",
        "<span id=\"overview\" />\n",
        "\n",
        "## 概要\n",
        "\n",
        "Singularity Machine Learning - Classification」機能を使えば、量子の専門知識を必要とせずに、量子ハードウェア上で実世界の機械学習問題を解くことができる。 アンサンブル法に基づくこの応用関数は、ハイブリッド分類器である。 最初のアンサンブル学習には、ブースティング、バギング、スタッキングといった古典的な手法を活用する。 その後、変分量子固有値解法（VQE）や量子近似最適化アルゴリズム（QAOA）などの量子アルゴリズムを採用し、学習済みアンサンブルの多様性、汎化能力、全体的な複雑性を向上させる。\n",
        "\n",
        "他の量子機械学習ソリューションとは異なり、この関数は、対象となるQPUの量子ビット数に制限されることなく、数百万の例と特徴を持つ大規模なデータセットを扱うことができる。 量子ビットの数は、学習可能なアンサンブルのサイズを決定するだけである。 また、非常に柔軟性があり、金融、ヘルスケア、サイバーセキュリティを含む幅広い分野の分類問題の解決に利用できます。\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "353e72a4",
      "metadata": {},
      "source": [
        "高次元でノイズが多く、不均衡なデータセットを含む古典的な難問に対して、一貫して高い精度を達成している。\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "339c5737",
      "metadata": {},
      "source": [
        "![仕組み](https://quantum.cloud.ibm.com/docs/images/guides/multiverse-computing-singularity/how_it_works.avif)\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "0639e5e5",
      "metadata": {},
      "source": [
        "そのために作られた：\n",
        "\n",
        "1. 量子機械学習を製品やサービスに組み込むことで、技術提供を強化しようとしている企業のエンジニアやデータサイエンティスト、\n",
        "2. 量子研究所の研究者は、量子機械学習の応用を模索し、分類作業に量子コンピューティングを活用しようとしている\n",
        "3. 機械学習などのコースで、量子コンピューティングの利点を実証しようとしている教育機関の学生や教師。\n",
        "\n",
        "以下の例では、 `create`、 `list`、 `fit`、 `predict` を含む様々な機能を紹介し、非線形の決定境界であるため難問として知られる、2つのインターリーブ半円からなる合成問題での使い方を示します。\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "ccf056e3",
      "metadata": {},
      "source": [
        "{/* cspell:ignore quantumly */}\n",
        "\n",
        "<span id=\"function-description\" />\n",
        "\n",
        "## 関数の説明\n",
        "\n",
        "この Qiskit 関数を使用すると、Singularity の量子強化アンサンブル分類器を使用してバイナリ分類問題を解くことができます。 その裏では、ハイブリッド・アプローチを使って、ラベル付きデータセット上で分類器のアンサンブルを古典的に訓練し、 IBM® QPU上で量子近似最適化アルゴリズム（QAOA）を使って多様性と汎化性を最大化するように最適化する。 ユーザーフレンドリーなインターフェイスを通じて、ユーザーは要件に応じて分類器を設定し、選択したデータセットで訓練し、未見のデータセットで予測を行うために使用することができます。\n",
        "\n",
        "一般的な分類問題を解く：\n",
        "\n",
        "1. データセットを前処理し、トレーニングセットとテストセットに分ける。 オプションで、訓練セットをさらに訓練セットと検証セットに分けることができる。 これは [scikit-learnを使って](https://scikit-learn.org/1.5/modules/generated/sklearn.model_selection.train_test_split.html)実現できる。\n",
        "2. トレーニングセットが不均衡な場合は、 [imbalanced-learnを使って](https://imbalanced-learn.org/stable/introduction.html#problem-statement-regarding-imbalanced-data-sets)クラスのバランスをとるために再サンプリングすることができる。\n",
        "3. トレーニングセット、検証セット、テストセットを別々に、カタログの `file_upload` メソッドを使用して関数のストレージにアップロードし、関連するパスを毎回渡します。\n",
        "4. `create` 学習者の数や種類、正則化（ラムダ値）、最適化オプション（レイヤー数、古典オプティマイザの種類、量子バックエンドなど）を含むハイパーパラメータを受け付けます。\n",
        "5. この関数の `fit` アクションを使用して、訓練セットで量子分類器を訓練します。訓練セットにはラベルを付け、検証セット（該当する場合）を渡します。\n",
        "6. 関数の `predict` アクションを使用して、以前に未見のテストセットで予測を行う。\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "26472870",
      "metadata": {},
      "source": [
        "***\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "73390a19",
      "metadata": {},
      "source": [
        "<span id=\"get-started\" />\n",
        "\n",
        "## 使用を開始する\n",
        "\n",
        "[IBM Quantum Platform API キーを](http://quantum.cloud.ibm.com/)使用して認証し、以下のように Qiskit Function を選択します：\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "id": "95a715d2",
      "metadata": {},
      "outputs": [],
      "source": [
        "from qiskit_ibm_catalog import QiskitFunctionsCatalog\n",
        "\n",
        "catalog = QiskitFunctionsCatalog(channel=\"ibm_quantum_platform\")\n",
        "\n",
        "# load function\n",
        "singularity = catalog.load(\"multiverse/singularity\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "e8837f5f",
      "metadata": {},
      "source": [
        "<span id=\"examples\" />\n",
        "\n",
        "## 例\n",
        "\n",
        "<span id=\"classify-a-dataset\" />\n",
        "\n",
        "### データセットを分類する\n",
        "\n",
        "この例では、\"Singularity Machine Learning - Classification \"関数を使って、2つの月の形をした半円が交互に並んだデータセットを分類します。 データセットは合成された2次元で、2値ラベルでラベル付けされている。 セントロイドベースのクラスタリングや線形分類のようなアルゴリズムにとって挑戦的であるように作成されている。\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "b12f9ee4",
      "metadata": {},
      "source": [
        "![月のデータセット](https://quantum.cloud.ibm.com/docs/images/guides/multiverse-computing-singularity/moon_shaped.avif)\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "b3cedca5",
      "metadata": {},
      "source": [
        "このプロセスを通して、分類器を作成する方法、学習データに適合させる方法、テストデータでの予測に使用する方法、そして終了時に分類器を削除する方法を学びます。\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "dba5a40e",
      "metadata": {},
      "source": [
        "始める前に、 [scikit-learnを](https://scikit-learn.org/)インストールする必要がある。 以下のコマンドでインストールする：\n",
        "\n",
        "```sh\n",
        "python3 -m pip install scikit-learn\n",
        "```\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "ba982810",
      "metadata": {},
      "source": [
        "以下のステップを実行します。\n",
        "\n",
        "1. [scikit-learn](https://scikit-learn.org/) の [`make_moons`](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_moons.html) 関数を使用して、合成データセットを作成します。\n",
        "2. 生成された合成データセットを[共有データディレクトリ](https://qiskit.github.io/qiskit-serverless/function_features/experimental/manage_data_directory.html)にアップロードしてください。\n",
        "3. action [`create`](/docs/api/functions/multiverse-computing-singularity#create) を使用して、量子強化型分類器を作成します。\n",
        "4. アクション [`list`](/docs/api/functions/multiverse-computing-singularity#list) を使用して、分類器を登録してください。\n",
        "5. [`fit`](/docs/api/functions/multiverse-computing-singularity#fit) action を使用して、トレーニングデータで分類器を学習させます。\n",
        "6. トレーニング済みの分類器を使用して、[`predict`](/docs/api/functions/multiverse-computing-singularity#predict) action アクションを通じてテストデータに対する予測を行います。\n",
        "7. アクション [`delete`](/docs/api/functions/multiverse-computing-singularity#delete) を使用して、分類子を削除します。\n",
        "8. 終わったら片付ける。\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "c1877f96",
      "metadata": {},
      "source": [
        "**ステップ 1.** 必要なモジュールをインポートして合成データセットを生成し、それをトレーニングデータセットとテストデータセットに分割する。\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": [
        "**ステップ 2.** ラベル付きトレーニングデータセットとテストデータセットをローカルディスクに保存し、 [共有データディレクトリ](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": [
        "**ステップ 3.** action [`create`](/docs/api/functions/multiverse-computing-singularity#create) を使用して、量子強化型分類器を作成します。\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": [
        "**ステップ 4.** action [`fit`](/docs/api/functions/multiverse-computing-singularity#fit) を使用して、量子強化分類器を学習させます。\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": [
        "**ステップ5.** アクション [`predict`](/docs/api/functions/multiverse-computing-singularity#predict) を使用して、量子強化分類器から予測値と確率を取得します。\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": [
        "**ステップ 6.** アクション [`delete`](/docs/api/functions/multiverse-computing-singularity#delete) を使用して、量子強化分類器を削除します。\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": [
        "**ステップ7.** ローカルおよび共有データディレクトリをクリーンアップする。\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": [
        "<span id=\"create_fit_predict-example\" />\n",
        "\n",
        "### `create_fit_predict`例\n",
        "\n",
        "次の例は、このアクションの [`create_fit_predict`](/docs/api/functions/multiverse-computing-singularity#create_fit_predict) 動作を示しています。\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 QiskitFunctionsCatalog to load the\n",
        "# \"Singularity Machine Learning - Classification\" function by Multiverse Computing\n",
        "from qiskit_ibm_catalog import QiskitFunctionsCatalog\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 = QiskitFunctionsCatalog(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": "5cc6f2b3",
      "metadata": {},
      "source": [
        "<span id=\"benchmarks\" />\n",
        "\n",
        "## ベンチマーク\n",
        "\n",
        "これらのベンチマークは、この分類器が困難な問題に対して極めて高い精度を達成できることを示している。 また、アンサンブルの学習者数（量子ビットの数）を増やすと精度が上がることも示している。\n",
        "\n",
        "「古典的精度」とは、この場合、サイズ75のアンサンブルに基づく AdaBoost 分類器である。 一方、\"量子精度 \"とは、\"特異点 Machine Learning - 分類 \"を使って得られた精度のことである。\n",
        "\n",
        "| 問題点     | データセット・サイズ | アンサンブル・サイズ | キュービット数 | 古典的な精度 | 量子精度 | 向上  |\n",
        "| ------- | ---------- | ---------- | ------- | ------ | ---- | --- |\n",
        "| 送電網の安定性 | 5000例、12機能 | 55カ所       | 55カ所    | 76%    | 91%  | 15％ |\n",
        "| 送電網の安定性 | 5000例、12機能 | 65         | 65      | 76%    | 92%  | 16％ |\n",
        "| 送電網の安定性 | 5000例、12機能 | 75%        | 75%     | 76%    | 94%  | 18％ |\n",
        "| 送電網の安定性 | 5000例、12機能 | 85         | 85      | 76%    | 94%  | 18％ |\n",
        "| 送電網の安定性 | 5000例、12機能 | 100        | 100     | 76%    | 95%  | 19% |\n",
        "\n",
        "***\n",
        "\n",
        "量子ハードウェアが進化し、スケールアップするにつれて、我々の量子分類器への影響はますます大きくなる。 量子ビットの数は、利用できるアンサンブルのサイズに制限を課すが、処理できるデータ量に制限はない。 この強力な機能により、分類器は何百万ものデータポイントと何千もの特徴を含むデータセットを効率的に扱うことができる。 重要なのは、アンサンブル・サイズに関する制約は、大規模版の分類器を実装することで対処できるということである。 反復的なアウター・ループ・アプローチを活用することで、アンサンブルを動的に拡張し、柔軟性と全体的なパフォーマンスを向上させることができる。 しかし、この機能は現在の分類器にはまだ実装されていないことは注目に値する。\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "cddff465",
      "metadata": {},
      "source": [
        "<span id=\"changelog\" />\n",
        "\n",
        "## 変更ログ\n",
        "\n",
        "<span id=\"4-june-2025\" />\n",
        "\n",
        "### 2025年6月4日\n",
        "\n",
        "* `QuantumEnhancedEnsembleClassifier` をアップグレードし、以下のアップデートを行った：\n",
        "  * オンサイト/アルファ正則化を追加。 `regularization_type` 、 `onsite` または `alpha`\n",
        "  * 自動正則化を追加。 自動正則化を使用するには、 `regularization` を `auto` に設定します\n",
        "  * `fit` メソッドに、量子最適化用の最適化データを選択するための `optimization_data` パラメータを追加。 これらのオプションのいずれかを使用できます： `train` `validation` または `both`\n",
        "  * 全体的なパフォーマンスの向上\n",
        "* 実行中のジョブの詳細なステータス追跡機能を追加\n",
        "\n",
        "<span id=\"20-may-2025\" />\n",
        "\n",
        "### 2025年5月20日\n",
        "\n",
        "* 標準化されたエラー処理\n",
        "\n",
        "<span id=\"18-march-2025\" />\n",
        "\n",
        "### 2025年3月18日\n",
        "\n",
        "* qiskit-serverless を 0.20.0 にアップグレードし、ベースイメージを 0.20.1\n",
        "\n",
        "<span id=\"14-february-2025\" />\n",
        "\n",
        "### 2025 年 2 月 14 日\n",
        "\n",
        "* ベース・イメージを次のようにアップグレードした。 0.19.1\n",
        "\n",
        "<span id=\"6-february-2025\" />\n",
        "\n",
        "### 2025年2月6日\n",
        "\n",
        "* qiskit-serverless を 0.19.0 にアップグレードし、ベースイメージを 0.19.0\n",
        "\n",
        "<span id=\"13-november-2024\" />\n",
        "\n",
        "### 2024年11月13日\n",
        "\n",
        "* シンギュラリティのリリース Machine Learning - 分類\n",
        "\n",
        "<span id=\"get-support\" />\n",
        "\n",
        "## サポートの利用\n",
        "\n",
        "ご質問は [Multiverse Computingまでお問い合わせ](mailto:singularity@multiversecomputing.com)ください。\n",
        "\n",
        "次の情報を必ずご記入ください。\n",
        "\n",
        "* Qiskitファンクション 求人ID (`job.job_id`)\n",
        "* 問題の詳細\n",
        "* 関連するエラーメッセージやコード\n",
        "* 問題を再現する手順\n",
        "\n",
        "<span id=\"next-steps\" />\n",
        "\n",
        "## 次のステップ\n",
        "\n",
        "<Admonition type=\"tip\" title=\"推奨事項\">\n",
        "  * [Multiverse Computingの特異点 Machine Learning 分類機能への](/functions?id=multiverse-singularity)アクセスをリクエストする。\n",
        "  * このQiskit関数の [APIリファレンス](/docs/api/functions/multiverse-computing-singularity)をご覧ください。\n",
        "  * レビュー [レクレール, L., et al. (2023). 中性原子量子プロセッサにおける金融リスク管理 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
}