├── .DS_Store
├── .gitignore
├── .travis.yml
├── .vscode
└── settings.json
├── CITATION.md
├── LICENSE
├── MANIFEST.in
├── Pipfile
├── Pipfile.lock
├── README.md
├── Untitled.ipynb
├── Untitled.py
├── archive
└── qmnist.py
├── docs
├── DOCUMENT.md
├── document.txt
└── index.html
├── image
└── qwgc_logo.png
├── label.txt
├── nohup.out
├── notebook
├── Plots.ipynb
├── Plots.py
├── qwgc_tutorial.ipynb
├── qwgc_tutorial.py
├── random_walk.ipynb
└── random_walk.py
├── qwgc
├── QWGC.py
├── QWGC_mix.py
├── QW_kernel.py
├── __init__.py
├── classifier
│ ├── __init__.py
│ ├── costfunc.py
│ └── qcircuit.py
├── experiments.toml
├── preprocess
│ ├── __init__.py
│ ├── gparse.py
│ ├── qwalk.py
│ └── qwfilter.py
└── utils
│ └── .gitignore
├── requirements.txt
├── result.txt
├── result2.txt
├── setup.py
└── test
└── test_QWGC.py
/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/qwqmlf/qwgc/d06c805023bf37a1252505f7dc6e30461d861440/.DS_Store
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | pip-wheel-metadata/
24 | share/python-wheels/
25 | *.egg-info/
26 | .installed.cfg
27 | *.egg
28 | MANIFEST
29 |
30 | # PyInstaller
31 | # Usually these files are written by a python script from a template
32 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
33 | *.manifest
34 | *.spec
35 |
36 | # Installer logs
37 | pip-log.txt
38 | pip-delete-this-directory.txt
39 |
40 | # Unit test / coverage reports
41 | htmlcov/
42 | .tox/
43 | .nox/
44 | .coverage
45 | .coverage.*
46 | .cache
47 | nosetests.xml
48 | coverage.xml
49 | *.cover
50 | *.py,cover
51 | .hypothesis/
52 | .pytest_cache/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | target/
76 |
77 | # Jupyter Notebook
78 | .ipynb_checkpoints
79 |
80 | # IPython
81 | profile_default/
82 | ipython_config.py
83 |
84 | # pyenv
85 | .python-version
86 |
87 | # pipenv
88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
91 | # install all needed dependencies.
92 | #Pipfile.lock
93 |
94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
95 | __pypackages__/
96 |
97 | # Celery stuff
98 | celerybeat-schedule
99 | celerybeat.pid
100 |
101 | # SageMath parsed files
102 | *.sage.py
103 |
104 | # Environments
105 | .env
106 | .venv
107 | env/
108 | venv/
109 | ENV/
110 | env.bak/
111 | venv.bak/
112 |
113 | # Spyder project settings
114 | .spyderproject
115 | .spyproject
116 |
117 | # Rope project settings
118 | .ropeproject
119 |
120 | # mkdocs documentation
121 | /site
122 |
123 | # mypy
124 | .mypy_cache/
125 | .dmypy.json
126 | dmypy.json
127 |
128 | # Pyre type checker
129 | .pyre/
130 |
131 | ./qwgc/utils/notification.py
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: python
2 |
3 | dist: bionic
4 |
5 | python:
6 | - 3.6
7 |
8 | install:
9 | - pip install -e .
10 |
11 | script:
12 | # This repository has NOT had tests
13 | # but Travis CI wouldn't allow us not to write
14 | # `script` so we run this meaning less command to avoid CI errors.
15 | - echo "TODO"
16 |
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "python.linting.flake8Enabled": true,
3 | "python.linting.pycodestyleEnabled": false,
4 | "python.linting.pydocstyleEnabled": false,
5 | "python.linting.enabled": true
6 | }
--------------------------------------------------------------------------------
/CITATION.md:
--------------------------------------------------------------------------------
1 |
2 | # Citations
3 |
4 | - Barr, Katie, Toby Fleming, and Viv Kendon. "Simulation methods for quantum walks on graphs applied to perfect state transfer and formal language recognition." CoSMoS 2013 (2013): 1.
5 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [2020] [Ryosuke Satoh]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | requirements.txt
--------------------------------------------------------------------------------
/Pipfile:
--------------------------------------------------------------------------------
1 | [[source]]
2 | name = "pypi"
3 | url = "https://pypi.org/simple"
4 | verify_ssl = true
5 |
6 | [dev-packages]
7 |
8 | [packages]
9 | qiskit = "*"
10 | tqdm = "*"
11 | umap-learn = "*"
12 | grakel-dev = "==0.1a6"
13 | autopep8 = "*"
14 | seaborn = "*"
15 | toml = "*"
16 | slackweb = "*"
17 | grakel = "==0.1b7"
18 | cryptography = "*"
19 |
20 | [requires]
21 | python_version = "3.7"
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | # qwgc
3 |
4 | [](https://opensource.org/licenses/Apache-2.0)
5 |
6 |
7 |
8 | qwgc stands for *Q*uantum *W*alk *G*raph *C*lassifier.
9 | This project aims to classify graph data with high accuracy.
10 | The key ideas of quantum machine learning and quantum walk are [here](https://qwqmlft.github.io/QuantumFrontier).
11 |
12 |
13 | ## How to install
14 |
15 | First, clone remote repository to your local.
16 |
17 | `git clone https://github.com/qwqmlf/qwgc.git`
18 |
19 | and then,
20 |
21 | ```zsh
22 | cd qwgc
23 | pip install -e .
24 | ```
25 |
26 | If you don't have any errors, your build is success.
27 |
28 | ## How to use
29 |
30 | [experiments.toml](https://github.com/qwqmlf/qwgc/blob/master/qwgc/experiments.toml) is the configuration (Hyper parameter) for QWGC.
31 |
32 | Put hyper parameters and then run
33 |
34 | ```zsh
35 | cd qwgc
36 | python QWGC.py
37 | ```
38 |
39 | (This simulation may take a long time to finish)
40 |
41 | ## Tutorials
42 |
43 | [Here](./notebook/tutorial.ipynb) is the tutorials how to use this (Japanese).
44 |
45 | ## Acknowledgement
46 |
47 | This project is supported by IPA mitou target project.
48 |
--------------------------------------------------------------------------------
/Untitled.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": 2,
6 | "metadata": {
7 | "ExecuteTime": {
8 | "end_time": "2020-06-23T08:08:36.362262Z",
9 | "start_time": "2020-06-23T08:08:36.357553Z"
10 | }
11 | },
12 | "outputs": [
13 | {
14 | "data": {
15 | "text/plain": [
16 | "['/Users/ryosuke/opt/anaconda3/lib/python3.7/site-packages/qiskit']"
17 | ]
18 | },
19 | "execution_count": 2,
20 | "metadata": {},
21 | "output_type": "execute_result"
22 | }
23 | ],
24 | "source": [
25 | "import qiskit\n",
26 | "qiskit.__path__"
27 | ]
28 | },
29 | {
30 | "cell_type": "code",
31 | "execution_count": null,
32 | "metadata": {},
33 | "outputs": [],
34 | "source": []
35 | }
36 | ],
37 | "metadata": {
38 | "jupytext": {
39 | "text_representation": {
40 | "extension": ".py",
41 | "format_name": "light",
42 | "format_version": "1.5",
43 | "jupytext_version": "1.3.3"
44 | }
45 | },
46 | "kernelspec": {
47 | "display_name": "Python 3",
48 | "language": "python",
49 | "name": "python3"
50 | },
51 | "language_info": {
52 | "codemirror_mode": {
53 | "name": "ipython",
54 | "version": 3
55 | },
56 | "file_extension": ".py",
57 | "mimetype": "text/x-python",
58 | "name": "python",
59 | "nbconvert_exporter": "python",
60 | "pygments_lexer": "ipython3",
61 | "version": "3.7.4"
62 | },
63 | "varInspector": {
64 | "cols": {
65 | "lenName": 16,
66 | "lenType": 16,
67 | "lenVar": 40
68 | },
69 | "kernels_config": {
70 | "python": {
71 | "delete_cmd_postfix": "",
72 | "delete_cmd_prefix": "del ",
73 | "library": "var_list.py",
74 | "varRefreshCmd": "print(var_dic_list())"
75 | },
76 | "r": {
77 | "delete_cmd_postfix": ") ",
78 | "delete_cmd_prefix": "rm(",
79 | "library": "var_list.r",
80 | "varRefreshCmd": "cat(var_dic_list()) "
81 | }
82 | },
83 | "types_to_exclude": [
84 | "module",
85 | "function",
86 | "builtin_function_or_method",
87 | "instance",
88 | "_Feature"
89 | ],
90 | "window_display": false
91 | }
92 | },
93 | "nbformat": 4,
94 | "nbformat_minor": 4
95 | }
96 |
--------------------------------------------------------------------------------
/Untitled.py:
--------------------------------------------------------------------------------
1 | # ---
2 | # jupyter:
3 | # jupytext:
4 | # text_representation:
5 | # extension: .py
6 | # format_name: light
7 | # format_version: '1.5'
8 | # jupytext_version: 1.3.3
9 | # kernelspec:
10 | # display_name: Python 3
11 | # language: python
12 | # name: python3
13 | # ---
14 |
15 | import qiskit
16 | qiskit.__path__
17 |
18 |
19 |
--------------------------------------------------------------------------------
/archive/qmnist.py:
--------------------------------------------------------------------------------
1 | """
2 | This is archive version of previous qmnist project.
3 | """
4 | from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
5 | from qiskit import execute, Aer
6 | from numpy import pi
7 | from sklearn.datasets import load_digits
8 | from sklearn.model_selection import train_test_split
9 | from tqdm import trange
10 |
11 | import numpy as np
12 | import random
13 | import copy
14 | import umap.umap_ as umap
15 |
16 | THETA_MIN, THETA_MAX = -pi, pi
17 | BACKEND = Aer.get_backend('qasm_simulator')
18 | SHOTS = 2048
19 |
20 |
21 | class QMNIST:
22 | """
23 | QMMIST is for quantum classifier for MNIST
24 |
25 | This
26 | """
27 | def __init__(self, encoder, alpha=0.0001,
28 | n_particle=20, iteration=50, w=0.8, Cp=1.3, Cg=1.1):
29 | self.encoder = encoder
30 | self.alpha = alpha
31 | self.n_particle = n_particle
32 | self.iteration = iteration
33 | self.w = w
34 | self.Cp = Cp
35 | self.Cg = Cg
36 |
37 | def fit(self, x=None, y=None):
38 | dim = len(x[0])
39 | particles = np.array([[random.uniform(THETA_MIN, THETA_MAX)
40 | for j in range(dim)]
41 | for n in range(self.n_particle)])
42 | velocities = np.array([[0 for i in range(dim)] for n in range(self.n_particle)])
43 | personal_best_pos = copy.copy(particles)
44 | personal_best_score = [self._get_error(x, y, theta)
45 | for theta in particles]
46 |
47 | best_particle = np.argmin(personal_best_score)
48 | grobal_best_pos = personal_best_pos[best_particle]
49 |
50 | errors = []
51 | accs = []
52 | print("Training start!")
53 | for t in trange(self.iteration):
54 | for n in range(self.n_particle):
55 | ran_p = random.uniform(0, 1)
56 | ran_g = random.uniform(0, 1)
57 | particles[n] = particles[n] + velocities[n]
58 | velocities[n] = (self.w*velocities[n] +
59 | self.Cp*ran_p*(personal_best_pos[n]-particles[n]) +
60 | self.Cg*ran_g*(grobal_best_pos-particles[n]))
61 | score = self._get_error(x, y, particles[n])
62 | if score < personal_best_score[n]:
63 | personal_best_score[n] = score
64 | personal_best_pos[n] = particles[n]
65 |
66 | best_particle = np.argmin(personal_best_score)
67 | grobal_best_pos = personal_best_pos[best_particle]
68 |
69 | error = self._get_error(x, y, grobal_best_pos)
70 | acc = self._get_accuracy(x, y, grobal_best_pos)
71 | print(error, acc, grobal_best_pos)
72 | errors.append(error)
73 | accs.append(acc)
74 | converg = [errors, accs]
75 | return grobal_best_pos, converg
76 |
77 | def _get_error(self, x, y, theta):
78 | counts = self._get_counts(x, theta)
79 | errors = []
80 | for ct, lb in zip(counts, y):
81 | emp_x = np.array([ct.get(b, 0)/SHOTS for b in self.encoder])
82 | err = self._error_func(emp_x, np.array(y))
83 | errors.append(err)
84 | return np.mean(errors)
85 |
86 | def _get_counts(self, x, theta):
87 | qcs = self._classifier(x, theta)
88 | job = execute(qcs, backend=BACKEND, shots=SHOTS)
89 | result = job.result()
90 | counts = [result.get_counts(qc) for qc in qcs]
91 | # print(counts)
92 | return counts
93 |
94 | @staticmethod
95 | def _error_func(x, bx, delta=1e-9):
96 | return -np.sum(bx * np.log(x + delta))
97 |
98 | @staticmethod
99 | def _map_func(x):
100 | val = x/np.arcsinh(x)
101 | # print(val, x)
102 | return val
103 |
104 | def _classifier(self, x, theta):
105 | qcs = []
106 | ld = len(x[0])
107 | for xt in x:
108 | dataq = QuantumRegister(ld)
109 | c = ClassicalRegister(ld)
110 | qc = QuantumCircuit(dataq, c)
111 | for xd, qr in zip(xt, dataq):
112 | qc.h(qr)
113 | qc.rz(self._map_func(xd), qr)
114 | qc.h(qr)
115 | qc.rz(self._map_func(xd), qr)
116 | # anzatz
117 | for r in range(4):
118 | for ith, th in enumerate(theta):
119 | qc.ry(th, dataq[ith])
120 | for ids, d in enumerate(dataq[:-1]):
121 | qc.cz(d, dataq[ids+1])
122 | qc.cz(dataq[0], dataq[-1])
123 | qc.measure(dataq, c)
124 | qcs.append(qc)
125 | return qcs
126 |
127 | def _get_accuracy(self, x, y, theta):
128 | counts = self._get_counts(x, theta)
129 | answers = self._get_answer(counts)
130 | count = 0
131 | for ans, lb in zip(answers, y):
132 | if ans == np.argmax(lb):
133 | count += 1
134 | accuracy = count/len(y)
135 | return accuracy
136 |
137 | def _get_answer(self, counts):
138 | answers = []
139 | for cs in counts:
140 | answer = np.argmax([cs.get(b, 0) for b in self.encoder])
141 | answers.append(answer)
142 | return answers
143 |
144 | def test(self, x, param):
145 | counts = self._get_counts(x, param)
146 | answer = self._get_answer(counts)
147 | return answer
148 |
149 | def performance(self, ans, label):
150 | count = 0
151 | for an, lb in zip(ans, label):
152 | if np.argmax(lb) == an:
153 | count += 1
154 | return count/len(label)
155 |
156 |
157 | if __name__ == '__main__':
158 | digits = load_digits()
159 | # qmnist = QMNIST(['0000000001', '0000000010',
160 | # '0000000100', '0000001000',
161 | # '0000010000', '0000100000',
162 | # '0001000000', '0010000000',
163 | # '0100000000', '1000000000'])
164 |
165 | qmnist = QMNIST(['0000', '1000',
166 | '0001', '1001',
167 | '0010', '1010',
168 | '0100', '1101',
169 | '0101', '1111'])
170 |
171 | # qmnist = QMNIST(['01', '10'])
172 | onhot_labels = []
173 | for i in digits.target:
174 | lab = [0 for _ in range(10)]
175 | lab[int(i)] = 1
176 | onhot_labels.append(lab)
177 | reducer = umap.UMAP(n_components=4)
178 | reducer.fit(digits.data)
179 | embedding = reducer.transform(digits.data)
180 | # Verify that the result of calling transform is
181 | # idenitical to accessing the embedding_ attribute
182 | assert(np.all(embedding == reducer.embedding_))
183 | x_train, x_test, y_train, y_test = train_test_split(embedding[:1000], onhot_labels[:1000])
184 | param, conv = qmnist.fit(x_train, y_train)
185 | answers = qmnist.test(x_test, param)
186 | accs = qmnist.performance(answers, y_test)
187 | print(param, conv)
188 | print(accs)
189 |
--------------------------------------------------------------------------------
/docs/DOCUMENT.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/qwqmlf/qwgc/d06c805023bf37a1252505f7dc6e30461d861440/docs/DOCUMENT.md
--------------------------------------------------------------------------------
/docs/document.txt:
--------------------------------------------------------------------------------
1 | 量子ウォークによるグラフ分類モデル
2 |
3 | 近年様々な場面においてグラフのデータの需要というものが高まってきています.例えば化学構造を判定する判定器や,ネットワークにおけるコミュニティ分析等様々に渡ります.
4 | 量子技術の関連で言うと,量子コンピュータにおける量子ビットをどのように接続するのか,といったものもグラフのデータの一種になります.
5 | しかしながらこのようなグラフのデータというのは一般に処理が非常に重たいという特徴があります.例えばグラフを行列の形式で表した場合,1000個のノードを持つグラフであれば
6 | 1000×1000の行列を扱うことになります.大きなグラフになれば,数万から数十万ものノードを持つグラフを扱わなければなりません.そのような場合古典のコンピュータでは非常に
7 | 大きなメモリが必要となってしまうことに加えて,処理に非常に時間がかかります.また,近年様々な機械学習の技術が発展してきている中で,グラフのデータにおける機械学習ではまだ
8 | 高い精度を実現しているとは言い難い状況です.特定のデータセットにおいては95%の精度を超えるものも出てきましたが,クラスやノードが増えたりすると50%を切ってしまうデータセットもあります.
9 |
10 | そこで今回我々が取り組んだこととしては,量子コンピュータを使ってうまくグラフを扱うことができないかということについて,実際にプロトタイプのモデルを作成し,検証を行いました.
11 | グラフに関するタスクは様々にありますが,今回はグラフの分類問題に絞ってモデルを作成しました.
12 |
13 | 要素技術について
14 | 量子ウォーク
15 |
16 | 量子ウォークとは簡単に言ってしまえば,古典のランダムウォークと呼ばれるものの量子版です.しかしながらその性質の特異さから,量子ランダムウォークではなく量子ウォーク
17 | と呼ばれるようになりました.量子ウォークは大きく二つの種類に分かれており,離散時間量子ウォークと連続時間量子ウォークと呼ばれるものが存在します.今回のプロジェクトでは
18 | コイン量子ウォークと呼ばれる離散時間量子ウォークの一種を用います.
19 |
20 | まずコイン量子ウォークの特徴として,古典のランダムウォークにおいて,各面の出現確率が1/2のコイントスをするように,コインのユニタリというものを定義します.この時コインは
21 | ユニタリな行列であればどのような行列でもコインとなり得ます.そしてそのようなコインに応じて,量子ウォーカーが次のステップでどのように動くのかということが決定されます.
22 | 古典のランダムウォークと全く異なる点のひとつとして,量子ウォーカーが確率的な場所の重ね合わせを持ちながら,歩を進めていくという点です.これにより,確率分布の拡散速度は
23 | 古典のランダムウォークに比べて平方根的に加速するという特徴があります.一般に一次元直線上のランダムウォークは無限回試行を繰り返せば,原点に確率分布が収束するような,
24 | 正規分布へ近づいていきますが,一次元直線状の量子ウォークにおいては,確率が外側に広がっていき,原点に向かって小さくなっていくような分布を示します.この分布の形状が
25 | どのようになるかについては,コインの決定方法によります.
26 |
27 | このような特徴を持った量子ウォークというものを任意のグラフ上で定義します.まず,グラフがどのように接続されているのかという隣接行列から,量子ウォーカーがどのように動くのか
28 | という情報を持ったステップオペレーターというものを定義します.各ノードにおいて,隣接するノードへどのように移動するのかを記述するための行列になります.次にどのくらいの
29 | 確率で移動するのかという確率遷移の役割を果たすコインオペレーターというものを定義します.今回は各ノードに対してローカルなコインオペレーターというものを定義します.これにより,
30 | 各ノード毎に隣接するノードのにどのくらいの確率で遷移するのかということを行列として保持しておくことができます.こうして,ステップオペレーターとコインオペレーターという二つの
31 | オペレーターが完成し,これらの内積をとったものが,1ステップの量子ウォークを表す時間発展のオペレーターとなります.これをt回かけることで,tステップ後の量子ウォークの時間発展の
32 | オペレーションを行うことができます.
33 |
34 | このようにして,グラフ上の量子ウォークを定義することで,あるグラフからそのグラフに特有な確率振幅というものを取り出すことができます.これをデータとして実際に分類を進めて
35 | いきます.
36 |
37 | 分類回路
38 |
39 | 上のように量子ウォークを用いてグラフから生成した確率振幅を,実際に量子ビットを用いて分類していきます.
40 |
41 | まず,量子ウォークの確率振幅を持った量子ビットをデータビットとし,そこに対して新たにマッピングビットとして量子ビットを追加します.次に,データビットからマッピングビット
42 | に対して,コントロールオペレーションを用いて情報をマッピングしていきます.この時,このコントロールオペレーションを特定の角度を持ったコントロールローテションオペレーション
43 | として行うことで,この回転の角度を調整していきます.この調整のプロセスについては後述します.最後にマッピングビットを測定し,事前に取り決めたエンコーダーにそって,その測定
44 | 結果がどのクラスに分類されるのかということを計算します.そしてその結果からどれくらいのコストが存在するのかということを計算し,先ほどの回転角度のパラメーターに対して
45 | フィードバックを行います.
46 |
47 |
48 |
49 |
50 |
--------------------------------------------------------------------------------
/docs/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | This is qwgc
6 |
7 |
8 | Welcom to quantum computing world!
9 |
10 |
11 |
--------------------------------------------------------------------------------
/image/qwgc_logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/qwqmlf/qwgc/d06c805023bf37a1252505f7dc6e30461d861440/image/qwgc_logo.png
--------------------------------------------------------------------------------
/nohup.out:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/qwqmlf/qwgc/d06c805023bf37a1252505f7dc6e30461d861440/nohup.out
--------------------------------------------------------------------------------
/notebook/Plots.py:
--------------------------------------------------------------------------------
1 | # ---
2 | # jupyter:
3 | # jupytext:
4 | # text_representation:
5 | # extension: .py
6 | # format_name: light
7 | # format_version: '1.5'
8 | # jupytext_version: 1.3.3
9 | # kernelspec:
10 | # display_name: Python 3
11 | # language: python
12 | # name: python3
13 | # ---
14 |
15 | # # Convergence plot
16 |
17 | e1=[0.6286408520623922, 0.6289525825569178, 0.5412940012637213, 0.5399199822334315, 0.49756061144296837, 0.5386496534421491, 0.5110201664171742, 0.4785323556159, 0.4879992233852226, 0.49388898393628267, 0.4227883738901349, 0.47665407322957315, 0.49194537115508497, 0.4784480810071889, 0.5067394759922192, 0.4815508310174932, 0.4480058931682556, 0.5191713001759654, 0.5025600642057176, 0.47646282461622946, 0.4620775882390643, 0.5346632906032827, 0.4886131751452513, 0.5068477238076842, 0.4455982578380637, 0.5182468309511442, 0.5194051409981214, 0.5102047452714895, 0.4224846316777891, 0.4369363754766283, 0.47643414498658937, 0.5205363676955092, 0.5191792358482716, 0.43761845483213274, 0.4410680839960249, 0.5124071742830791, 0.5298468258800075, 0.5061098855038695, 0.48256532980818484, 0.4913228065366606, 0.4972612354925298, 0.4978721811109297, 0.4054224929939014, 0.4689590445321974, 0.47656007392483984, 0.4383041892763407, 0.44729094116756796, 0.4355191217281943, 0.39603253338464445]
18 | e2=[0.6445889256767168, 0.6535514888883678, 0.650516819829064, 0.5756429937727983, 0.6142765741620072, 0.5835705610683382, 0.5912615393329274, 0.6146589955098392, 0.6122305885006271, 0.615096288252815, 0.5755860024839088, 0.544477825409265, 0.5426761288272395, 0.5468697195293689, 0.564680589127484, 0.5771165305986262, 0.5684633735633585, 0.5680884419879598, 0.5612183060968275, 0.559276953305883, 0.43673818405890585, 0.4411540650165362, 0.4598893136551889, 0.43005624189179076, 0.45188026405543275, 0.47144659911395703, 0.5244689044281716, 0.41605587984112, 0.4556096201350907, 0.46408102111806254, 0.4693180656437913, 0.4268421245136888, 0.4412494204726097, 0.39367845982910615]
19 | e3=[0.662780905315912, 0.557526130143123, 0.5584640419156808, 0.5344490232122784, 0.593609022343057, 0.4937605123293818, 0.49679500580245917, 0.6381938409925619, 0.4969497574371143, 0.5490326065330788, 0.6127879707910444, 0.5089002055028583, 0.5504401226212559, 0.6142692709979238, 0.5721990951978606, 0.5018530856716944, 0.48248730823997454, 0.5393567930056656, 0.41791994591838755, 0.5305910774126542, 0.561185300298215, 0.595460105472618, 0.5115104804811111, 0.4495276525911773, 0.43500401066793454, 0.4161182946891324, 0.42475182877301493, 0.5073871378890902, 0.47263913226342963, 0.5149631515053271, 0.598002020559863, 0.41349915170939194, 0.47894825230795474, 0.5622578158963416, 0.5723435539368699, 0.4462502586322237, 0.4093627693814017, 0.5492960278816822, 0.510461265579312, 0.5808173512459651, 0.5597837733339822, 0.5640112157072309, 0.44698468041157, 0.5070970659950728, 0.48072844551751587, 0.5272173485178996, 0.5376622571610833, 0.5735053315795404, 0.4092035721307091, 0.5440903033836487, 0.5011121569382986, 0.5527630387469133, 0.4941897766576979, 0.470192162722345, 0.47418095121567044, 0.48084680432628457, 0.4239088964655666, 0.46940819486126134, 0.4537334210540194, 0.4864943090841813, 0.4687166558652696, 0.49614205816549944, 0.42874339930129546, 0.4479324170994075, 0.40787039901158556, 0.48786153290305956, 0.40963323764273557, 0.4352159063157325, 0.4888689022690961, 0.47162666268555464, 0.44671000444880116, 0.4967216183541344, 0.4012512434083865, 0.46064594635128436, 0.4049871203999046, 0.47170955324407465, 0.48706359188208187, 0.39931433341039707]
20 | e4=[0.631157721764274, 0.626369631668824, 0.6435168046798363, 0.5756890928745755, 0.6805477459512386, 0.5457392115779026, 0.6670013898692743, 0.571441632419972, 0.5711226503295723, 0.5043703755755192, 0.5133700170618634, 0.4890578230830625, 0.48377985095373055, 0.5401161872295855, 0.5231897730483787, 0.5224417136122825, 0.48197008488419696, 0.5430021431008605, 0.48585065976376307, 0.4947049468193294, 0.5128519566834271, 0.5111700349984294, 0.5021240973161041, 0.44473351723091004, 0.5387269935977932, 0.5000663192282513, 0.47768543276690545, 0.4804686186752253, 0.5298907808582913, 0.4752329625280757, 0.44839780034261145, 0.4701039454704951, 0.4918735308810149, 0.4728677770754973, 0.4576550851711339, 0.502450222085708, 0.5163739719069254, 0.5213008138551934, 0.4652131556745651, 0.49846654870033724, 0.5137510967641185, 0.5446460345322064, 0.47656732480459313, 0.4516336465509245, 0.5271248472630446, 0.4559450905739887, 0.49738101909129345, 0.5253791961349298, 0.5135150601261252, 0.44079823430873305, 0.5324834268850102, 0.5035609323350201, 0.5182742329465138, 0.5504791701670207, 0.531284676694358, 0.474503007577341, 0.5366327134778044, 0.5011612366374507, 0.5127348471786759, 0.5019671684236049, 0.44189963776688185, 0.46295316911159845, 0.5348905595183858, 0.5269112370262575, 0.5090272490103386, 0.47609522731817105, 0.491370758355211, 0.4135600347595616, 0.4818512230353636, 0.512062390185624, 0.47933046522657563, 0.4934857435730518, 0.4806171151139013, 0.4608250672563326, 0.41268520144053455, 0.4918494520803791, 0.46745210963432454, 0.48071324978066593, 0.5057204328529747, 0.4996037331029218, 0.5413217090462604, 0.4508761552721001, 0.47468589579687376, 0.5642027975890482, 0.41545508292293726, 0.48314552116470366, 0.3997297679560264]
21 | e5=[0.6682606140119535, 0.5778862814702397, 0.571284816447605, 0.5732217554886555, 0.576681243443929, 0.5696738503322155, 0.561619312862779, 0.5550863827708744, 0.5376039510952384, 0.5209829601641807, 0.5787276254893167, 0.5649896199922552, 0.5685287073392442, 0.4857622856463922, 0.5184760505457569, 0.5477220163966926, 0.5677443951422002, 0.546248508606815, 0.48857192683520445, 0.4844910863766792, 0.4503989103757882, 0.42963829512934754, 0.36462205360641897]
22 | e6=[0.6052190978338532, 0.6168189279264902, 0.5742753886203199, 0.5916751574417829, 0.6499174495644433, 0.5572021688155816, 0.5875677462728359, 0.5882764329669297, 0.42224941745738764, 0.46388965858198655, 0.46894811449133583, 0.5386172982477864, 0.445138792658842, 0.5659195198584153, 0.4280846453576261, 0.5081342706424578, 0.591777700219891, 0.4300014148912618, 0.44029194146143813, 0.4655751631352384, 0.5144871176051569, 0.4302597905571364, 0.47086406673852405, 0.42197278841497904, 0.5666806007720256, 0.4684396130328333, 0.46515501410751087, 0.5854247908909535, 0.46820092150107384, 0.4542753960527196, 0.5136825397873981, 0.42490230795806355, 0.5681653948495334, 0.4982418526291404, 0.5297805255166854, 0.5255641991721257, 0.46604946752584037, 0.42125778606643877, 0.5572774702893012, 0.4857469072821239, 0.46583437875598993, 0.49471480783108884, 0.4960882334145554, 0.464275426856948, 0.4227442887486467, 0.4736773611229292, 0.49004926134414617, 0.49931503682149486, 0.4988062267806028, 0.49268082475005154, 0.4488809454972674, 0.5174211905808321, 0.42898509257033995, 0.41935662991751776, 0.4804755068098414, 0.5517276889852001, 0.6108761441851374, 0.5106562598517737, 0.5707976053860792, 0.5431404102118769, 0.610686118237394, 0.5640443974179815, 0.45304879473737386, 0.5000248112364134, 0.4302734132332332, 0.48721656167805666, 0.5295429629785897, 0.46752394358529753, 0.6145431584915981, 0.50988218844425, 0.49915956989048965, 0.5278205896473646, 0.620852541372503, 0.4237926102741802, 0.42282174131809014, 0.4208938526055965, 0.487461524736154, 0.4753131817344044, 0.4822918616140902, 0.44156923779603763, 0.41871631240516527, 0.46848062331449036, 0.46980532334976366, 0.4709761803139777, 0.3976063267327049]
23 | e7=[0.6343177780040268, 0.619599304033062, 0.6242120198917819, 0.6031668480623487, 0.6402201060305929, 0.6231041583237609, 0.6293624185342378, 0.6458794486207945, 0.6827538772276097, 0.6720506480634977, 0.6899104720222323, 0.669870406811187, 0.6512371597807493, 0.6920056581481943, 0.5914131484170293, 0.6232179447484109, 0.5801354474941912, 0.6763159966305158, 0.56685784250218, 0.6637311529482484, 0.5847709695092046, 0.5633961429876598, 0.560108233954407, 0.52832327254978, 0.5283157800182223, 0.49202826266850064, 0.46519065544218025, 0.458531046376133, 0.48787502470038335, 0.4633186448926279, 0.5231878042415427, 0.5232549990667295, 0.45401437184614385, 0.4628743973973229, 0.46133926646432816, 0.4803737244518355, 0.4908663462940766, 0.47381789765142834, 0.46783045177687643, 0.46850374045145793, 0.4681717836248394, 0.4664232598009578, 0.475161204989716, 0.4698246364777594, 0.46279370428901806, 0.47086318835181673, 0.47130924184490053, 0.48004062896072147, 0.5380318909358003, 0.522459093653992, 0.5086512464786042, 0.4940124113230001, 0.5084629644805148, 0.49907221807047564, 0.5060149840853123, 0.5399783523243797, 0.5411928928687932, 0.5080996494638225, 0.49238446160879457, 0.5090379936341687, 0.4514971394109261, 0.5069246117398007, 0.5122056635240435, 0.5183315031961354, 0.5247657452974124, 0.5358356076290758, 0.5328220546034671, 0.5280624432744783, 0.5274743097746725, 0.4975618714767399, 0.49785887670110296, 0.5172247834730592, 0.5139599573220014, 0.5470670151810273, 0.5289727214355933, 0.5291905638247228, 0.4802756837124825, 0.5105438294031261, 0.4966151637696548, 0.4622230385770683, 0.5028894815058449, 0.5204636049862856, 0.46890755144793184, 0.536715875218253, 0.5287019172764743, 0.49212818638466355, 0.4978716350387547, 0.47170291861259944, 0.537535312754868, 0.5285083683899722, 0.5435672463104038, 0.5362293614488318, 0.48409470635156077, 0.45942009997388766, 0.5383618196483511, 0.5066198888774862, 0.5322328585016302, 0.5380757401024095, 0.5307318705952703, 0.49557513053245256, 0.540221765590457, 0.5319199897476646, 0.4425432496155992, 0.5424946438115121, 0.4967073166823288, 0.522464533354847, 0.48612498629064954, 0.5236114041318946, 0.5270520927976627, 0.5375392206453816, 0.49356780560525965, 0.5055856811585618, 0.5432119154861312, 0.5048427773577933, 0.45663313202496075, 0.45486778712936404, 0.44971790073868045, 0.5149780350294215, 0.5083240728859777, 0.44894944420421445, 0.5042145757006968, 0.48460426559739705, 0.4967351042896734, 0.5044661611141689, 0.43596825173934706, 0.5746881408014808, 0.5560117818174737, 0.48581143997140513, 0.4178848063830119, 0.4124531613792558, 0.41128625935257995, 0.5130877411153815, 0.5702506434152459, 0.5191608795298068, 0.40421862548733356, 0.49370921494417785, 0.47747102686452786, 0.4501159143626001, 0.42434966281242287, 0.5694928908915956, 0.4707648838018859, 0.46308786979076044, 0.5674826460753027, 0.41319744667993896, 0.43378581408673195, 0.5479508775304427, 0.42830800640058475, 0.5040567675034388, 0.5102932814824029, 0.5352098084517855, 0.4711907835610163, 0.4135569939522152, 0.5645434706974641, 0.39392153030740434]
24 | e8=[0.5913407969216123, 0.5968027045561548, 0.5807132242546393, 0.6045555424432444, 0.5790465745724817, 0.5146519574308367, 0.5386476154031689, 0.5457725039582826, 0.5544308346069118, 0.5435916500554991, 0.5640535382781875, 0.5419371097075426, 0.5441329113708785, 0.5580210026385325, 0.539490557893939, 0.5427861674156166, 0.5546224894721118, 0.5497072631021152, 0.5562272792102939, 0.5191799008595017, 0.5651000039656113, 0.5648645310545621, 0.5442534059819037, 0.5442239567027761, 0.5569325490735977, 0.5570671528470494, 0.5707478917193466, 0.5520669114088126, 0.5560904525558917, 0.536186225898877, 0.567669985618328, 0.5404920496327675, 0.551565557944254, 0.5425809403646311, 0.5557752017202766, 0.5535524873136072, 0.54511963019625, 0.5578999806184163, 0.5430200803197988, 0.5600545158472466, 0.5495828613081718, 0.554367532743426, 0.5492933831513049, 0.5571854750471325, 0.542362247911772, 0.5480834794851243, 0.5262099870228901, 0.48032788936449317, 0.4782151124259759, 0.49380543526049225, 0.5064807825285621, 0.4947974190672037, 0.4937050456318475, 0.49423348593034644, 0.4934758389741058, 0.5088370646749851, 0.4945296999162127, 0.4980231753465324, 0.4966765276873942, 0.4921028081643773, 0.515243532046272, 0.505921332289337, 0.5040872928584723, 0.4934447759396242, 0.5075192382266717, 0.5097597347103172, 0.4742844879083192, 0.5442708524819456, 0.4999348179754739, 0.461829856728611, 0.4705040366840693, 0.4903857708284842, 0.4924730661893619, 0.5134988021147889, 0.4923443029208326, 0.4727467433790539, 0.5225885499341563, 0.47025597023306087, 0.49101448323887475, 0.5430488000164548, 0.46579466193938523, 0.5151981816002086, 0.5429112242988399, 0.5038012282289347, 0.524662590969537, 0.4958443962133329, 0.4577390007625348, 0.5445978798228361, 0.502963558160195, 0.4894387668322627, 0.5440032976839626, 0.4819860916037589, 0.4654945753767531, 0.5152589293772628, 0.49937169712317414, 0.4864882370386736, 0.4507856824420945, 0.46654016177363283, 0.5097213545853928, 0.5404550468061052, 0.5419278186965883, 0.4495814173506067, 0.5153273272247367, 0.45098667264602854, 0.46487961539249983, 0.5234411744015217, 0.5336811462704812, 0.4455712071824399, 0.5365523056268828, 0.5121995525704492, 0.4736035794709903, 0.4473335804233988, 0.4906554048692217, 0.43056341428429684, 0.48750676622735406, 0.46975202791639503, 0.41985163165128453, 0.42365061155579714, 0.46134934441088365, 0.46918184061159246, 0.4432015336494499, 0.4720567531651249, 0.4683567090279011, 0.42967603770654866, 0.4236602081687182, 0.4135466892675132, 0.45815086391436777, 0.3967556123885781]
25 | e9=[0.6650768332261353, 0.5839188975158505, 0.5465120888927283, 0.5550907987683472, 0.567639764704636, 0.5085926678869052, 0.5275917470790742, 0.541221468537061, 0.5704477431835283, 0.5448885505140948, 0.5132874077181068, 0.5101701010115886, 0.5310406275923955, 0.5454947990050796, 0.5625857434190685, 0.5159442036807962, 0.5988034093157687, 0.5943047004640979, 0.551393955716915, 0.5233365342078535, 0.4752450983304961, 0.5050691325599479, 0.5235954093501491, 0.4552512305179317, 0.5831833398610338, 0.4731778439749536, 0.5687028273171127, 0.5889767650973098, 0.6064331743720209, 0.440816151178571, 0.448903119770252, 0.44343653750230294, 0.5001408741585447, 0.49118657617553213, 0.467956850971661, 0.4825464062978623, 0.5399849464121956, 0.47311507777648387, 0.4968562934355171, 0.46528754202033956, 0.5009424715411169, 0.4498238228474625, 0.5111711895467378, 0.46172956095965534, 0.48795037350222076, 0.49779900451624604, 0.41431572809038547, 0.5548793389362827, 0.5592370825347295, 0.47399601371736727, 0.5362121023064179, 0.5389262776700031, 0.48785242517507516, 0.48497470394201003, 0.48853758754813664, 0.452062814504457, 0.48515275520764484, 0.5178452313538177, 0.4370453782697105, 0.5143343530357027, 0.4733976407685126, 0.4377874336752083, 0.4225158612975633, 0.4079474669212051, 0.5525408255038543, 0.5199513551123233, 0.4448075381183994, 0.4889228086780745, 0.5444860707172519, 0.5482472432312546, 0.4715690031152096, 0.5860841514937343, 0.48233223561238736, 0.5260061348833885, 0.5273267432013465, 0.5210076022602085, 0.5551322110634548, 0.43377446518549584, 0.5930831673002215, 0.47734011874861937, 0.5223724082746285, 0.46364564600104363, 0.49103227014858114, 0.5078208924726832, 0.5142013832446156, 0.42539199248715004, 0.573131639889572, 0.4196562315745191, 0.5830005193887268, 0.5093072734962075, 0.5148966644389248, 0.4243085194017081, 0.6687310583399344, 0.46364319971652684, 0.49546870554391054, 0.5366528704484373, 0.5198103049962106, 0.5387543007216663, 0.582636034027522, 0.5363235009290618, 0.48327522215619056, 0.541926394132778, 0.5559785869462495, 0.6016761352697166, 0.5371624283020867, 0.5674319149578625, 0.5300704977548727, 0.5547608427601932, 0.4798895004992304, 0.4660034751436862, 0.524066221672807, 0.48431688551826535, 0.4902196506170733, 0.540522649117206, 0.4411247935696716, 0.5057168246330429, 0.6111460839056243, 0.5640026472940163, 0.5352351126005239, 0.43094285001997823, 0.5156524893462651, 0.43502378139170633, 0.4967973382630091, 0.49812092740202074, 0.5167071715045539, 0.5532030008701334, 0.5617041929433927, 0.5188911940730441, 0.5743757589835153, 0.5189928236553618, 0.4380557607907093, 0.5418787229350316, 0.44821135345496893, 0.5310716701733434, 0.5461678917843644, 0.519134739798097, 0.5511987988747173, 0.5773381630359999, 0.5233184425743422, 0.49873902095696, 0.5038420863478974, 0.5758701606630139, 0.5551576247842767, 0.5159133205832385, 0.5433872211476676, 0.5233134104986293, 0.5134074229814606, 0.49244212787856195, 0.5004507865528482, 0.5177767871179224, 0.5125121555910681, 0.5202937524719504, 0.5158894931633854, 0.518259284945597, 0.49879019957162246, 0.5138751753512852, 0.5193327327927922, 0.520053378362557, 0.4996759240244054, 0.5307492186079692, 0.5321791654099939, 0.512370357644313, 0.5051488492226954, 0.5155795339277843, 0.5850895438525353, 0.49333688234630446, 0.5146387574915534, 0.5152962059410358, 0.4916785527685588, 0.5220270697847215, 0.5108044898684504, 0.5225887670058841, 0.5054755192744912, 0.5200111921446353, 0.6186353617217828, 0.5162420347066328, 0.48991362080819656, 0.49458247546427553, 0.5310543800879368, 0.49156501831817023, 0.5209129827957445, 0.5071274285234982, 0.514889685151172, 0.4876652826616725, 0.5176711547960228, 0.501579488061985, 0.5219832016573605, 0.5211421406724956, 0.6102793042683985, 0.5092234796765647, 0.505841113259587, 0.5191361626567386, 0.509224562794439, 0.5095766326615782, 0.502079751965955, 0.5127003003234921, 0.5099580442929842, 0.5107503813960915, 0.5886776852182013, 0.5220688084678431, 0.5280708084273058, 0.5097898025489782, 0.5047902080968601, 0.5005626889772651, 0.596540291245381, 0.4996027048629127, 0.4934349312367303, 0.5409843332211969, 0.5017001340834972, 0.5094353513995228, 0.5170367406199069, 0.530769105638814, 0.5176185091437396, 0.5094759296400767, 0.5193568466416617, 0.4989014112392066, 0.5279480159795279, 0.5029211093859308, 0.5002122616570341, 0.5009459192487525, 0.5161268696467814, 0.5122714761320836, 0.4996834477594777, 0.5003828952897394, 0.5152310440552359, 0.5268164219017487, 0.4977712336603499, 0.5046063697037492, 0.5049611779603863, 0.471537858447829, 0.426280740636709, 0.4063048376824669, 0.4556689882653091, 0.429043458117716, 0.46098399335733065, 0.4783089903682395, 0.4548024144447215, 0.46235139284638144, 0.4855141050547884, 0.4525664843675803, 0.4752750869575304, 0.39445032834640115]
26 | e10=[0.6443296151657899, 0.5846714977547917, 0.5672715023778702, 0.5730989175581916, 0.5384647413211849, 0.645025012113611, 0.5818761835357733, 0.5485799801801237, 0.5470440562426591, 0.6848038874433044, 0.5762873974699276, 0.5210875247502859, 0.5840268965938661, 0.5996170002320559, 0.5675317667073588, 0.530705152494162, 0.43856855545184587, 0.5336486205176295, 0.5041957778265646, 0.5331599343293132, 0.4638759111952121, 0.5702342410880747, 0.4641523004965677, 0.49632076472769915, 0.4134526096867966, 0.6395538621427509, 0.5807024881555874, 0.54209316417008, 0.4917106519049478, 0.5746860150482541, 0.4903252002874721, 0.407509811691121, 0.41193636837385816, 0.5197750790448739, 0.5015629445346276, 0.5122720293420352, 0.5089435162867448, 0.479120258101935, 0.9612299362567398, 0.5322306367524896, 0.5408316328291428, 0.5005022853080526, 0.40517976682543727, 0.4738710242232649, 0.5853321607871663, 0.6350323074683683, 0.6220323108115962, 0.5756956691561051, 0.5785318277560356, 0.5495550621945828, 0.6706174816054492, 0.6379782769471595, 0.7984002265429345, 0.5819019958048154, 0.565515984004764, 0.585069528132984, 0.7163610180148806, 0.5907315843404257, 0.5649416080557663, 0.5797493081636891, 0.5929644452090546, 0.7590981885358427, 0.6029722793981109, 0.753962026409037, 0.6612429927176287, 0.5633060981382474, 0.6934616792472114, 0.599324234927781, 0.6621616927728853, 0.5921192185054662, 0.43641299280375273, 0.5122249502827196, 0.409546418406672, 0.42286517450873307, 0.6224070628071293, 0.5023519159195332, 0.5663255019772804, 0.5678506389375136, 0.464807663895237, 0.4602657015700848, 0.41183164602462163, 0.4275251302283884, 0.5801912671155873, 0.5318028256314792, 0.5397358271202957, 0.4531821739411755, 0.44849727924771193, 0.46869408154450576, 0.4549633610858585, 0.4462452859369011, 0.524381047614326, 0.379113122281514]
27 | errors = [e1, e2, e3, e4, e5, e6, e7, e8, e9]
28 |
29 | import numpy as np
30 | import matplotlib.pyplot as plt
31 | import seaborn as sns
32 |
33 | fig = plt.figure(figsize=(20, 10))
34 | sns.set()
35 | plt.xlabel("The number of iterations", fontsize=30)
36 | plt.ylabel("Error", fontsize=30)
37 | plt.xticks(fontsize=20)
38 | plt.yticks(fontsize=20)
39 | for ier, er in enumerate(errors):
40 | lens = len(er)
41 | plt.plot(range(lens), er, label="ex%d"%(ier+1))
42 | plt.legend(fontsize=20)
43 | plt.show()
44 |
45 | figure = plt.figure(figsize=(10, 10))
46 | plt.boxplot([0.9473684210526315, 0.7894736842105263, 0.8947368421052632, 0.8947368421052632, 0.7894736842105263, 0.8947368421052632, 0.6842105263157895, 0.7368421052631579, 0.8888888888888888, 0.7777777777777778])
47 | plt.title("Result of 10 cross validation", fontsize=20)
48 | plt.xlabel("MUTAG experiment", fontsize=20)
49 | plt.tick_params(labelsize=14)
50 | plt.ylabel("Accuracy", fontsize=20)
51 |
52 | e3s=[0.6114993145170406, 0.5580492397062562, 0.551723552407508, 0.5484116800260197, 0.5143462721841497, 0.628101523805724, 0.5356993571948219, 0.5266942280148578, 0.5141310873542365, 0.5638829554297106, 0.5496228055765812, 0.6360133689458043, 0.5201943196959011, 0.5481851459170456, 0.5055907141722972, 0.4941810064365272, 0.49340466605586575, 0.4634544459337397, 0.4611237576608274, 0.45213919591606666, 0.4534383746210488, 0.5054618981122072, 0.5165870609303926, 0.45209150635940387, 0.46805949776885464, 0.46960440853671903, 0.467819372880231, 0.4741484070294051, 0.4820804390230995, 0.4717719920228282, 0.5693892077112471, 0.5511274894354884, 0.5033156791541581, 0.5225321272437906, 0.5036599855410948, 0.51329297604302, 0.46424100042295025, 0.48893838154754043, 0.491828375814068, 0.5032194807511081, 0.4509417716028073, 0.4795241201436505, 0.5327343558753157, 0.4878793485411833, 0.4968022638355129, 0.47016307388363854, 0.5139168596002424, 0.44169284992918284, 0.4970774248606773, 0.5008123176407452, 0.5167832520763408, 0.5080038420660207, 0.48930759606351343, 0.513371961439122, 0.43260350311028717, 0.4378572126596461, 0.44645119576095627, 0.43974257495457336, 0.44501068910222275, 0.5046275199007141, 0.5248927422341266, 0.5057426950560957, 0.44435592756939385, 0.5028020254976295, 0.43205956750536756, 0.5095266443472911, 0.43189189288242835, 0.48790827272910336, 0.4615726181458669, 0.4708616965051463, 0.44032234603084713, 0.5179107099016528, 0.447553212974451, 0.4866584089091045, 0.5095162013165208, 0.5159928986646231, 0.5044830183103161, 0.4292861696424971, 0.5314628116720455, 0.43598839835680664, 0.4577829631040909, 0.4873913033076141, 0.4503809344508515, 0.484440023394841, 0.48888482964533436, 0.4920285335157382, 0.5073922782465428, 0.44670952906510897, 0.49607219758491355, 0.4308090376369893, 0.5268897603175041, 0.503559006011311, 0.5325591799558704, 0.5112110616324055, 0.4217329296463216, 0.4287457162429004, 0.5387852988261452, 0.5221160368806622, 0.509923902633072, 0.4411366299303317, 0.43803455040269307, 0.5335288104235335, 0.5272146852894581, 0.4602714866419109, 0.4465667728038471, 0.49895069098977923, 0.44450285295324765, 0.5251224372640607, 0.5278343169334901, 0.4596689338797286, 0.5217282828884132, 0.42935151668392935, 0.46706278369369864, 0.511648879842166, 0.49038583458744545, 0.4240684556714285, 0.5085615349599282, 0.4667558025833304, 0.5225293906551759, 0.4791700925332441, 0.42187666877056285, 0.4444577598049048, 0.43180975598120047, 0.47279635019359195, 0.40434165271953953, 0.4567439578687747, 0.4047810725738134, 0.45285436709795845, 0.5106699339221253, 0.41760528844233397, 0.463230639757571, 0.4583953066465225, 0.47033013236271226, 0.46012210399176057, 0.48140415708781703, 0.4471153121689473, 0.485398357745934, 0.4602156421568477, 0.48008157966420123, 0.4202314394133098, 0.504311984447005, 0.4655888166277228, 0.43114982313289985, 0.46496997393407696, 0.46041725990525456, 0.4662905080385762, 0.43186752985533855, 0.5113262759807295, 0.4719745720033306, 0.47791479563461675, 0.46799098060250977, 0.40620578584396677, 0.42314041607019615, 0.4162314065076259, 0.41579571768218204, 0.43814693535584737, 0.47413006835703997, 0.4974571568255316, 0.4935654224734384, 0.48136060672275627, 0.4550978367425495, 0.49706958170713433, 0.44513768595224995, 0.4253361121582329, 0.44381941515869333, 0.4761198169714065, 0.47667447892671105, 0.48046363042033574, 0.5199316709111657, 0.48927857372412814, 0.4808599995841265, 0.49799963296315697, 0.4492087033317719, 0.46986478238223167, 0.506700053418057, 0.4987938011003559, 0.4544414206143903, 0.5377744716063275, 0.5140073014745788, 0.42192876338556845, 0.4486045885520557, 0.42644917513144487, 0.4116325393736495, 0.4322134994562949, 0.476302541798784, 0.48675134068911835, 0.41824997807779385, 0.426746519901415, 0.46480259963728177, 0.5214455692010816, 0.41548303889992255, 0.42933136120094717, 0.4838030541852354, 0.494936691128753, 0.49186212498168014, 0.4217631685828114,
53 | 0.45602912462583534, 0.5125161938121239, 0.4457479372848052, 0.46618893650081916, 0.48881100807439615, 0.43768350802896466, 0.4739599720363637, 0.4955716129352989, 0.4804280162630706, 0.48163906724030736, 0.4143071427832678, 0.48475848400436833, 0.44899270858594775, 0.4838938111763643, 0.4848282167826762, 0.4838980545767503, 0.4866190119509327, 0.4717631934896995, 0.5165489359356199, 0.48360361419074716, 0.4804091649028527, 0.5097297759525212, 0.4571519002443824, 0.4452585896454598, 0.4414109845063244, 0.4235666003629125, 0.5153951286649423, 0.4883078008311837, 0.4346874565124854, 0.5005732966822127, 0.417852787993552, 0.4145857127347467, 0.48591110524336795, 0.4345903953415311, 0.41977222100784434, 0.5371283981310165, 0.47305277802964524, 0.44317952697867435, 0.4036964309526516, 0.4581214250541329, 0.5463341411652219, 0.46045127199889063, 0.4501169516101683, 0.4179825918218954, 0.49900783694877715, 0.4892906123586632, 0.42840660739898967, 0.47162708436149237, 0.4345798849491902, 0.47562520954776094, 0.4340927110566402, 0.4313336037367724, 0.4129143693247415, 0.5135537564781154, 0.47204003930970917, 0.4210640712529034, 0.4245605754426493, 0.4743745984824515, 0.48794937883439804, 0.4180700741879826, 0.4912515867736354, 0.4903159358869692, 0.49091273489139003, 0.4327263671175196, 0.5112962766853835, 0.418128526296058, 0.4832865396091334, 0.48082133074596606, 0.4832623410972604, 0.41270459153098055, 0.42109973525643424, 0.4998801209675613, 0.46762469008572893, 0.4799947903769364, 0.4736394640658181, 0.47211493605277344, 0.5287411401320841, 0.5200724040148723, 0.5066205296433474, 0.5127730183590961, 0.44369916589791547, 0.48456698587240804, 0.5051576392479146, 0.5081283632369991, 0.4193870952105006, 0.43548458423797165, 0.5146117075667941, 0.6496553944513833, 0.4143930795231045, 0.4289819520927289, 0.5080801555292406, 0.5131411994688787, 0.43696130146368667, 0.5427646826654766, 0.45345802627109194, 0.5433482910534887, 0.5143319170186181, 0.5097298427495505, 0.5136637813655547, 0.5106507420608952, 0.5548887569702587, 0.7065321055530301, 0.5168715814597589, 0.41794267534812685, 0.43090336510087845, 0.7212155749399769, 0.6165544559697002, 0.46033737106777256, 0.5089387495523169, 0.5253975539361965, 0.5115566116956278, 0.42320202401689294, 0.5246174570570632, 0.6281310330202612, 0.4751536510310882, 0.5950102991564058, 0.4978649425068354, 0.46610446928565485, 0.544534190394418, 0.6016255287956038, 0.5631491919128527, 0.6833236214330077, 0.4110880226407702, 0.4722339929634415, 0.5323749024552461, 0.4891842913332914, 0.6762690545068252, 0.41950833442907715, 0.4876659176727193, 0.6046630614307239, 0.4928000945510993, 0.553452844399436, 0.4511162775004234, 0.47151456349690807, 0.4909478739757076, 0.4918155366451409, 0.4431381515130087, 0.48011543632848297, 0.6012506969150045, 0.4602080508155012, 0.4857964362690456, 0.554271610426304, 0.41699549081779524, 0.4613389595659844, 0.413520621478622, 0.5796217614630786, 0.4849478885457273, 0.405352719966207, 0.4885767886098703, 0.5219683081108104, 0.4626909895475748, 0.5026622317544714, 0.5683235089403735, 0.40180703773062326, 0.41191760583198633, 0.39797130773487593]
54 |
55 | plt.plot(range(len(e3s)), e3s)
56 |
57 |
58 |
--------------------------------------------------------------------------------
/notebook/qwgc_tutorial.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | # ---
3 | # jupyter:
4 | # jupytext:
5 | # text_representation:
6 | # extension: .py
7 | # format_name: light
8 | # format_version: '1.5'
9 | # jupytext_version: 1.3.3
10 | # kernelspec:
11 | # display_name: Python 3
12 | # language: python
13 | # name: python3
14 | # ---
15 |
16 | # # Quantum Walk Graph Classifier
17 |
18 | # 今回の成果物である量子ウォークにおけるグラフの分類器に関するチュートリアル
19 |
20 | # +
21 | import numpy as np
22 | import random
23 | import copy
24 | import sys
25 | import networkx as nx
26 | import matplotlib.pyplot as plt
27 |
28 | from numpy import pi
29 | from tqdm import trange
30 | from grakel import datasets, Graph
31 | from sklearn.model_selection import KFold
32 |
33 | sys.path.append("../")
34 | from qwgc.QWGC import QWGC
35 | # -
36 | # # 量子ウォーク
37 |
38 | # このプロジェクトにおける肝となる量子アルゴリズムである量子ウォークというものについてです。詳しくは我々の[プロジェクトページ](https://qwqmlf.github.io/QuantumFrontier/article)をご覧ください。今回は[MUTAG](https://rdrr.io/cran/QSARdata/man/mutagen.html)と呼ばれるデータセットを用いて、量子ウォークがグラフ上で行われるということがどういうことなのかということについて見ていきます。
39 |
40 | # MUTAGを取ってくる
41 | Data = datasets.fetch_dataset('MUTAG', verbose=False)
42 | data_x, data_y = np.array(Data.data), np.array(Data.target)
43 |
44 | # まずはMUTAGとはどのようなデータなのかという点について見ていきます。代表として先頭10データを可視化していきたいと思います。
45 |
46 | # visualization of data
47 | subtract = 0
48 | lens = []
49 | for d, l in zip(data_x[:10], data_y[:10]):
50 | print(l)
51 | plt.figure(figsize=(10, 10))
52 | G = nx.DiGraph()
53 | connection = d[0]
54 | nodesize = [(i+1)**800 for i in d[1].values()]
55 | edge_weight = d[2]
56 | lens.append(len([i for i in d[1].values()]))
57 | adjacency = Graph(connection).get_adjacency_matrix()
58 | nodes = np.array([str(i+1) for i, _ in enumerate(adjacency)])
59 | edges = []
60 | weight = []
61 | for i, v in edge_weight.items():
62 | ed = [str(st-subtract) for st in list(i)]
63 | ed.append(v+1)
64 | edges.append(tuple(ed))
65 | subtract = max(d[1].keys())
66 | G.add_nodes_from(nodes)
67 | G.add_weighted_edges_from(edges)
68 | pos = nx.kamada_kawai_layout(G)
69 | edge_labels = {(i, j): w['weight'] for i, j, w in G.edges(data=True)}
70 | nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
71 | nx.draw_networkx(G, pos, with_labels=True, alpha=0.8)
72 | plt.show()
73 |
74 | # これらがMUTAGと呼ばれている変異原性があるのかないのかというデータセットになります。10から30程度のノード数を持ったグラフデータの集まりで、各ノードはある元素を表していて、各リンクは元素間の結合を表しています。各リンクの間についているラベルはその結合がどのような結合なのかということを表しています。ではここの上で量子ウォークを行うと、どのような状態がえられるのかということを見ていきたいと思います。
75 |
76 | # 今回のプログラムはこちらの論文を参考としています。[Barr, Katie, Toby Fleming, and Viv Kendon. "Simulation methods for quantum walks on graphs applied to perfect state transfer and formal language recognition." Proceedings of the 2013 workshop on complex systems modelling and simulation, Milan, Italy. 2013.]
77 |
78 | # まずは量子ウォーカーが1ステップ進んだ時を考えます。スタートは全て0ノードです。
79 |
80 | # +
81 | from qwgc.preprocess.qwalk import QuantumWalk
82 | # 対象のデータ
83 | data = data_x[0]
84 | label = data_y[0]
85 | # 隣接行列
86 | adjacency = Graph(data[0]).get_adjacency_matrix()
87 | count = np.count_nonzero(adjacency)//2
88 | # 量子ウォークのハイパーパラメータ
89 | step = 1
90 | # 次数が2の場合のコインのパラメータ(今回は簡単のために全てアダマールコイン)
91 | coin = np.kron(np.identity(count), 1/np.sqrt(2)*np.array([[1, 1], [1, -1]]))
92 | # 初期状態 (0からスタート)
93 | initial = None
94 | # 量子ウォーカーが測定される確率
95 | qwalk = QuantumWalk(initial, coin, adjacency)
96 | qwalk.n_steps(step)
97 | probs = qwalk.calc_probs()
98 |
99 | # 描画
100 | plt.figure(figsize=(10, 10))
101 | G = nx.DiGraph()
102 | # ノードの大きさで確率を表す
103 | connection = data[0]
104 | nodesize = [(i+0.1)*800 for i in probs]
105 | edge_weight = data[2]
106 | nodes = np.array([str(i+1) for i, _ in enumerate(adjacency)])
107 | edges = []
108 | weight = []
109 | for i, v in edge_weight.items():
110 | ed = [str(st) for st in list(i)]
111 | ed.append(v+1)
112 | edges.append(tuple(ed))
113 | subtract = max(data[1].keys())
114 | G.add_nodes_from(nodes)
115 | G.add_weighted_edges_from(edges)
116 | pos = nx.spring_layout(G)
117 | edge_labels = {(i, j): w['weight'] for i, j, w in G.edges(data=True)}
118 | nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
119 | nx.draw_networkx(G, pos, with_labels=True, alpha=0.8, node_size=nodesize)
120 | plt.show()
121 |
122 |
123 | # -
124 |
125 | # このように初期のノードから隣り合った二つのノードにおいて量子ウォーカーが観測されうるのがわかるかと思います。
126 | # もう少しステップを進めてみます。
127 |
128 | def draw(nodesize):
129 | plt.figure(figsize=(10, 10))
130 | G = nx.DiGraph()
131 | # ノードの大きさで確率を表す
132 | connection = data[0]
133 | nodesize = [(i)*800 for i in probs]
134 | edge_weight = data[2]
135 | nodes = np.array([str(i+1) for i, _ in enumerate(adjacency)])
136 | edges = []
137 | weight = []
138 | for i, v in edge_weight.items():
139 | ed = [str(st) for st in list(i)]
140 | ed.append(v+1)
141 | edges.append(tuple(ed))
142 | subtract = max(data[1].keys())
143 | G.add_nodes_from(nodes)
144 | G.add_weighted_edges_from(edges)
145 | pos = nx.spring_layout(G)
146 | edge_labels = {(i, j): w['weight'] for i, j, w in G.edges(data=True)}
147 | nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
148 | nx.draw_networkx(G, pos, with_labels=True, alpha=0.8, node_size=nodesize)
149 | plt.show()
150 |
151 |
152 | data = data_x[0]
153 | label = data_y[0]
154 | # 隣接行列
155 | adjacency = Graph(data[0]).get_adjacency_matrix()
156 | count = np.count_nonzero(adjacency)//2
157 | # 量子ウォークのハイパーパラメータ
158 | for step in range(1, 10):
159 | # 次数が2の場合のコインのパラメータ(今回は簡単のために全てアダマールコイン)
160 | coin = np.kron(np.identity(count), 1/np.sqrt(2)*np.array([[1, 1], [1, -1]]))
161 | # 初期状態 (0からスタート)
162 | initial = None
163 | # 量子ウォーカーが測定される確率
164 | qwalk = QuantumWalk(initial, coin, adjacency)
165 | qwalk.n_steps(step)
166 | probs = qwalk.calc_probs()
167 | draw(probs)
168 |
169 | # やや見辛いですが、少しずつ観測される確率が広がっていっていることがわかると思います。
170 |
171 | # # 分類回路
172 |
173 | # これらを実際に量子回路に流して分類を行なっていきます。
174 |
175 | from qwgc.preprocess.qwfilter import QWfilter
176 | from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
177 | from qiskit import Aer, execute, transpile
178 | data = data_x[0]
179 | label = data_y[0]
180 | # filter
181 | u3param = [pi, 0, pi/2]
182 | # step
183 | step = 3
184 | # initial 重ね合わせを初期状態として利用
185 | initial = "super"
186 | qwfilter = QWfilter(u3param, step, initial)
187 | # 今回は測定をせずに、振幅をそのまま量子回路にマッピングを行います。
188 | amplitude = qwfilter.single_amplitude(data)
189 |
190 | # これにより特定のステップが終了した後の量子ウォークの確率振幅を取り出すことができました。これをqiskitのinitialize関数というものを用いて量子ビットに情報として入れていきます。またこの時$2^n$の大きさのベクトルである必要があることから0埋めを行います。
191 |
192 | la = len(amplitude)
193 | new_amplitude = list(amplitude) + [0 for i in range(64 - 38)]
194 | print(len(new_amplitude))
195 |
196 | nq = 6
197 | # 量子レジスタの定義
198 | qr = QuantumRegister(nq, name="quantum walk")
199 | ancilla = QuantumRegister(2, name="ancilla")
200 | # 古典レジスタの定義
201 | cr = ClassicalRegister(2)
202 | # 量子回路の定義
203 | qc = QuantumCircuit(qr, ancilla, cr)
204 | qc.draw(output='mpl')
205 |
206 | # このように合計8量子ビットを用意しました。このうち上6つが量子ウォークのデータ(実際の実験ではこの部分が7個になっています。)、下2つが補助の量子ビットになっています。ここに量子ウォーク後の確率振幅を入れていきます。
207 |
208 | qc.initialize(new_amplitude, qr)
209 |
210 | # そして、パラメータを初期化し、補助量子ビットに制御Ryゲートを用いてマッピングを行なっていきます。
211 |
212 | # 回転角を初期化
213 | theta = [np.random.uniform(-pi, pi) for i in range(nq)]
214 | for ith, th in enumerate(theta):
215 | qc.cry(th, qr[ith], ancilla[ith%2])
216 | qc.draw(output="mpl")
217 |
218 | # 最後に補助量子ビットを測定します。
219 |
220 | qc.measure(ancilla, cr)
221 |
222 | # この測定によって、このグラフがどのクラスに分類されるのかということを見ていきます。今回は01をクラス-1、(つまり変異原性の性質が陰性)10をクラスの1(性質が陽性)とします。
223 |
224 | backend = Aer.get_backend("qasm_simulator")
225 | shots = 1024
226 | job = execute(qc, backend=backend, shots=shots)
227 | counts = job.result().get_counts(qc)
228 | dinom = counts.get('01', 0) + counts.get('10', 0) + 1e-10
229 | print("クラス-1である確率:", counts.get('01', 0)/dinom, "クラス1である確率:", counts.get('10', 0)/dinom)
230 | if counts.get('01', 0)/dinom > counts.get('10', 0)/dinom:
231 | answer = -1
232 | else:
233 | answer = 1
234 | print("このグラフはクラス ", answer, "です.")
235 |
236 | # このような分類結果になります。これを実際のラベルと比較をしてみます。
237 |
238 | print("正解は", data_y[1], "です。")
239 |
240 | # これらを全てのデータに対して行い、エラーを計算し実際にパラメータのアップデートを行なっていきます。
241 |
--------------------------------------------------------------------------------
/notebook/random_walk.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": 1,
6 | "metadata": {
7 | "ExecuteTime": {
8 | "end_time": "2020-02-07T05:47:10.548954Z",
9 | "start_time": "2020-02-07T05:47:10.062430Z"
10 | }
11 | },
12 | "outputs": [],
13 | "source": [
14 | "%matplotlib inline\n",
15 | "import matplotlib.pyplot as plt\n",
16 | "import numpy as np"
17 | ]
18 | },
19 | {
20 | "cell_type": "code",
21 | "execution_count": 15,
22 | "metadata": {
23 | "ExecuteTime": {
24 | "end_time": "2020-02-07T06:01:38.608976Z",
25 | "start_time": "2020-02-07T06:01:38.596435Z"
26 | }
27 | },
28 | "outputs": [
29 | {
30 | "data": {
31 | "text/plain": [
32 | "array([-0.01535351, -0.5319249 , -1.66412157, ..., -0.35529907,\n",
33 | " -0.44420375, -0.30539867])"
34 | ]
35 | },
36 | "execution_count": 15,
37 | "metadata": {},
38 | "output_type": "execute_result"
39 | }
40 | ],
41 | "source": [
42 | "random_walk = np.random.randn(100000)\n",
43 | "random_walk"
44 | ]
45 | },
46 | {
47 | "cell_type": "code",
48 | "execution_count": 16,
49 | "metadata": {
50 | "ExecuteTime": {
51 | "end_time": "2020-02-07T06:01:40.414733Z",
52 | "start_time": "2020-02-07T06:01:38.745700Z"
53 | },
54 | "scrolled": false
55 | },
56 | "outputs": [
57 | {
58 | "data": {
59 | "text/plain": [
60 | "(array([ 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,\n",
61 | " 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,\n",
62 | " 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,\n",
63 | " 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,\n",
64 | " 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,\n",
65 | " 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,\n",
66 | " 0., 0., 0., 0., 0., 0., 1., 1., 0., 0., 0.,\n",
67 | " 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,\n",
68 | " 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,\n",
69 | " 0., 0., 1., 1., 0., 0., 0., 1., 0., 0., 0.,\n",
70 | " 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 1.,\n",
71 | " 0., 0., 1., 0., 1., 0., 0., 0., 0., 0., 0.,\n",
72 | " 1., 1., 0., 1., 1., 2., 0., 0., 0., 0., 1.,\n",
73 | " 1., 0., 0., 1., 1., 1., 0., 2., 1., 0., 1.,\n",
74 | " 0., 1., 1., 2., 2., 1., 1., 3., 3., 1., 0.,\n",
75 | " 1., 2., 1., 3., 1., 2., 1., 1., 2., 1., 2.,\n",
76 | " 3., 4., 3., 0., 3., 0., 1., 1., 3., 1., 0.,\n",
77 | " 3., 4., 5., 3., 1., 3., 3., 5., 2., 5., 3.,\n",
78 | " 4., 5., 1., 3., 5., 4., 6., 7., 2., 7., 7.,\n",
79 | " 3., 4., 7., 5., 4., 4., 3., 5., 2., 6., 7.,\n",
80 | " 5., 3., 4., 7., 2., 5., 11., 8., 13., 6., 5.,\n",
81 | " 9., 10., 5., 9., 13., 8., 10., 8., 11., 12., 15.,\n",
82 | " 8., 12., 7., 7., 8., 12., 15., 10., 18., 17., 15.,\n",
83 | " 13., 18., 14., 10., 12., 18., 20., 23., 20., 21., 17.,\n",
84 | " 25., 21., 21., 21., 16., 26., 15., 23., 24., 23., 21.,\n",
85 | " 27., 26., 21., 23., 25., 31., 24., 23., 28., 35., 24.,\n",
86 | " 34., 36., 26., 30., 27., 31., 40., 29., 36., 37., 38.,\n",
87 | " 45., 33., 37., 44., 27., 48., 34., 46., 42., 46., 38.,\n",
88 | " 46., 53., 46., 63., 50., 64., 55., 62., 44., 55., 51.,\n",
89 | " 48., 69., 37., 55., 49., 49., 50., 75., 73., 65., 76.,\n",
90 | " 57., 68., 64., 57., 85., 70., 75., 71., 75., 79., 79.,\n",
91 | " 79., 85., 76., 68., 100., 88., 81., 83., 97., 110., 97.,\n",
92 | " 96., 102., 105., 93., 88., 110., 118., 85., 124., 106., 105.,\n",
93 | " 103., 113., 112., 99., 138., 127., 114., 121., 134., 145., 141.,\n",
94 | " 143., 130., 142., 147., 127., 139., 141., 146., 147., 159., 142.,\n",
95 | " 147., 138., 153., 152., 153., 153., 161., 167., 185., 164., 162.,\n",
96 | " 197., 201., 172., 173., 185., 187., 148., 167., 209., 189., 196.,\n",
97 | " 170., 202., 180., 186., 199., 201., 243., 204., 226., 233., 215.,\n",
98 | " 193., 205., 225., 200., 229., 243., 214., 246., 204., 232., 209.,\n",
99 | " 236., 233., 230., 245., 244., 270., 225., 237., 265., 249., 248.,\n",
100 | " 288., 251., 273., 238., 241., 300., 263., 283., 283., 297., 272.,\n",
101 | " 269., 263., 274., 303., 296., 297., 294., 290., 305., 292., 296.,\n",
102 | " 316., 296., 302., 314., 305., 316., 301., 313., 293., 315., 322.,\n",
103 | " 321., 326., 342., 332., 305., 317., 351., 354., 366., 340., 306.,\n",
104 | " 364., 329., 343., 350., 334., 351., 376., 351., 372., 333., 349.,\n",
105 | " 362., 334., 358., 345., 351., 371., 325., 361., 349., 356., 372.,\n",
106 | " 338., 364., 322., 372., 366., 337., 364., 385., 379., 384., 358.,\n",
107 | " 358., 368., 381., 382., 365., 384., 401., 366., 360., 383., 377.,\n",
108 | " 352., 383., 384., 384., 354., 368., 340., 354., 399., 403., 372.,\n",
109 | " 389., 375., 340., 381., 370., 338., 389., 382., 347., 400., 343.,\n",
110 | " 377., 370., 342., 355., 365., 358., 354., 346., 296., 343., 346.,\n",
111 | " 316., 364., 326., 371., 355., 334., 325., 352., 365., 348., 353.,\n",
112 | " 333., 347., 334., 345., 356., 347., 355., 360., 352., 317., 322.,\n",
113 | " 342., 333., 310., 329., 317., 308., 322., 339., 323., 305., 342.,\n",
114 | " 339., 283., 291., 318., 313., 266., 297., 285., 302., 288., 290.,\n",
115 | " 281., 290., 299., 288., 271., 252., 248., 275., 256., 293., 252.,\n",
116 | " 293., 298., 264., 283., 261., 229., 242., 259., 247., 250., 255.,\n",
117 | " 248., 240., 237., 245., 251., 241., 241., 249., 214., 224., 220.,\n",
118 | " 226., 238., 219., 235., 242., 222., 171., 214., 209., 228., 201.,\n",
119 | " 225., 211., 191., 180., 189., 184., 173., 175., 200., 155., 170.,\n",
120 | " 186., 169., 174., 185., 185., 156., 155., 159., 156., 172., 158.,\n",
121 | " 152., 161., 170., 140., 143., 151., 144., 140., 129., 130., 122.,\n",
122 | " 142., 135., 119., 114., 113., 121., 139., 135., 125., 124., 123.,\n",
123 | " 98., 116., 116., 130., 121., 110., 106., 96., 106., 104., 100.,\n",
124 | " 88., 84., 98., 87., 80., 103., 91., 90., 104., 110., 90.,\n",
125 | " 82., 93., 83., 91., 83., 90., 78., 84., 78., 78., 63.,\n",
126 | " 77., 65., 58., 68., 68., 59., 62., 56., 70., 46., 62.,\n",
127 | " 49., 48., 45., 50., 61., 57., 54., 49., 46., 58., 52.,\n",
128 | " 46., 49., 46., 48., 49., 53., 50., 46., 55., 44., 34.,\n",
129 | " 30., 35., 45., 32., 34., 41., 41., 33., 35., 27., 28.,\n",
130 | " 32., 20., 33., 35., 22., 26., 29., 32., 20., 22., 21.,\n",
131 | " 30., 28., 20., 26., 19., 23., 22., 24., 24., 11., 29.,\n",
132 | " 17., 23., 23., 14., 17., 9., 16., 19., 15., 12., 19.,\n",
133 | " 14., 12., 18., 13., 16., 17., 13., 17., 18., 5., 10.,\n",
134 | " 5., 14., 9., 11., 10., 10., 11., 9., 9., 6., 10.,\n",
135 | " 10., 7., 5., 4., 9., 2., 4., 6., 7., 2., 3.,\n",
136 | " 9., 10., 7., 6., 10., 5., 9., 4., 7., 8., 3.,\n",
137 | " 4., 6., 5., 5., 4., 4., 6., 4., 6., 5., 2.,\n",
138 | " 4., 3., 4., 1., 2., 3., 4., 3., 0., 1., 2.,\n",
139 | " 4., 3., 1., 2., 5., 3., 5., 4., 0., 3., 2.,\n",
140 | " 0., 1., 1., 1., 2., 3., 4., 0., 2., 1., 0.,\n",
141 | " 2., 1., 0., 0., 1., 1., 0., 0., 4., 2., 2.,\n",
142 | " 1., 1., 1., 2., 1., 1., 1., 0., 0., 3., 0.,\n",
143 | " 0., 0., 3., 2., 0., 0., 2., 2., 0., 1., 1.,\n",
144 | " 1., 2., 2., 0., 2., 1., 0., 0., 0., 0., 0.,\n",
145 | " 0., 0., 0., 1., 0., 1., 0., 0., 0., 1., 0.,\n",
146 | " 0., 1., 0., 0., 0., 0., 0., 1., 0., 0., 1.,\n",
147 | " 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,\n",
148 | " 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0.,\n",
149 | " 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,\n",
150 | " 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.]),\n",
151 | " array([-4.89790212, -4.88865781, -4.87941351, ..., 4.32791098,\n",
152 | " 4.33715528, 4.34639958]),\n",
153 | " )"
154 | ]
155 | },
156 | "execution_count": 16,
157 | "metadata": {},
158 | "output_type": "execute_result"
159 | },
160 | {
161 | "data": {
162 | "image/png": "iVBORw0KGgoAAAANSUhEUgAAAm0AAAJrCAYAAACyUqSjAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjMsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy+AADFEAAAgAElEQVR4nO3de7itdVkv/O8toPlmicoKEbBFQir1GiqSpSUCnk2szLR3KxhFe4c73VoK5bvTCrNdhnbSi9LAstQ8BAn2hhxCc3tABbdnUZcCoSxTUctQ4H7/GM+S6WTOteYc8zDmM+fnc13jGu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AACMgtAEAjIDQBgAwAv8/ympshDhWVkMAAAAASUVORK5CYII=\n",
163 | "text/plain": [
164 | ""
165 | ]
166 | },
167 | "metadata": {
168 | "needs_background": "light"
169 | },
170 | "output_type": "display_data"
171 | }
172 | ],
173 | "source": [
174 | "fig = plt.figure(figsize=(10, 10))\n",
175 | "plt.title(\"random walk\", fontsize=20)\n",
176 | "plt.xlabel(\"Position\", fontsize=20)\n",
177 | "plt.ylabel(\"Probability\", fontsize=20)\n",
178 | "plt.hist(random_walk, 1000)"
179 | ]
180 | },
181 | {
182 | "cell_type": "code",
183 | "execution_count": null,
184 | "metadata": {},
185 | "outputs": [],
186 | "source": []
187 | }
188 | ],
189 | "metadata": {
190 | "jupytext": {
191 | "text_representation": {
192 | "extension": ".py",
193 | "format_name": "light",
194 | "format_version": "1.5",
195 | "jupytext_version": "1.3.3"
196 | }
197 | },
198 | "kernelspec": {
199 | "display_name": "Python 3",
200 | "language": "python",
201 | "name": "python3"
202 | },
203 | "varInspector": {
204 | "cols": {
205 | "lenName": 16,
206 | "lenType": 16,
207 | "lenVar": 40
208 | },
209 | "kernels_config": {
210 | "python": {
211 | "delete_cmd_postfix": "",
212 | "delete_cmd_prefix": "del ",
213 | "library": "var_list.py",
214 | "varRefreshCmd": "print(var_dic_list())"
215 | },
216 | "r": {
217 | "delete_cmd_postfix": ") ",
218 | "delete_cmd_prefix": "rm(",
219 | "library": "var_list.r",
220 | "varRefreshCmd": "cat(var_dic_list()) "
221 | }
222 | },
223 | "types_to_exclude": [
224 | "module",
225 | "function",
226 | "builtin_function_or_method",
227 | "instance",
228 | "_Feature"
229 | ],
230 | "window_display": false
231 | }
232 | },
233 | "nbformat": 4,
234 | "nbformat_minor": 4
235 | }
236 |
--------------------------------------------------------------------------------
/notebook/random_walk.py:
--------------------------------------------------------------------------------
1 | # ---
2 | # jupyter:
3 | # jupytext:
4 | # text_representation:
5 | # extension: .py
6 | # format_name: light
7 | # format_version: '1.5'
8 | # jupytext_version: 1.3.3
9 | # kernelspec:
10 | # display_name: Python 3
11 | # language: python
12 | # name: python3
13 | # ---
14 |
15 | # %matplotlib inline
16 | import matplotlib.pyplot as plt
17 | import numpy as np
18 |
19 | random_walk = np.random.randn(100000)
20 | random_walk
21 |
22 | fig = plt.figure(figsize=(10, 10))
23 | plt.title("random walk", fontsize=20)
24 | plt.xlabel("Position", fontsize=20)
25 | plt.ylabel("Probability", fontsize=20)
26 | plt.hist(random_walk, 1000)
27 |
28 |
29 |
--------------------------------------------------------------------------------
/qwgc/QWGC.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import random
3 | import copy
4 | import time
5 |
6 | from numpy import pi
7 | from tqdm import trange
8 | from grakel import datasets
9 | from sklearn.model_selection import KFold
10 |
11 | try:
12 | # FIXME
13 | from .classifier.qcircuit import ClassifierCircuit
14 | from .preprocess.qwfilter import QWfilter
15 | except ImportError:
16 | from classifier.qcircuit import ClassifierCircuit
17 | from preprocess.qwfilter import QWfilter
18 |
19 | try:
20 | from utils.notification import Notify
21 | notify = True
22 | except Exception:
23 | notify = False
24 | np.set_printoptions(threshold=10000)
25 |
26 | THETA_MIN, THETA_MAX = -pi, pi
27 |
28 |
29 | class QWGC:
30 | '''
31 | In this package, we selected particle swarm optimzier as a optimizer
32 | for tuning vector theta.
33 | You can choose any of optimization way, but gradient way might not
34 | suit for this model.
35 | FIXME: more customizable
36 | In this scheme, the type of coin is constantly changing in each iteraions.
37 | '''
38 |
39 | def __init__(self, encoder, Cp=1.8, Cg=1.3, n_particle=20, T=100, w=0.8,
40 | ro_max=1.0, n_layer=2, lamb=0.005, n_steps=5,
41 | initial='super', **kwargs):
42 | '''
43 | Hyper parameters of model.
44 | Input:
45 | FIXME:
46 | encoder: list of binary
47 | e.g. ['01', '10']
48 | length of encoder must be the same as the number of class
49 | Cp: float (constant value of coefficient
50 | for personal best position)
51 | Cg: float (constant value of coefficient
52 | for grobal best position)
53 | n_particle: int (the number of particles
54 | for searching better parameters)
55 | T: int (the number of iterations of how many times
56 | this model learns)
57 | w: float (constant value of coefficient
58 | for previous particle directions)
59 | ro_max: float (maximum number of random number
60 | which is used for updating parameter)
61 | n_layer: int (the number of layers of mapping circuit)
62 | lamb: float (constant value of coefficient
63 | for the sum of square in error)
64 | n_steps: int (the number of steps of Quantum walk)
65 | '''
66 | if len(encoder[0]) != n_layer:
67 | raise ValueError('The size of encoder is different\
68 | from the number of layers')
69 | self.encoder = encoder
70 | self.Cp = Cp
71 | self.Cg = Cg
72 | self.w = w
73 | self.ro_max = ro_max
74 | # FIXME more efficient
75 | if T < 0:
76 | raise ValueError('The number of iterations must be \
77 | non negative value')
78 | if n_particle < 0:
79 | raise ValueError('The number of particles must be\
80 | non negative value')
81 | if n_layer <= 0:
82 | raise ValueError('The number of layers must be\
83 | one or over')
84 | if n_steps < 0:
85 | raise ValueError('The number of steps must be\
86 | zero or over')
87 | self.T = T
88 | self.n_particle = n_particle
89 | self.layers = n_layer
90 | self.step = n_steps
91 | self.lamb = lamb
92 | self.initial = initial
93 |
94 | def optimize(self, train_data, train_label, coin_update=False):
95 | '''
96 | Input:
97 | train_data: 2dim array (a series of training data)
98 | train_label: 2dim array (a series of label, one hot)
99 | Output:
100 | theta: array
101 | coin_param: ?
102 | '''
103 | self.n_class = len(train_label[0])
104 | if self.n_class > 2**self.layers:
105 | raise ValueError('the number of class must be less than 2^layers')
106 |
107 | # initial parameter for Quantum Walk
108 | # each particle has [theta, phi, lambda]
109 | # coin_u3s = np.array([[random.uniform(THETA_MIN, THETA_MAX)
110 | # for i in range(3)]
111 | # for n in range(self.n_particle)])
112 | if coin_update:
113 | coin_u3s = np.array([[random.uniform(THETA_MIN, THETA_MAX),
114 | 0, 0]
115 | for n in range(self.n_particle)])
116 | else:
117 | coin_u3s = np.array([[pi/2, pi/2, 0]
118 | for n in range(self.n_particle)])
119 |
120 | ampdata = [QWfilter(coin_u3s[n], self.step,
121 | self.initial).amplitude(train_data)
122 | for n in range(self.n_particle)]
123 | theta_size = self.ceilog(max(set(map(len, ampdata[0]))))
124 |
125 | # FIXME
126 | n_amp = np.array([[self._zero_fill(amp, 2**theta_size)
127 | for amp in ampdata[n]]
128 | for n in range(self.n_particle)])
129 |
130 | # initialize particles
131 | particles = np.array([np.array([random.uniform(THETA_MIN, THETA_MAX)
132 | for i in range(theta_size)])
133 | for n in range(self.n_particle)])
134 |
135 | velocities = np.array([np.zeros(theta_size)
136 | for n in range(self.n_particle)])
137 | coin_v = np.array([np.zeros(3) for n in range(self.n_particle)])
138 |
139 | # for recording best positions of each particle
140 | personal_bpos = copy.copy(particles)
141 | personal_cbpos = copy.copy(coin_u3s)
142 | personal_best_scores = [self._get_cost(amps, train_label, theta, notify=False)
143 | for amps, theta in zip(n_amp, particles)]
144 |
145 | # recording best position of all particles
146 | best_particle = np.argmin(personal_best_scores)
147 | grobal_best_pos = personal_bpos[best_particle]
148 | grobal_best_coin = coin_u3s[best_particle]
149 | # print(train_label)
150 |
151 | print('training start!')
152 | # start training
153 | # to check convergence of error, prepare this list
154 | errors = []
155 | accuracy = []
156 | flag = 1
157 | for nap in n_amp[best_particle]:
158 | print(list(nap))
159 | for t in trange(self.T, desc='training'):
160 | ampdata = [QWfilter(coin_u3s[n], self.step,
161 | self.initial).amplitude(train_data)
162 | for n in range(self.n_particle)]
163 | n_amp = np.array([[self._zero_fill(amp, 2**theta_size)
164 | for amp in ampdata[n]]
165 | for n in range(self.n_particle)])
166 | for n in range(self.n_particle):
167 | amp = n_amp[n]
168 | # random number for personal best pos
169 | rnp = random.uniform(0, self.ro_max)
170 | # random number for grobal best
171 | rng = random.uniform(0, self.ro_max)
172 | rnp_c = random.uniform(0, self.ro_max)
173 | rng_c = random.uniform(0, self.ro_max)
174 |
175 | # update positions parameter
176 | particles[n] = particles[n] + velocities[n]
177 | velocities[n] = (self.w*velocities[n] +
178 | self.Cp*rnp*(personal_bpos[n]-particles[n]) +
179 | self.Cg*rng*(grobal_best_pos-particles[n]))
180 | # update coins
181 | # coin_u3s[n] = coin_u3s[n] + coin_v[n]
182 | # No coin update
183 | if coin_update:
184 | coin_u3s[n] = coin_u3s[n] + coin_v[n]
185 |
186 | coin_v[n] = (self.w*coin_v[n] +
187 | self.Cp*rnp_c*(personal_cbpos[n]-coin_u3s[n]) +
188 | self.Cg*rng_c*(grobal_best_coin-coin_u3s[n]))
189 |
190 | # calculation cost with updated parameters
191 | # and update best position and score
192 | score = self._get_cost(amp, train_label, particles[n])
193 | if score < personal_best_scores[n]:
194 | personal_best_scores[n] = score
195 | personal_bpos[n] = particles[n]
196 | personal_cbpos[n] = coin_u3s[n]
197 |
198 | # in all particles, calculate which is the best particle
199 | # and coin parameters
200 | best_particle = np.argmin(personal_best_scores)
201 | grobal_best_coin = coin_u3s[best_particle]
202 | grobal_best_pos = personal_bpos[best_particle]
203 |
204 | best_amp_data = QWfilter(grobal_best_coin, self.step,
205 | self.initial).amplitude(train_data)
206 | n_best_amp = [self._zero_fill(amp, 2**theta_size)
207 | for amp in best_amp_data]
208 | if t % 10 == 0:
209 | error = self._get_cost(n_best_amp, train_label, grobal_best_pos, notify=False)
210 | else:
211 | error = self._get_cost(n_best_amp, train_label, grobal_best_pos, notify=False)
212 | accs = self._get_accuracy(n_best_amp, train_label,
213 | grobal_best_pos)
214 | errors.append(error)
215 | accuracy.append(accs)
216 | # print(error, accs)
217 | # if t % 10 == 0:
218 | # flag *= -1
219 | # if notify:
220 | # Notify.notify_error(t, error, accs)
221 | if error < 0.40:
222 | break
223 | # if t > 10 and np.mean(errors[-10:-1]) < errors[-1]:
224 | # # print(particles)
225 | # reseter = np.array([[random.uniform(-pi/8, pi/8) for _ in range(theta_size)]for n in range(particles)])
226 | # # print('reseter', reseter, 'best particle', best_particle)
227 | # particles = np.array([p+reseter for i, p in enumerate(particles) if i != best_particle])
228 | # # print(particles)
229 | for nap in n_amp[best_particle]:
230 | print(list(nap))
231 | convergence = [errors, accuracy]
232 | return grobal_best_pos, grobal_best_coin, convergence
233 |
234 | def _get_cost(self, data, label, theta, notify=False):
235 | cost = ClassifierCircuit(data, label, theta, self.n_class,
236 | self.layers, self.encoder).cost(notify=notify)
237 |
238 | error = cost + self.lamb*np.sum([i**2 for i in theta])
239 | return error
240 |
241 | def _get_accuracy(self, data, label, theta):
242 | answers = ClassifierCircuit(data, label, theta, self.n_class,
243 | self.layers, self.encoder).answers()
244 | acc = self._accs(answers, label)
245 | return acc
246 |
247 | @staticmethod
248 | def ceilog(x):
249 | return int(np.ceil(np.log2(x)))
250 |
251 | def test(self, test_data, theta, coin_param):
252 | '''
253 | Test function to evaluate the performance
254 | Input:
255 | test_data: 2dim array (a series of test data)
256 | theta: tuned parameters theta
257 | coin_param: optimzed coin parameters
258 | Output:
259 | answers: 2dim array (answers for each data)
260 | '''
261 | theta_size = len(theta)
262 | ampdata = QWfilter(coin_param, self.step,
263 | self.initial).amplitude(test_data)
264 | n_amp = np.array([self._zero_fill(amp, 2**theta_size)
265 | for amp in ampdata])
266 | # TODO Inplement the case that the number of class is unknown
267 | answers = ClassifierCircuit(n_amp, None, theta, 2,
268 | self.layers, self.encoder).answers()
269 | return answers
270 |
271 | def _accs(self, ans, label):
272 | count = 0
273 | for i, j in zip(ans, label):
274 | if np.argmax(i) == np.argmax(j):
275 | count += 1
276 | # print('answer ', [np.argmax(i) for i in ans])
277 | # print('label ', [np.argmax(i) for i in label])
278 | return count/len(label)
279 |
280 | @staticmethod
281 | def _zero_fill(x, base, array=True):
282 |
283 | # FIXME efficiently
284 | xl = list(x)
285 | x_len = len(xl)
286 | if base - x_len < 0:
287 | raise ValueError('Error')
288 | xs = xl + [0 for _ in range(base-x_len)]
289 | if array:
290 | return np.array(xs)
291 | else:
292 | return xs
293 |
294 | def summary(self, answer, label, printer=False):
295 | accs = self._accs(answer, label)
296 | if printer:
297 | print('The accuracy of this model is ', accs)
298 | return accs
299 |
300 |
301 | def one_hot_encoder(label, n_class):
302 | enc_label = [np.zeros(n_class) for _ in label]
303 | for ilb, lb in enumerate(label):
304 | if lb == -1:
305 | enc_label[ilb][0] = 1
306 | else:
307 | enc_label[ilb][lb-1] = 1
308 | return enc_label
309 |
310 |
311 | if __name__ == '__main__':
312 | # prepare dataset
313 | import toml
314 | # parsing parameters from toml
315 | config = toml.load('experiments.toml')
316 | p_pso = config['pso']
317 | p_qw = config['qw']
318 |
319 | data_name = 'ENZYMES'
320 | Data = datasets.fetch_dataset(data_name, verbose=False)
321 | data_x, data_y = np.array(Data.data), np.array(Data.target)
322 |
323 | acclist = []
324 | k = 10
325 | kf = KFold(n_splits=k, shuffle=True, random_state=1)
326 |
327 | qwgc = QWGC(['000001', '000010', '000100', '001000', '010000', '100000'],
328 | Cp=p_pso['Cp'], Cg=p_pso['Cg'],
329 | n_particle=p_pso['particles'], T=p_pso['iterations'],
330 | w=p_pso['w'], ro_max=p_pso['random_max'],
331 | n_layer=p_pso['layers'], lamb=p_pso['lambda'],
332 | n_steps=p_qw['steps'], initial=p_qw['initial'])
333 |
334 | for train_index, test_index in kf.split(data_x):
335 | # preprocessing for generating data.
336 | x_train, y_train = data_x[train_index], data_y[train_index]
337 | x_test, y_test = data_x[test_index], data_y[test_index]
338 | # Notify.notify_accs("class%d" % y_train[0], "class%d" % y_train[-1])
339 |
340 | # one hot encoding
341 | print(list(y_train))
342 | y_train = one_hot_encoder(y_train, 6)
343 | y_test = one_hot_encoder(y_test, 6)
344 |
345 | theta, coin_param, conv = qwgc.optimize(x_train, y_train)
346 | # test
347 | ans = qwgc.test(x_test, theta, coin_param)
348 | # evaluate
349 | accs = qwgc.summary(ans, y_test)
350 |
351 | acclist.append(accs)
352 | print(accs)
353 | if notify:
354 | Notify.notify_accs(accs, conv)
355 | print('acclist', acclist)
356 | print('mean', np.mean(acclist))
357 |
--------------------------------------------------------------------------------
/qwgc/QWGC_mix.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import random
3 | import copy
4 |
5 | from numpy import pi
6 | from tqdm import trange
7 | from grakel import datasets
8 | from sklearn.model_selection import KFold
9 |
10 | from classifier.qcircuit import ClassifierCircuit
11 | from preprocess.qwfilter import QWfilter
12 |
13 | try:
14 | from utils.notification import Notify
15 | notify = True
16 | except Exception:
17 | notify = False
18 |
19 | THETA_MIN, THETA_MAX = -pi, pi
20 |
21 |
22 | class QWGC:
23 | '''
24 | In this package, we selected particle swarm optimzier as a optimizer
25 | for tuning vector theta.
26 | You can choose any of optimization way, but gradient way might not
27 | suit for this model.
28 | FIXME: more customizable
29 | In this scheme, the type of coin is constantly changing in each iteraions.
30 | '''
31 |
32 | def __init__(self, encoder, Cp=1.8, Cg=1.3, n_particle=20, T=100, w=0.8,
33 | ro_max=1.0, n_layer=2, lamb=0.005, n_steps=5,
34 | initial='super', **kwargs):
35 | '''
36 | Hyper parameters of model.
37 | Input:
38 | FIXME:
39 | encoder: list of binary
40 | e.g. ['01', '10']
41 | length of encoder must be the same as the number of class
42 | Cp: float (constant value of coefficient
43 | for personal best position)
44 | Cg: float (constant value of coefficient
45 | for grobal best position)
46 | n_particle: int (the number of particles
47 | for searching better parameters)
48 | T: int (the number of iterations of how many times
49 | this model learns)
50 | w: float (constant value of coefficient
51 | for previous particle directions)
52 | ro_max: float (maximum number of random number
53 | which is used for updating parameter)
54 | n_layer: int (the number of layers of mapping circuit)
55 | lamb: float (constant value of coefficient
56 | for the sum of square in error)
57 | n_steps: int (the number of steps of Quantum walk)
58 | '''
59 | if len(encoder[0]) != n_layer:
60 | raise ValueError('The size of encoder is different\
61 | from the number of layers')
62 | self.encoder = encoder
63 | self.Cp = Cp
64 | self.Cg = Cg
65 | self.w = w
66 | self.ro_max = ro_max
67 | # FIXME more efficient
68 | if T < 0:
69 | raise ValueError('The number of iterations must be \
70 | non negative value')
71 | if n_particle < 0:
72 | raise ValueError('The number of particles must be\
73 | non negative value')
74 | if n_layer <= 0:
75 | raise ValueError('The number of layers must be\
76 | one or over')
77 | if n_steps < 0:
78 | raise ValueError('The number of steps must be\
79 | zero or over')
80 | self.T = T
81 | self.n_particle = n_particle
82 | self.layers = n_layer
83 | self.step = n_steps
84 | self.lamb = lamb
85 | self.initial = initial
86 |
87 | def optimize(self, train_data, train_label):
88 | '''
89 | Input:
90 | train_data: 2dim array (a series of training data)
91 | train_label: 2dim array (a series of label, one hot)
92 | Output:
93 | theta: array
94 | coin_param: ?
95 | '''
96 | self.n_class = len(train_label[0])
97 | if self.n_class > 2**self.layers:
98 | raise ValueError('the number of class must be less than 2^layers')
99 |
100 | # initial parameter for Quantum Walk
101 | # each particle has [theta, phi, lambda]
102 | # coin_u3s = np.array([[random.uniform(THETA_MIN, THETA_MAX)
103 | # for i in range(3)]
104 | # for n in range(self.n_particle)])
105 | coin_u3s = np.array([[random.uniform(THETA_MIN, THETA_MAX),
106 | pi/self.step, pi/self.step]
107 | for n in range(self.n_particle)])
108 |
109 | ampdata = [QWfilter(coin_u3s[n], self.step,
110 | self.initial).amplitude(train_data)
111 | for n in range(self.n_particle)]
112 | theta_size = self.ceilog(max(set(map(len, ampdata[0]))))
113 |
114 | # FIXME
115 | n_amp = np.array([[self._zero_fill(amp, 2**theta_size)
116 | for amp in ampdata[n]]
117 | for n in range(self.n_particle)])
118 |
119 | # initialize particles
120 | particles = np.array([[random.uniform(THETA_MIN, THETA_MAX)
121 | for i in range(theta_size)]
122 | for n in range(self.n_particle)])
123 | velocities = np.array([np.zeros(theta_size)
124 | for n in range(self.n_particle)])
125 | coin_v = np.array([np.zeros(3) for n in range(self.n_particle)])
126 |
127 | # for recording best positions of each particle
128 | personal_bpos = copy.copy(particles)
129 | personal_cbpos = copy.copy(coin_u3s)
130 | personal_best_scores = [self._get_cost(amps, train_label, theta)
131 | for amps, theta in zip(n_amp, particles)]
132 |
133 | # recording best position of all particles
134 | best_particle = np.argmin(personal_best_scores)
135 | grobal_best_pos = personal_bpos[best_particle]
136 | grobal_best_coin = coin_u3s[best_particle]
137 |
138 | print('training start!')
139 | # start training
140 | # to check convergence of error, prepare this list
141 | errors = []
142 | accuracy = []
143 | for t in trange(self.T, desc='training'):
144 | ampdata = [QWfilter(coin_u3s[n], self.step,
145 | self.initial).amplitude(train_data)
146 | for n in range(self.n_particle)]
147 | n_amp = np.array([[self._zero_fill(amp, 2**theta_size)
148 | for amp in ampdata[n]]
149 | for n in range(self.n_particle)])
150 | for n in range(self.n_particle):
151 | amp = n_amp[n]
152 | # random number for personal best pos
153 | rnp = random.uniform(0, self.ro_max)
154 | # random number for grobal best
155 | rng = random.uniform(0, self.ro_max)
156 |
157 | # update position
158 | particles[n] = particles[n] + velocities[n]
159 | # update coin pos
160 |
161 | coin_u3s[n] = coin_u3s[n] + coin_v[n]
162 |
163 | velocities[n] = (self.w*velocities[n] +
164 | self.Cp*rnp*(personal_bpos[n]-particles[n]) +
165 | self.Cg*rng*(grobal_best_pos-particles[n]))
166 |
167 | coin_v[n] = (self.w*coin_v[n] +
168 | self.Cp*rnp*(personal_cbpos[n]-coin_u3s[n]) +
169 | self.Cg*rng*(grobal_best_coin-coin_u3s[n]))
170 |
171 | # calculation cost with updated parameters
172 | # and update best position and score
173 | score = self._get_cost(amp, train_label, particles[n])
174 | if score < personal_best_scores[n]:
175 | personal_best_scores[n] = score
176 | personal_bpos[n] = particles[n]
177 | personal_cbpos[n] = coin_u3s[n]
178 |
179 | # in all particles, calculate which is the best particle
180 | # and coin parameters
181 | best_particle = np.argmin(personal_best_scores)
182 | grobal_best_coin = coin_u3s[best_particle]
183 | grobal_best_pos = personal_bpos[best_particle]
184 |
185 | best_amp_data = QWfilter(grobal_best_coin, self.step,
186 | self.initial).amplitude(train_data)
187 | n_best_amp = [self._zero_fill(amp, 2**theta_size)
188 | for amp in best_amp_data]
189 | error = self._get_cost(n_best_amp, train_label, grobal_best_pos)
190 | accs = self._get_accuracy(n_best_amp, train_label,
191 | grobal_best_pos)
192 | errors.append(error)
193 | accuracy.append(accs)
194 | if t % 10 == 0 and notify:
195 | Notify.notify_error(t, error, accs)
196 | convergence = [errors, accuracy]
197 | return grobal_best_pos, grobal_best_coin, convergence
198 |
199 | def _get_cost(self, data, label, theta):
200 | cost = ClassifierCircuit(data, label, theta, self.n_class,
201 | self.layers, self.encoder).cost()
202 |
203 | error = cost + self.lamb*np.sum([i**2 for i in theta])
204 | return error
205 |
206 | def _get_accuracy(self, data, label, theta):
207 | answers = ClassifierCircuit(data, label, theta, self.n_class,
208 | self.layers, self.encoder).answers()
209 | acc = self._accs(answers, label)
210 | return acc
211 |
212 | @staticmethod
213 | def ceilog(x):
214 | return int(np.ceil(np.log2(x)))
215 |
216 | def test(self, test_data, theta, coin_param):
217 | '''
218 | Test function to evaluate the performance
219 | Input:
220 | test_data: 2dim array (a series of test data)
221 | theta: tuned parameters theta
222 | coin_param: optimzed coin parameters
223 | Output:
224 | answers: 2dim array (answers for each data)
225 | '''
226 | theta_size = len(theta)
227 | ampdata = QWfilter(coin_param, self.step,
228 | self.initial).amplitude(test_data)
229 | n_amp = np.array([self._zero_fill(amp, 2**theta_size)
230 | for amp in ampdata])
231 | # TODO Inplement the case that the number of class is unknown
232 | answers = ClassifierCircuit(n_amp, None, theta, 2,
233 | self.layers, self.encoder).answers()
234 | return answers
235 |
236 | def _accs(self, ans, label):
237 | count = 0
238 | for i, j in zip(ans, label):
239 | if np.argmax(i) == np.argmax(j):
240 | count += 1
241 | # print('answer ', [np.argmax(i) for i in ans])
242 | # print('label ', [np.argmax(i) for i in label])
243 | return count/len(label)
244 |
245 | @staticmethod
246 | def _zero_fill(x, base, array=True):
247 |
248 | # FIXME efficiently
249 | xl = list(x)
250 | x_len = len(xl)
251 | if base - x_len < 0:
252 | raise ValueError('Error')
253 | xs = xl + [0 for _ in range(base-x_len)]
254 | if array:
255 | return np.array(xs)
256 | else:
257 | return xs
258 |
259 | def summary(self, answer, label, printer=False):
260 | accs = self._accs(answer, label)
261 | if printer:
262 | print('The accuracy of this model is ', accs)
263 | return accs
264 |
265 |
266 | def one_hot_encoder(label, n_class):
267 | enc_label = [np.zeros(n_class) for _ in label]
268 | for ilb, lb in enumerate(label):
269 | if lb == -1:
270 | enc_label[ilb][0] = 1
271 | else:
272 | enc_label[ilb][lb] = 1
273 | return enc_label
274 |
275 |
276 | if __name__ == '__main__':
277 | # prepare dataset
278 | import toml
279 | # parsing parameters from toml
280 | config = toml.load('experiments.toml')
281 | p_pso = config['pso']
282 | p_qw = config['qw']
283 |
284 | data_name = 'MUTAG'
285 | Data = datasets.fetch_dataset(data_name, verbose=False)
286 | data_x, data_y = np.array(Data.data), np.array(Data.target)
287 |
288 | acclist = []
289 | k = 5
290 | kf = KFold(n_splits=k, shuffle=True)
291 |
292 | qwgc = QWGC(['01', '10'], Cp=p_pso['Cp'], Cg=p_pso['Cg'],
293 | n_particle=p_pso['particles'], T=p_pso['iterations'],
294 | w=p_pso['w'], ro_max=p_pso['random_max'],
295 | n_layer=p_pso['layers'], lamb=p_pso['lambda'],
296 | n_steps=p_qw['steps'], initial=p_qw['initial'])
297 | for train_index, test_index in kf.split(data_x):
298 | # preprocessing for generating data.
299 | x_train, y_train = data_x[train_index], data_y[train_index]
300 | x_test, y_test = data_x[test_index], data_y[test_index]
301 |
302 | # one hot encoding
303 | y_train = one_hot_encoder(y_train, 2)
304 | y_test = one_hot_encoder(y_test, 2)
305 |
306 | theta, coin_param, conv = qwgc.optimize(x_train, y_train)
307 | # test
308 | ans = qwgc.test(x_test, theta, coin_param)
309 | # evaluate
310 | accs = qwgc.summary(ans, y_test)
311 |
312 | acclist.append(accs)
313 | print(accs)
314 | if notify:
315 | Notify.notify_accs(accs, conv)
316 | print('acclist', acclist)
317 | print('mean', np.mean(acclist))
318 |
--------------------------------------------------------------------------------
/qwgc/QW_kernel.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import random
3 | import matplotlib.pyplot as plt
4 |
5 | from numpy import pi
6 | from tqdm import tqdm, trange
7 | from sklearn.model_selection import KFold
8 | from grakel import datasets
9 | from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
10 | from qiskit import Aer, execute
11 | from sklearn import svm
12 |
13 | from preprocess.qwfilter import QWfilter
14 |
15 | try:
16 | from utils.notification import Notify
17 | notify = True
18 | except Exception:
19 | notify = False
20 |
21 | step = 3
22 | THETA_MIN, THETA_MAX = -pi, pi
23 | iteration = 200
24 | backend = Aer.get_backend('qasm_simulator')
25 | shots = 1024
26 |
27 | '''
28 | This is just very prototype code
29 | '''
30 |
31 |
32 | def qw_kernel(train_data, train_label, lam=2):
33 | '''
34 | Input:
35 | train_data: 2dim array (a series of training data)
36 | train_label: 2dim array (a series of label, one hot)
37 | Output:
38 | theta: array
39 | coin_param: ?
40 | '''
41 | ld = len(train_data)
42 | # start training
43 | # to check convergence of error, prepare this list
44 | weights = np.zeros(ld)
45 | print('training start!')
46 | for i in trange(iteration):
47 | it = random.randint(0, ld-1)
48 | decision = 0
49 | for j in range(it):
50 | # FIXME ambiguous error message
51 | try:
52 | decision += weights[j] * train_label[it] * _kernel_function(train_data[it], train_data[j], 7)
53 | except ValueError:
54 | continue
55 | decision *= train_label[it]/lam
56 | if decision < 1:
57 | weights[it] += 1
58 | return weights
59 |
60 |
61 | def test(x_train, y_train, x_test, y_test, weights):
62 | print('test start!')
63 | errors = 0
64 | for ila, lb_test in tqdm(enumerate(y_test)):
65 | decision = 0
66 | for ilb, lb_train in enumerate(y_train):
67 | decision += weights[ilb]*y_train[ilb]*_kernel_function(x_train[ilb], x_test[ila], 7)
68 | if decision < 0:
69 | prediction = -1
70 | else:
71 | prediction = 1
72 | if prediction != y_test[ila]:
73 | errors += 1
74 | return 1 - errors/len(y_test)
75 |
76 |
77 | def _kernel_function(x, y, qsize):
78 | # definition of coin
79 | coin_u3s = np.array([pi, 0, pi/2])
80 |
81 | ampdata_x = QWfilter(coin_u3s, step, 'super').single_amplitude(x)
82 | x_amp = _zero_fill(ampdata_x, 2**qsize)
83 |
84 | q1 = QuantumRegister(qsize)
85 | qc1 = QuantumCircuit(q1, name='QW1')
86 | qc1.initialize(x_amp, q1)
87 | qw1 = qc1.to_instruction()
88 |
89 | ampdata_y = QWfilter(coin_u3s, step, 'super').single_amplitude(y)
90 | y_amp = _zero_fill(ampdata_y, 2**qsize)
91 |
92 | q2 = QuantumRegister(qsize)
93 | qc2 = QuantumCircuit(q2)
94 | qc2.initialize(y_amp, q2)
95 | qw2 = qc2.to_instruction()
96 |
97 | kq = QuantumRegister(qsize)
98 | c = ClassicalRegister(qsize)
99 | kqc = QuantumCircuit(kq, c)
100 | kqc.append(qw1, qargs=kq)
101 | kqc.append(qw2, qargs=kq)
102 | kqc.measure(kq, c)
103 | # calc prob '000...0'
104 | job = execute(kqc, backend=backend, shots=shots)
105 | count = job.result().get_counts(kqc)
106 | return count.get('0'*qsize, 0)/shots
107 |
108 |
109 | def ceilog(x):
110 | return int(np.ceil(np.log2(x)))
111 |
112 |
113 | def _zero_fill(x, base, array=True):
114 | # FIXME efficiently
115 | xl = list(x)
116 | x_len = len(xl)
117 | if base - x_len < 0:
118 | raise ValueError('Error')
119 | xs = xl + [0 for _ in range(base-x_len)]
120 | if array:
121 | return np.array(xs)
122 | else:
123 | return xs
124 |
125 |
126 | if __name__ == '__main__':
127 | data_name = 'MUTAG'
128 | Data = datasets.fetch_dataset(data_name, verbose=False)
129 | data_x, data_y = np.array(Data.data), np.array(Data.target)
130 |
131 | k = 5
132 | kf = KFold(n_splits=k, shuffle=True)
133 | accuracy = []
134 | for train_index, test_index in kf.split(data_x):
135 | # preprocessing for generating data.
136 | x_train, y_train = data_x[train_index], data_y[train_index]
137 | x_test, y_test = data_x[test_index], data_y[test_index]
138 | weight = qw_kernel(x_train, y_train)
139 | accs = test(x_train, y_train, x_test, y_test, weight)
140 | print(accs)
141 | if notify:
142 | Notify.notify_accs(accs, 'svm')
143 | accuracy.append(accs)
144 | Notify.notify_accs(accuracy, 'K5 result')
145 | Notify.notify_accs(np.mean(accuracy), 'K5 result mean')
146 | print(accuracy)
147 | print(np.mean(accuracy))
148 |
--------------------------------------------------------------------------------
/qwgc/__init__.py:
--------------------------------------------------------------------------------
1 | from .QWGC import QWGC
2 |
--------------------------------------------------------------------------------
/qwgc/classifier/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/qwqmlf/qwgc/d06c805023bf37a1252505f7dc6e30461d861440/qwgc/classifier/__init__.py
--------------------------------------------------------------------------------
/qwgc/classifier/costfunc.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/qwqmlf/qwgc/d06c805023bf37a1252505f7dc6e30461d861440/qwgc/classifier/costfunc.py
--------------------------------------------------------------------------------
/qwgc/classifier/qcircuit.py:
--------------------------------------------------------------------------------
1 | from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
2 | from qiskit import Aer, execute
3 | from scipy.special import softmax
4 |
5 | from utils.notification import Notify
6 | import numpy as np
7 | from numpy import pi
8 |
9 | QASM = Aer.get_backend('qasm_simulator')
10 |
11 |
12 | class ClassifierCircuit:
13 | '''
14 | This class is the core part of this algorithm.
15 | FIXME inherit QWGC and take super constructor.
16 | '''
17 |
18 | def __init__(self, data, label, theta, n_class,
19 | layers, encoder, shots=1024):
20 | '''
21 | Input:
22 | encoding: list (discribe the correspondence of
23 | measurement basis and label)
24 | e.g. ['01', '10']
25 | '''
26 | self.data = data
27 | if label is None:
28 | # FIXME this is for test
29 | self.label = 0
30 | else:
31 | if len(label[0]) != len(encoder):
32 | raise ValueError('dimension of label and \
33 | encoder must be the same')
34 | self.label = label
35 | # FIXME
36 | self.n_class = n_class
37 | self.theta = theta
38 | self.qsize = len(theta)
39 | self.layers = layers
40 | self.encoder = encoder
41 | self.shots = shots
42 | if layers > self.qsize:
43 | raise Warning('The length of theta is shorter \
44 | than the number of layers')
45 |
46 | def _circuit_constructor(self, visualize=False, notify=False):
47 | '''
48 | returning circuits
49 | TODO
50 | if visualize got the list of integers,
51 | then, print out the circuit of certain index
52 | '''
53 | qcs = []
54 | nq = self.qsize
55 | layer = self.layers
56 | if notify:
57 | Notify.notify_accs(list(self.data[0]), list(self.data[-1]))
58 | for index, d in enumerate(self.data):
59 | # qubits for representing data
60 | qr = QuantumRegister(nq)
61 | # qubits for mapping data
62 | mp = QuantumRegister(layer)
63 | c = ClassicalRegister(layer)
64 | qc = QuantumCircuit(qr, mp, c, name='data%d' % index)
65 | qc.initialize(d, qr)
66 | # qc.h(qr)
67 | qc = self._map(qc, qr, mp)
68 | qc.measure(mp, c)
69 | qcs.append(qc)
70 | return qcs
71 |
72 | def _map(self, qc, qr, mp):
73 | # counter = 0
74 | for ith, theta in enumerate(self.theta):
75 | # if ith % self.layers == 0:
76 | qc.cry(theta, qr[ith], mp[ith % self.layers])
77 | # else:
78 | # qc.h(mp[ith%self.layers])
79 | # qc.cu3(theta, pi/2, pi/2, qr[ith], mp[ith % self.layers])
80 | # qc.h(mp[ith%self.layers])
81 | return qc
82 |
83 | def cost(self, notify=False):
84 | '''
85 | This function is the interface to pass through
86 | the result of measurement
87 | Input:
88 | data: amplitude vector
89 | Output:
90 | result of measurement
91 | '''
92 | qcs = self._circuit_constructor(notify=notify)
93 | probs = self._get_result(qcs, notify=notify)
94 | cross = np.mean([self._cross_entropy_error(pb, lb)
95 | for pb, lb in zip(probs, self.label)])
96 | return cross
97 |
98 | def answers(self):
99 | qcs = self._circuit_constructor()
100 | probs = self._get_result(qcs)
101 | answers = [np.zeros(self.n_class) for _ in probs]
102 | for ipb, pb in enumerate(probs):
103 | ind = np.argmax(pb)
104 | answers[ipb][ind] = 1
105 | return answers
106 |
107 | def _get_result(self, qcs, notify=False):
108 | '''
109 | returning probabilities of estimation
110 | '''
111 | job = execute(qcs, backend=QASM, shots=self.shots)
112 | counts = [job.result().get_counts(qc) for qc in qcs]
113 | dinom = [sum([cs.get(i, 0) for i in self.encoder]) for cs in counts]
114 | if notify:
115 | bins = [format(i, "02b") for i in range(4)]
116 | Notify.notify_accs("After Classify data0", [counts[0].get(b, 0)/sum(counts[0].values()) for b in bins])
117 | Notify.notify_accs("After Classify data last", [counts[-1].get(b, 0)/sum(counts[-1].values()) for b in bins])
118 | enc_probs = [np.array([cs.get(i, 0)/(din+1e-10) for i in self.encoder])
119 | for cs, din in zip(counts, dinom)]
120 | return enc_probs
121 |
122 | @staticmethod
123 | def ceilog(x):
124 | return int(np.ceil(np.log2(x)))
125 |
126 | @staticmethod
127 | def _cross_entropy_error(y, t, delta=1e-7):
128 | return -np.sum(t * np.log(y + delta))
129 |
--------------------------------------------------------------------------------
/qwgc/experiments.toml:
--------------------------------------------------------------------------------
1 | title = 'Hypter parameters of qwgc'
2 |
3 | [pso]
4 | Cp = 1.4
5 | Cg = 1.1
6 | particles = 10
7 | iterations = 200
8 | w = 0.7
9 | random_max = 1.2
10 | layers = 6
11 | lambda = 0.0005
12 |
13 | [qw]
14 | steps = 5
15 | initial = 'super'
16 |
--------------------------------------------------------------------------------
/qwgc/preprocess/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/qwqmlf/qwgc/d06c805023bf37a1252505f7dc6e30461d861440/qwgc/preprocess/__init__.py
--------------------------------------------------------------------------------
/qwgc/preprocess/gparse.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 |
3 |
4 | class GraphInfo:
5 | def __init__(self, adjacency_matrix):
6 | self.adja = adjacency_matrix
7 | self.dim = len(adjacency_matrix)
8 |
9 | def shift(self):
10 | deg = self._degrees
11 | node_index = self._first_node()
12 | ndim = self.dim
13 | size = node_index[ndim-1] + len(deg[ndim-1])
14 | deg2 = [[0] for _ in deg]
15 | for i, v in enumerate(deg):
16 | deg2[i] = list(set(v))
17 | array = np.zeros((size, size), dtype=int)
18 | for i, val in enumerate(deg):
19 | index1 = node_index[i]
20 | n = 0
21 | for j, jval in enumerate(deg2[i]):
22 | nolinks = self.adja[jval][i]
23 | n = self._coinst(i, val[j])
24 | coinst = index1 + n
25 | node = val[j]
26 | for k in deg2[node]:
27 | if k == i:
28 | coinst2 = node_index[node] + self._coinst(node, i)
29 | for k in range(int(nolinks)):
30 | array[coinst+k][coinst2+k] = 1
31 | # FIXME catch before
32 | for i, v in enumerate(array):
33 | for j, w in enumerate(array):
34 | if array[i][j] == 1:
35 | array[j][i] = 1
36 | return array
37 |
38 | @property
39 | def _degrees(self):
40 | degrees = [[] for _ in range(self.dim)]
41 | for iv, v in enumerate(self.adja):
42 | for ix, x in enumerate(v):
43 | if x == 1:
44 | degrees[iv].append(ix)
45 | return degrees
46 |
47 | def _first_node(self):
48 | n = 0
49 | array = np.zeros(len(self._degrees), dtype=int)
50 | for i, v in enumerate(self._degrees):
51 | array[i] = n
52 | n += len(v)
53 | return array
54 |
55 | def _coinst(self, i, j):
56 | n1 = 0
57 | n2 = 0
58 | idim = len(self._degrees[i])
59 | for k in range(idim):
60 | if n2 == 0:
61 | if self._degrees[i][k] != j:
62 | n1 += 1
63 | else:
64 | n2 = 1
65 | if n1 == idim:
66 | return 'no link'
67 | else:
68 | return n1
69 |
--------------------------------------------------------------------------------
/qwgc/preprocess/qwalk.py:
--------------------------------------------------------------------------------
1 | '''
2 | Thank you Barr Katie for providing your code.
3 | I reffered this paper and code.
4 | Barr, Katie, Toby Fleming, and Viv Kendon.
5 | "Simulation methods for quantum walks on
6 | graphs applied to perfect state transfer and
7 | formal language recognition." CoSMoS 2013 (2013): 1.
8 | '''
9 | import numpy as np
10 | import numpy.linalg as la
11 | from .gparse import GraphInfo
12 |
13 |
14 | class QuantumWalk:
15 |
16 | def __init__(self, initial_state, coin_operator, adjacency_matrix,
17 | tolerance=1e-5):
18 | '''
19 | initial_state: None or array like
20 | coin_operator: array like
21 | adjacency_matrix: array like
22 | '''
23 | gf = GraphInfo(adjacency_matrix)
24 | if not is_unitary(coin_operator):
25 | raise ValueError('Coin operator must be unitary')
26 | else:
27 | self.coin_operator = coin_operator
28 | self.shift_operator = gf.shift()
29 | self.time_ev = np.dot(self.shift_operator, coin_operator)
30 | eigs, _ = la.eig(self.time_ev)
31 | if initial_state is None:
32 | self.create_default_initial()
33 | else:
34 | self.initial_state = initial_state
35 | self.current_state = initial_state
36 | self.adjacency = adjacency_matrix
37 | self.dim = len(adjacency_matrix)
38 | self.tolerance = tolerance
39 |
40 | def create_default_initial(self):
41 | basis_state = self.time_ev.shape[0]
42 | vec = np.zeros((basis_state))
43 | vec[0] = 1
44 | self.initial_state = vec
45 |
46 | def step(self):
47 | self.current_state = np.dot(self.time_ev, self.current_state)
48 |
49 | def step_back(self):
50 | self.current_state = np.dot(np.concatenate(self.time_ev.transpose()),
51 | self.current_state)
52 |
53 | def steps(self, n):
54 | for i in range(n):
55 | state = np.dot(self.time_ev, self.current_state)
56 | self.current_state = state
57 |
58 | @property
59 | def node_deg(self):
60 | return [int(np.sum(self.adjacency[i])) for i in range(self.dim)]
61 |
62 | def prob_at_node(self, index):
63 | if index > self.dim:
64 | raise ValueError('Graph does not have %d nodes' % index)
65 | probs = self.calc_probs
66 | return probs[index]
67 |
68 | def calc_probs(self):
69 | probs = np.zeros(self.dim)
70 | ind = 0
71 | for i in range(self.dim):
72 | for j in range(self.node_deg[i]):
73 | amps_at_j = self.current_state[ind]
74 | probs[i] += amps_at_j * np.conjugate(amps_at_j)
75 | ind += 1
76 | assert np.isclose(np.sum(probs), 1, atol=self.tolerance)
77 | return probs
78 |
79 | def calc_amp(self):
80 | # FIXME in this implementation, we can't get amplitudes of each node
81 | return self.current_state
82 |
83 | def n_steps(self, steps):
84 | if steps < 0:
85 | raise ValueError('steps must be 0 or over')
86 | elif steps == 0:
87 | self.current_state = self.initial_state
88 | return self.current_state
89 |
90 | eig = la.eig(self.time_ev)[1]
91 | inverse = la.inv(eig)
92 | diag = np.dot(np.dot(inverse, self.time_ev), eig)
93 |
94 | for i, _ in enumerate(diag):
95 | transition = diag[i][i]
96 | x = transition.real
97 | y = transition.imag
98 | theta = np.arctan2(y, x)
99 | diag[i][i] = np.cos(steps*theta) + complex(0, np.sin(steps*theta))
100 | transform_bvec = np.dot(inverse, self.initial_state)
101 | evolved = np.dot(diag, transform_bvec)
102 | trans_back = np.dot(eig, evolved)
103 | self.current_state = trans_back
104 | return trans_back
105 |
106 |
107 | def is_unitary(operator):
108 | h, w = operator.shape
109 | if not h == w:
110 | return False
111 | adjoint = np.conjugate(operator.transpose())
112 | product1 = np.dot(operator, adjoint)
113 | product2 = np.dot(adjoint, operator)
114 | ida = np.eye(h)
115 | return np.allclose(product1, ida) & np.allclose(product2, ida)
116 |
--------------------------------------------------------------------------------
/qwgc/preprocess/qwfilter.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import random
3 | import copy
4 | import itertools
5 |
6 | from grakel import Graph
7 | from .qwalk import QuantumWalk
8 |
9 | np.set_printoptions(linewidth=100000)
10 |
11 |
12 | class QWfilter:
13 | def __init__(self, u3param, step, initial):
14 | self.u3p = u3param
15 | self.step = step
16 | self.initial = initial
17 |
18 | def amplitude(self, data, normalize=False):
19 | '''
20 | interface
21 | Output:
22 | amplitude (no normalize)
23 | '''
24 | adjacency = [Graph(d[0]).get_adjacency_matrix() for d in data]
25 | amplitude = []
26 | for ad in adjacency:
27 | amp = self.coin_walk(ad)
28 | # amp = self.szegedy_google(ad)
29 | amplitude.append(amp)
30 | return amplitude
31 |
32 | def coin_walk(self, ad):
33 | count = np.count_nonzero(ad)//2
34 | nad = len(ad)
35 | # prepare coin with u3 parameter
36 | coin = self._compose_coins(count, ad)
37 | # prepare initial state
38 | initial_state = self._initial(count, nad)
39 |
40 | # construct quantum walk and go n steps
41 | qwalk = QuantumWalk(initial_state, coin, ad)
42 | qwalk.n_steps(self.step)
43 | amplitude = qwalk.calc_amp()
44 | # print(list(amplitude))
45 | return amplitude
46 |
47 | def szegedy_google(self, adjacency):
48 | """
49 | quantum pagerank
50 | """
51 | G = google_matrix(adjacency)
52 | initial = 1/2*np.array([np.sqrt(G[j][i])
53 | for i, _ in enumerate(G)
54 | for j, _ in enumerate(G)])
55 | print(sum([abs(i)**2 for i in initial]))
56 | Pi_op = self._Pi_operator(G)
57 | print(is_unitary(Pi_op))
58 | swap = self._swap_operator(len(G))
59 | print(is_unitary(swap))
60 | operator = (2*Pi_op) - np.identity(len(Pi_op))
61 | Szegedy = np.dot(operator, swap)
62 | Szegedy_n = copy.deepcopy(Szegedy)
63 | if self.step == 0:
64 | return initial
65 | elif self.step == 1:
66 | amp = np.dot(Szegedy, self.initial)
67 | return amp
68 | else:
69 | for n in range(self.step-1):
70 | Szegedy_n = np.dot(Szegedy_n, Szegedy)
71 | amp = np.dot(Szegedy_n, initial)
72 | return amp
73 |
74 | def _Pi_operator(self, ptran):
75 | '''
76 | This is not a quantum operation,
77 | just returning matrix
78 | '''
79 | lg = len(ptran)
80 | psi_op = []
81 | count = 0
82 | for i in range(lg):
83 | psi_vec = [0 for _ in range(lg**2)]
84 | for j in range(lg):
85 | psi_vec[count] = np.sqrt(ptran[j][i])
86 | count += 1
87 | psi_op.append(np.kron(np.array(psi_vec).T,
88 | np.conjugate(psi_vec)).reshape((lg**2, lg**2)))
89 | Pi = psi_op[0]
90 | for i in psi_op[1:]:
91 | Pi = np.add(Pi, i)
92 | return Pi
93 |
94 | def _swap_operator(self, lad):
95 | # find closest 2 pow
96 | base = int(np.ceil(np.log2((1 << int(np.ceil(np.log2(lad)))))))
97 | swap = np.zeros((lad**2, lad**2))
98 | for i in range(lad):
99 | # ibin = format(i, '0%db' % base)
100 | for j in range(lad):
101 | # jbin = format(j, '0%db' % base)
102 | # a = int(ibin + jbin, 2)
103 | # b = int(jbin + ibin, 2)
104 | ai = np.array([1 if t == i else 0 for t in range(lad)])
105 | bi = np.conjugate(np.array([1 if k == j else 0 for k in range(lad)]).T)
106 | swap += np.kron(ai, bi)
107 | # raise Exception("")
108 | return swap
109 |
110 | def _reform(self, ad):
111 | for il, ln in enumerate(ad):
112 | rd = random.choice([i for i, _ in enumerate(ln) if i != il])
113 | if sum(ln) == 1:
114 | ad[il][rd] = 1
115 | return ad
116 |
117 | def single_amplitude(self, d):
118 | ad = Graph(d[0]).get_adjacency_matrix()
119 | count = np.count_nonzero(ad)//2
120 | nad = len(ad)
121 |
122 | # prepare coin with u3 parameter
123 | coin = self._compose_coins(count, ad)
124 | # prepare initial state
125 | initial_state = self._initial(count, nad)
126 |
127 | # construct quantum walk and go n steps
128 | qwalk = QuantumWalk(initial_state, coin, ad)
129 | qwalk.n_steps(self.step)
130 | amplitude = qwalk.calc_amp()
131 | return amplitude
132 |
133 | def single_prob(self, d):
134 | ad = Graph(d[0]).get_adjacency_matrix()
135 | count = np.count_nonzero(ad)//2
136 | nad = len(ad)
137 |
138 | # prepare coin with u3 parameter
139 | coin = self._compose_coins(count, ad)
140 | # prepare initial state
141 | initial_state = self._initial(count, nad)
142 |
143 | # construct quantum walk and go n steps
144 | qwalk = QuantumWalk(initial_state, coin, ad)
145 | qwalk.n_steps(self.step)
146 | probability = qwalk.calc_probs()
147 | return probability
148 |
149 | def _compose_coins(self, count, adja):
150 | '''
151 | Input:
152 | count: the number of non-zero elements in adjacency matrix
153 | adja: adjacency matrix of data
154 | pahse: FIXME default True
155 | useing quantum coin with phase
156 | Output:
157 | coin: 2d matrix (unitary)
158 | '''
159 | co = []
160 | elcoin = []
161 | coin = np.array(np.diag(np.zeros(count*2)), dtype=np.complex)
162 | for lad in adja:
163 | s = int(sum(lad))
164 | co.append(s)
165 | section = [0] + list(itertools.accumulate(co))[0:-1]
166 | for c in co:
167 | coin_element = self._coin(c)
168 | for ce in coin_element:
169 | elcoin.append(ce)
170 | counter = 0
171 | for ic, coinel in enumerate(zip(coin, elcoin)):
172 | ci, ce = coinel[0], coinel[1]
173 | nce = len(ce)
174 | ci[counter:counter+nce] = ce
175 | if ic+1 in section:
176 | counter = ic+1
177 | if not is_unitary(coin):
178 | raise Exception('coin operator must be unitary')
179 | return coin
180 |
181 | def _coin(self, num):
182 | if num == 2:
183 | # testing if this is good enough to make good amp or not
184 | coin = self.U3(self.u3p[0], self.u3p[1], self.u3p[2])
185 | else:
186 | coin = np.array([[2/num for k in range(num)]
187 | for i in range(num)] - np.identity(num))
188 |
189 | if not is_unitary(coin):
190 | raise Exception("elementary operator must be unitary.")
191 | return coin
192 |
193 | def _initial(self, count, nad):
194 | if self.initial is None:
195 | initial_state = None
196 | elif isinstance(self.initial, list or np.ndarray):
197 | initial_state = self.initial
198 | else:
199 | initial_state = [1/np.sqrt(nad) for i in range(nad)] + \
200 | [0 for i in range(2*count-nad)]
201 | # FIXME check threshold
202 | assert(np.sum(i**2 for i in initial_state)-1 < 1e-5)
203 | return initial_state
204 |
205 | @staticmethod
206 | def U3(theta, phi, lamb):
207 | return np.array([[np.cos(theta/2),
208 | -np.exp(1j*lamb)*np.sin(theta/2)],
209 | [np.exp(1j*phi)*np.sin(theta/2),
210 | np.exp(1j*lamb+1j*phi)*np.cos(theta/2)]])
211 |
212 |
213 | def is_unitary(operator, tolerance=0.0001):
214 | h, w = operator.shape
215 | if not h == w:
216 | return False
217 | adjoint = np.conjugate(operator.transpose())
218 | product1 = np.dot(operator, adjoint)
219 | product2 = np.dot(adjoint, operator)
220 | ida = np.eye(h)
221 | return np.allclose(product1, ida) & np.allclose(product2, ida)
222 |
223 |
224 | def prob_transition(graph, gtype='google'):
225 | if gtype == 'google':
226 | return google_matrix(graph)
227 | else:
228 | pmatrix = np.zeros(graph.shape)
229 | indegrees = np.sum(graph, axis=0)
230 | for ix, indeg in enumerate(indegrees):
231 | if indeg == 0:
232 | pmatrix[:, ix] = graph[:, ix]
233 | else:
234 | pmatrix[:, ix] = graph[:, ix]/indeg
235 | return pmatrix
236 |
237 |
238 | def google_matrix(graph, alpha=0.85):
239 | E = np.zeros((len(graph), len(graph)))
240 | for i, t in enumerate(graph):
241 | if sum(graph[:, i]) == 0:
242 | E[:, i] = np.array([1/len(graph) for _ in graph])
243 | else:
244 | for ij, j in enumerate(t):
245 | E[ij, i] = j/sum(graph[:, i])
246 | G = alpha*E + (1-alpha)/(len(graph)) * np.ones((len(graph), len(graph)))
247 | return G
248 |
--------------------------------------------------------------------------------
/qwgc/utils/.gitignore:
--------------------------------------------------------------------------------
1 | notification.py
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | #
2 | # These requirements were autogenerated by pipenv
3 | # To regenerate from the project's Pipfile, run:
4 | #
5 | # pipenv lock --requirements
6 | #
7 |
8 | -i https://pypi.org/simple/
9 | attrs==21.2.0; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4'
10 | autopep8==1.5.4
11 | cached-property==1.5.2; python_version < '3.8'
12 | certifi==2021.5.30
13 | cffi==1.14.6
14 | charset-normalizer==2.0.4; python_version >= '3'
15 | cryptography==3.3.2
16 | cycler==0.10.0
17 | cython==0.29.24; python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3'
18 | dill==0.3.4; python_version >= '2.7' and python_version != '3.0'
19 | dlx==1.0.4
20 | docplex==2.21.207
21 | fastdtw==0.3.4
22 | fastjsonschema==2.15.1
23 | future==0.18.2; python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3'
24 | grakel-dev==0.1a6
25 | grakel==0.1b7
26 | h5py==3.4.0; python_version >= '3.7'
27 | idna==3.2; python_version >= '3'
28 | importlib-metadata==4.8.1; python_version < '3.8'
29 | inflection==0.5.1; python_version >= '3.5'
30 | joblib==1.0.1; python_version >= '3.6'
31 | jsonschema==3.2.0
32 | kiwisolver==1.3.2; python_version >= '3.7'
33 | llvmlite==0.37.0; python_version < '3.10' and python_version >= '3.7'
34 | lxml==4.6.3; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4'
35 | matplotlib==3.4.3; python_version >= '3.7'
36 | more-itertools==8.9.0; python_version >= '3.5'
37 | mpmath==1.2.1
38 | multitasking==0.0.9
39 | nest-asyncio==1.5.1; python_version >= '3.5'
40 | networkx==2.6.2; python_version >= '3.7'
41 | nose==1.3.7
42 | ntlm-auth==1.5.0; python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3'
43 | numba==0.54.0; python_version < '3.10' and python_version >= '3.7'
44 | numpy==1.20.3; python_version == '3.7'
45 | pandas==1.3.2; python_full_version >= '3.7.1'
46 | pillow==8.3.2; python_version >= '3.6'
47 | ply==3.11
48 | psutil==5.8.0; python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3'
49 | pybind11==2.7.1; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4'
50 | pycodestyle==2.7.0; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'
51 | pycparser==2.20; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'
52 | pyparsing==2.4.7; python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3'
53 | pyrsistent==0.18.0; python_version >= '3.6'
54 | python-constraint==1.4.0
55 | python-dateutil==2.8.2; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'
56 | pytz==2021.1
57 | qiskit-aer==0.7.0; python_version >= '3.6'
58 | qiskit-aqua==0.8.0; python_version >= '3.6'
59 | qiskit-ibmq-provider==0.11.0; python_version >= '3.6'
60 | qiskit-ignis==0.5.0; python_version >= '3.6'
61 | qiskit-terra==0.16.0; python_version >= '3.6'
62 | qiskit==0.23.0
63 | quandl==3.6.1; python_version >= '3.5'
64 | requests-ntlm==1.1.0
65 | requests==2.26.0; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4, 3.5'
66 | retworkx==0.10.1; python_version >= '3.6'
67 | scikit-learn==0.24.2; python_version >= '3.6'
68 | scipy==1.7.1; python_version < '3.10' and python_version >= '3.7'
69 | seaborn==0.11.0
70 | six==1.16.0; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'
71 | slackweb==1.0.5
72 | sympy==1.8; python_version >= '3.6'
73 | threadpoolctl==2.2.0; python_version >= '3.6'
74 | toml==0.10.2
75 | tqdm==4.51.0
76 | typing-extensions==3.10.0.2; python_version < '3.8'
77 | umap-learn==0.4.6
78 | urllib3==1.26.6; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4' and python_version < '4'
79 | websockets==9.1; python_full_version >= '3.6.1'
80 | yfinance==0.1.63
81 | zipp==3.5.0; python_version >= '3.6'
82 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | from setuptools import setup
2 |
3 | with open('requirements.txt', 'r') as f:
4 | requirements = [line.strip() for line in f]
5 |
6 | discription = "qwgc is a quantum walk graph classifier \
7 | for classification for Graph data."
8 | setup(
9 | name="qwgc",
10 | version="0.0.3",
11 | description="Graph classifier based on quantum walk",
12 | long_description=discription,
13 | url="https://Chibikuri.github.io/qwgc",
14 | author="Ryosuke Satoh",
15 | author_email="ryosuke.satoh.wk@gmail.com",
16 | license="Apache 2.0",
17 | classifiers=[
18 | "License :: OSI Approved :: Apache Software License",
19 | "Operating System :: MacOS",
20 | "Operating System :: POSIX :: Linux",
21 | "Programming Language :: Python :: 3.6",
22 | "Programming Language :: Python :: 3.7",
23 | ],
24 | keywords="quantum walk machine learning",
25 | install_requires=requirements,
26 | include_package_data=True,
27 | python_requires=">=3.5",
28 | )
29 |
--------------------------------------------------------------------------------
/test/test_QWGC.py:
--------------------------------------------------------------------------------
1 | import pytest
2 |
--------------------------------------------------------------------------------