QGAN_EN.ipynb 38.3 KB
Newer Older
Q
Quleaf 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Quantum Generative Adversarial Network"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<em> Copyright (c) 2021 Institute for Quantum Computing, Baidu Inc. All Rights Reserved. </em>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Classical Generative Adversarial Network"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Introduction to Generative Adversarial Network"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Generative Adversarial Network (GAN) is a generative model, which is a breakthrough in deep learning in recent years [1]. It contains two parts: the generator $G$ and the discriminator $D$. The generator accepts a random noise signal and uses it as input to generate the data we expect. The discriminator evaluates the received data $x$ and outputs a probability $P(x)$ that the data $x$ is real."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Nash Equilibrium"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here we use the idea of Nash equilibrium to discuss the convergence problem of GAN.\n",
    "\n",
    "Nash equilibrium refers to a non-cooperative game involving two or more participants, assuming that each participant knows other participants' equilibrium strategies. No participant can change one's strategy to benefit. In the game theory, if each participant chooses his strategy, and no player can benefit by changing the strategy while other participants remain the same, then the current set of strategy choices and their corresponding results constitute Nash Equilibrium.\n",
    "\n",
    "We can regard the training process of GAN as a game process between generator and discriminator. No matter what the generator's strategy is, the best strategy of the discriminator is to try to distinguish the real data and the generated data. And regardless of the strategy of the discriminator, the best strategy for the generator is to make the discriminator unable to distinguish. This game is a zero-sum game, which is one of non-cooperative game. That is, one party gains while the other party must lose. Therefore, there exists the Nash equilibrium strategy in the game between the generator and the discriminator. When there are enough samples of real data and the learning ability of both parties is strong enough, a Nash equilibrium point will eventually be reached. **The generator has the ability to generate real data, and the discriminator can no longer distinguish between generated data and real data.** \n",
    "\n",
    "GAN adopts the idea of Nash equilibrium. In GAN, the generator and the discriminator are playing a non-cooperative game. No matter what strategies the generator adopts, the best strategy of the discriminator is to discriminate as much as possible; and no matter what strategies the discriminator adopts, the best strategy of the generator is to make the discriminator unable to discriminate as much as possible. Therefore, the two parties' strategic combination in the game and the corresponding results constitute the Nash equilibrium. **When the Nash equilibrium is reached, the generator can to generate real data, and the discriminator cannot distinguish between the generated data and the real data**."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Optimization goal"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In GAN, we want to get an excellent generator (but only an excellent discriminator can accurately determine whether the generator is excellent). Our training's ideal result is that the discriminator cannot identify whether the data comes from real data or generated data.\n",
    "\n",
    "Therefore, our objective function is as follows:\n",
    "\n",
    "$$\n",
    "\\min_{G}\\max_{D} V(G,D)= \\min_{G}\\max_{D}\\mathbb{E}_{x\\sim P_{data}}[\\log D(x)] +\\mathbb{E}_{z\\sim P_{z}}[\\log(1-D(G(z)))]. \\tag{1}\n",
    "$$\n",
    "\n",
    "Here, $G$ represents the parameters of the generator and $D$ represents the parameters of the discriminator. In the actual process, the alternate training method is usually adopted; that is, first fix $G$, train $D$, then fix $D$, train $G$, and repeat. When the two's performance is sufficient, the model will converge, and the two will reach the Nash equilibrium."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Advantages"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- Compared with other generative models, GAN generates better results.\n",
    "- Theoretically, as long as it is a differentiable function, it can be used to build generators and discriminators, so it can be combined with deep neural networks to make deep generative models.\n",
    "- Compared with other generative models, GAN does not rely on prior assumptions, and we do not need to assume the probability distribution and law of the data in advance.\n",
    "- The form of data generated by GAN is also very simple, just forward propagation through the generator."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Disadvantages"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- GAN does not require pre-modeling. Too much freedom makes training difficult to converge and unstable.\n",
    "- GAN has a vanishing gradient problem. In this case, there is no loss in the training of the discriminator, so there is no adequate gradient information to pass back to the generator to optimize itself.\n",
    "- There may be a problem of model collapse in the learning process of GAN. The generator degenerates, always generating the same sample points, and cannot continue learning. The discriminator also points to similar sample points in similar directions, and the model parameters are no longer updated, but the actual effect is feeble."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Quantum Generative Adversarial Network"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The quantum generative adversarial network is similar to the classical one, except that it is no longer used to generate classical data but generate quantum states [2-3]. In practice, if we have a quantum state, it will collapse to a certain eigenstate after observation and cannot be restored to the previous quantum state. Therefore, if we have a method that generates many identical (or similar) quantum states based on the existing target quantum state, it will be very convenient for our experiments.\n",
    "\n",
    "Assuming that our existing target quantum states all come from a mixed state, they belong to the same ensemble, and their density operator is $\\rho$. Then we need to have a generator $G$ whose input is noise data, denoted by the ensemble $\\rho_{z}=\\sum_{i}p_{i}|z_{i}\\rangle\\langle z_ {i}|$. Therefore, we take out a random noise sample $|z_{i}\\rangle$ every time and get the generated quantum state $|x\\rangle=G|z_{i}\\rangle$ after passing through the generator. We expect the generated $| x\\rangle$ that is close to the target quantum state $\\rho$.\n",
    "\n",
    "It is worth noting that for the ensemble of the target state and the ensemble of the noise data mentioned above, we think that there exists a physical device that can generate a quantum state from the ensemble. According to quantum physics, We can get a genuinely random quantum state every time. However, in computer programs, we need to simulate this process.\n",
    "\n",
    "We expect the discriminator to judge whether the quantum state we input is an existing target state or a generated quantum state. This process needs to be given by measurement.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## A simple example"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem Description"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For simplicity, we assume that the existing target quantum state is a pure state, and the input state for the generator is $|0\\rangle$.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The circuit to prepare the existing target quantum state:\n",
    "![QGAN-fig-target_state](figures/QGAN-fig-target_state.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The circuit of the generator is:\n",
    "![QGAN-fig-generator](figures/QGAN-fig-generator.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The circuit of the discriminator is:\n",
    "![QGAN-fig-discriminator](figures/QGAN-fig-discriminator.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "By measuring the quantum state output by the discriminator, we can get the probability of judging the target state as the target state $P_{T}$ and the probability of judging the generated state as the target state $P_{G}$."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Specific process"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Assuming that the existing target quantum state is $|\\psi\\rangle$, the quantum state generated by the generator is $|x\\rangle=G|00\\rangle$ (the generator uses a two-qubit circuit, of which the 0th qubit is a generated quantum state).\n",
    "\n",
    "The discriminator discriminates the data and obtains the quantum state $|\\phi\\rangle$ when the input is the target state, $|\\phi\\rangle=D(|\\psi\\rangle\\otimes |00\\rangle)$; When the input is generated state, $|\\phi\\rangle=D(G\\otimes I)|000\\rangle$.\n",
    "\n",
    "For the quantum state obtained by the discriminator, we also need to use the Pauli Z gate to measure the third qubit so as to obtain the judgment result of the input quantum state by the discriminator (that is, the probability that the discriminator thinks the input is the target state). First there is $M_{z}=I\\otimes I\\otimes\\sigma_{z}$, and the measurement result is $\\text{disc_output}=\\langle\\phi|M_{z}|\\phi\\rangle$, so the probability of the measurement that the result is the target state is $P=(\\text{disc_output}+1)/2$.\n",
    "\n",
Q
Quleaf 已提交
202
    "We define the loss function of the discriminator as $\\mathcal{L}_{D}=P_{G}(\\text{gen_theta}, \\text{disc_phi})-P_{T}(\\text{disc_phi})$, The loss function of the generator is $\\mathcal{L}_{G}=-P_{G}(\\text{gen_theta}, \\text{disc_phi})$. Here, $P_{G}$ and $P_{T}$ are the expressions of $P=(\\text{disc_output}+1)/2$, when the input quantum state is the generated state and the target state, respectively. gen\\_theta and disc\\_phi are the parameters of the generator and discriminator circuits.\n",
Q
Quleaf 已提交
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
    "\n",
    "So we only need to optimize the objective function $\\min_{\\text{disc_phi}}\\mathcal{L}_{D}$ and $\\min_{\\text{gen_theta}}\\mathcal{L}_{G}$ respectively. The discriminator and generator can be alternately trained."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Paddle Quantum Implementation"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "First import the relevant packages."
   ]
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
223
   "execution_count": 2,
Q
Quleaf 已提交
224 225 226 227 228 229 230 231 232
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-01-09T10:49:41.308412Z",
     "start_time": "2021-01-09T10:49:38.115680Z"
    }
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
Q
Quleaf 已提交
233 234
    "import scipy\n",
    "import warnings\n",
Q
Quleaf 已提交
235
    "import paddle\n",
Q
Quleaf 已提交
236 237 238 239 240 241 242 243 244
    "import paddle_quantum\n",
    "from paddle_quantum.state import zero_state\n",
    "from paddle_quantum.ansatz import Circuit\n",
    "from paddle_quantum import Hamiltonian\n",
    "from paddle_quantum.loss import ExpecVal\n",
    "from paddle_quantum.qinfo import partial_trace\n",
    "from tqdm import tqdm\n",
    "\n",
    "warnings.filterwarnings(\"ignore\")"
Q
Quleaf 已提交
245 246 247 248 249 250 251 252 253 254 255
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Then define our network model QGAN."
   ]
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
256
   "execution_count": 3,
Q
Quleaf 已提交
257 258 259 260 261 262 263 264
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-01-09T10:49:43.091496Z",
     "start_time": "2021-01-09T10:49:43.060879Z"
    }
   },
   "outputs": [],
   "source": [
Q
Quleaf 已提交
265 266
    "# set the backend to density_matrix\n",
    "paddle_quantum.set_backend('density_matrix')\n",
Q
Quleaf 已提交
267 268
    "\n",
    "\n",
Q
Quleaf 已提交
269 270 271 272
    "class QGAN(paddle_quantum.gate.Gate):\n",
    "    def __init__(self, target_state):\n",
    "        super().__init__()\n",
    "        self.target_state = target_state.clone()\n",
Q
Quleaf 已提交
273
    "\n",
Q
Quleaf 已提交
274 275 276 277 278
    "        # Quantum circuit of generator\n",
    "        self.generator = Circuit(3)\n",
    "        self.generator.u3([0, 1])\n",
    "        self.generator.cnot([0, 1])\n",
    "        self.generator.u3(0)\n",
Q
Quleaf 已提交
279
    "\n",
Q
Quleaf 已提交
280 281 282 283 284
    "        # Quantum circuit of the discriminator\n",
    "        self.discriminator = Circuit(3)\n",
    "        self.discriminator.u3([0, 2])\n",
    "        self.discriminator.cnot([0, 2])\n",
    "        self.discriminator.u3(0)\n",
Q
Quleaf 已提交
285 286
    "\n",
    "    def disc_target_as_target(self):\n",
Q
Quleaf 已提交
287 288 289
    "        \"\"\"\n",
    "        The probability that the discriminator judges the target state as the target state\n",
    "        \"\"\"\n",
Q
Quleaf 已提交
290 291 292
    "        state = self.discriminator(self.target_state)\n",
    "        expec_val_func = ExpecVal(Hamiltonian([[1.0, 'z2']]))\n",
    "        \n",
Q
Quleaf 已提交
293
    "        # The judgment result of the discriminator on the target state\n",
Q
Quleaf 已提交
294
    "        target_disc_output = expec_val_func(state)\n",
Q
Quleaf 已提交
295 296 297
    "        prob_as_target = (target_disc_output + 1) / 2\n",
    "\n",
    "        return prob_as_target\n",
Q
Quleaf 已提交
298 299
    "\n",
    "    def disc_gen_as_target(self):\n",
Q
Quleaf 已提交
300 301 302 303
    "        \"\"\"\n",
    "        The probability that the discriminator judges the generated state as the target state\n",
    "        \"\"\"\n",
    "        # Get the quantum state generated by the generator\n",
Q
Quleaf 已提交
304 305 306
    "        gen_state = self.generator()\n",
    "\n",
    "        state = self.discriminator(gen_state)\n",
Q
Quleaf 已提交
307
    "        # The judgment result of the discriminator on the generated state\n",
Q
Quleaf 已提交
308 309
    "        expec_val_func = ExpecVal(Hamiltonian([[1.0, 'z2']]))\n",
    "        gen_disc_output = expec_val_func(state)\n",
Q
Quleaf 已提交
310 311 312
    "        prob_as_target = (gen_disc_output + 1) / 2\n",
    "\n",
    "        return prob_as_target\n",
Q
Quleaf 已提交
313 314
    "\n",
    "    def forward(self, model_name):\n",
Q
Quleaf 已提交
315 316 317
    "        if model_name == 'gen':\n",
    "        # Calculate the loss function of the generator, the interval of the loss value is [-1, 0],\n",
    "        # 0 means extremely poor generation effect, -1 means excellent generation effect\n",
Q
Quleaf 已提交
318 319
    "            loss = -1 * self.disc_gen_as_target()\n",
    "        else:\n",
Q
Quleaf 已提交
320 321 322
    "        # Calculate the loss function of the discriminator, the loss value range is [-1, 1],\n",
    "        # -1 means perfect distinction, 0 means indistinguishable, 1 means inverted distinction\n",
    "            loss = self.disc_gen_as_target() - self.disc_target_as_target()\n",
Q
Quleaf 已提交
323
    "            loss = self.disc_gen_as_target() - self.disc_target_as_target()\n",
Q
Quleaf 已提交
324
    "\n",
Q
Quleaf 已提交
325
    "        return loss\n",
Q
Quleaf 已提交
326 327
    "\n",
    "    def get_target_state(self):\n",
Q
Quleaf 已提交
328 329 330
    "        \"\"\"\n",
    "        Get the density matrix representation of the target state\n",
    "        \"\"\"\n",
Q
Quleaf 已提交
331
    "        state = partial_trace(self.target_state, 2, 4, 2)\n",
Q
Quleaf 已提交
332
    "\n",
Q
Quleaf 已提交
333
    "        return state.numpy()\n",
Q
Quleaf 已提交
334 335
    "\n",
    "    def get_generated_state(self):\n",
Q
Quleaf 已提交
336 337 338
    "        \"\"\"\n",
    "        Get the density matrix representation of the generated state\n",
    "        \"\"\"\n",
Q
Quleaf 已提交
339 340
    "        state = self.generator()\n",
    "        state = partial_trace(state, 2, 4, 2)\n",
Q
Quleaf 已提交
341
    "\n",
Q
Quleaf 已提交
342
    "        return state.numpy()"
Q
Quleaf 已提交
343 344 345 346 347 348
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Q
Quleaf 已提交
349
    "Next, we use PaddlePaddle to train our model."
Q
Quleaf 已提交
350 351 352 353
   ]
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
354
   "execution_count": 4,
Q
Quleaf 已提交
355 356 357 358 359 360 361 362 363 364 365
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-01-09T10:52:15.221809Z",
     "start_time": "2021-01-09T10:49:55.308722Z"
    }
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
Q
Quleaf 已提交
366
      "Training: 100%|#################################################| 2250/2250 [00:57<00:00, 39.44it/s]\n"
Q
Quleaf 已提交
367 368 369 370 371 372 373
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "the density matrix of the target state:\n",
Q
Quleaf 已提交
374 375
      "[[0.02447175+0.j         0.12500004-0.09081785j]\n",
      " [0.12500004+0.09081785j 0.97552836+0.j        ]] \n",
Q
Quleaf 已提交
376 377
      "\n",
      "the density matrix of the generated state:\n",
Q
Quleaf 已提交
378 379
      "[[0.02444258+3.7252903e-09j 0.12302095-9.3332648e-02j]\n",
      " [0.12302095+9.3332678e-02j 0.97555757-7.4505806e-09j]] \n",
Q
Quleaf 已提交
380
      "\n",
Q
Quleaf 已提交
381
      "the distance between these two quantum states is 2.0483967e-05 \n",
Q
Quleaf 已提交
382
      "\n",
Q
Quleaf 已提交
383
      "the fidelity between these two quantum states is 0.9999947358758301\n"
Q
Quleaf 已提交
384 385 386 387 388 389 390
     ]
    }
   ],
   "source": [
    "# Learning rate\n",
    "LR = 0.1\n",
    "# Total number of iterations\n",
Q
Quleaf 已提交
391
    "ITR = 25\n",
Q
Quleaf 已提交
392
    "# In each iteration, the number of iterations of the discriminator\n",
Q
Quleaf 已提交
393
    "ITR1 = 40\n",
Q
Quleaf 已提交
394 395 396
    "# In each iteration, the number of generator iterations\n",
    "ITR2 = 50\n",
    "\n",
Q
Quleaf 已提交
397 398 399 400 401 402
    "# prepare the target quantum state\n",
    "target_state = zero_state(num_qubits=3)\n",
    "target_state = paddle_quantum.gate.RY(0, param=0.9 * np.pi)(target_state)\n",
    "target_state = paddle_quantum.gate.RZ(0, param=0.2 * np.pi)(target_state)\n",
    "target_state.data = paddle.to_tensor(target_state.data.numpy())\n",
    "\n",
Q
Quleaf 已提交
403 404
    "# Used to record the change of loss value\n",
    "loss_history = list()\n",
Q
Quleaf 已提交
405
    "paddle.seed(18)\n",
Q
Quleaf 已提交
406
    "gan_demo = QGAN(target_state)\n",
Q
Quleaf 已提交
407 408 409 410 411 412 413 414 415 416 417 418
    "optimizer = paddle.optimizer.SGD(learning_rate=LR, parameters=gan_demo.parameters())\n",
    "pbar = tqdm(desc=\"Training: \", total=ITR * (ITR1 + ITR2), ncols=100, ascii=True)\n",
    "for itr0 in range(ITR):\n",
    "\n",
    "    # Record the change in the loss value of the discriminator\n",
    "    loss_disc_history = list()\n",
    "\n",
    "    # Train the discriminator\n",
    "    for itr1 in range(ITR1):\n",
    "        pbar.update(1)\n",
    "        loss_disc = gan_demo('disc')\n",
    "        loss_disc.backward()\n",
Q
Quleaf 已提交
419 420 421 422
    "        optimizer.minimize(\n",
    "            loss_disc, parameters=gan_demo.discriminator.parameters(),\n",
    "            no_grad_set=gan_demo.generator.parameters()\n",
    "        )\n",
Q
Quleaf 已提交
423 424 425 426 427 428 429 430 431 432 433
    "        gan_demo.clear_gradients()\n",
    "        loss_disc_history.append(loss_disc.numpy()[0])\n",
    "\n",
    "    # Record the change of the generator loss value\n",
    "    loss_gen_history = list()\n",
    "\n",
    "    # Training generator\n",
    "    for itr2 in range(ITR2):\n",
    "        pbar.update(1)\n",
    "        loss_gen = gan_demo('gen')\n",
    "        loss_gen.backward()\n",
Q
Quleaf 已提交
434 435 436 437
    "        optimizer.minimize(\n",
    "            loss_gen, parameters=gan_demo.generator.parameters(),\n",
    "            no_grad_set=gan_demo.discriminator.parameters()\n",
    "        )\n",
Q
Quleaf 已提交
438 439 440
    "        optimizer.clear_grad()\n",
    "        loss_gen_history.append(loss_gen.numpy()[0])\n",
    "\n",
Q
Quleaf 已提交
441
    "\n",
Q
Quleaf 已提交
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
    "    loss_history.append((loss_disc_history, loss_gen_history))\n",
    "pbar.close()\n",
    "\n",
    "# Get the target quantum state\n",
    "target_state = gan_demo.get_target_state()\n",
    "\n",
    "# Get the final quantum state generated by the generator\n",
    "gen_state = gan_demo.get_generated_state()\n",
    "print(\"the density matrix of the target state:\")\n",
    "print(target_state, \"\\n\")\n",
    "print(\"the density matrix of the generated state:\")\n",
    "print(gen_state, \"\\n\")\n",
    "\n",
    "# Calculate the distance between two quantum states,\n",
    "# The distance here is defined as tr[(target_state-gen_state)^2]\n",
Q
Quleaf 已提交
457
    "distance = np.trace(np.matmul(target_state-gen_state, target_state-gen_state)).real\n",
Q
Quleaf 已提交
458
    "# Calculate the fidelity of two quantum states\n",
Q
Quleaf 已提交
459 460 461
    "fidelity = np.trace(\n",
    "    scipy.linalg.sqrtm(scipy.linalg.sqrtm(target_state) @ gen_state @ scipy.linalg.sqrtm(gen_state))\n",
    ").real\n",
Q
Quleaf 已提交
462 463
    "print(\"the distance between these two quantum states is\", distance, \"\\n\")\n",
    "print(\"the fidelity between these two quantum states is\", fidelity)"
Q
Quleaf 已提交
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We compare the target quantum state's density matrix $\\rho_\\text{target}$ and  the generated quantum state's density matrix $\\rho_\\text{gen}$ and calculate the distance between them $\\text{tr}[(\\rho_\\text{target}-\\rho_\\text{gen})^2]$ and fidelity. We can know that our generator generates a quantum state very close to the target state."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Visualization of the training process"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, let's observe the change of the discriminator and generator's loss curve during the training process.\n",
    "\n",
    "First install the required packages."
   ]
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
491
   "execution_count": 5,
Q
Quleaf 已提交
492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
   "metadata": {},
   "outputs": [],
   "source": [
    "from IPython.display import clear_output\n",
    "!pip install celluloid\n",
    "clear_output()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, we draw the change of the loss curve."
   ]
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
509
   "execution_count": 6,
Q
Quleaf 已提交
510 511 512 513
   "metadata": {},
   "outputs": [
    {
     "data": {
Q
Quleaf 已提交
514
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAZgAAAEXCAYAAACQ3VJYAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/YYfK9AAAACXBIW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CcYMzMrhBOMmZkVwgnGzMwK8f8BH2SB/lgvSbwAAAAASUVORK5CYII=",
Q
Quleaf 已提交
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
      "text/plain": [
       "<Figure size 432x288 with 2 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "from celluloid import Camera\n",
    "def draw_pic(loss_history):\n",
    "    fig, axes = plt.subplots(nrows=1, ncols=2)\n",
    "    camera = Camera(fig)\n",
    "    axes[0].set_title(\"discriminator\")\n",
    "    axes[0].set_xlabel(\"disc_iter\")\n",
    "    axes[0].set_ylabel(\"disc_loss\")\n",
    "    axes[0].set_xlim(0, 20)\n",
    "    axes[0].set_ylim(-1, 1)\n",
    "    axes[1].set_title(\"generator\")\n",
    "    axes[1].set_xlabel(\"gen_iter\")\n",
    "    axes[1].set_ylabel(\"gen_loss\")\n",
    "    axes[1].set_xlim(0, 50)\n",
    "    axes[1].set_ylim(-1, 0)\n",
    "    for loss in loss_history:\n",
    "        disc_data, gen_data = loss\n",
    "        disc_x_data = range(0, len(disc_data))\n",
    "        gen_x_data = range(0, len(gen_data))\n",
    "        axes[0].plot(disc_x_data, disc_data, color='red')\n",
    "        axes[1].plot(gen_x_data, gen_data, color='blue')\n",
    "        camera.snap()\n",
    "    animation = camera.animate(interval=600, \n",
    "                               repeat=True, repeat_delay=800)\n",
    "    animation.save(\"./figures/loss.gif\")\n",
    "draw_pic(loss_history)\n",
    "clear_output()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![QGAN-fig-loss](./figures/loss.gif)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this dynamic picture, each frame represents an iterative process. In an iteration, the red line on the left represents the loss curve of the discriminator, and the blue line on the right represents the loss curve of the generator. It can be seen that at the initial stage, the discriminator and generator can gradually learn from a poor discriminant ability and generation ability to a better discrimination ability and generation ability in the current situation. As the learning progresses, the generator’s generation ability is getting stronger and stronger, and the discriminator’s ability is getting stronger and stronger. However, the discriminator can not distinguish the real data and the generated data because the generator has generated data close to real data. At this time, the model has converged."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Q
Quleaf 已提交
573 574
    "_______\n",
    "\n",
Q
Quleaf 已提交
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
    "## References"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[1] Goodfellow, I. J. et al. Generative Adversarial Nets. [Proc. 27th Int. Conf. Neural Inf. Process. Syst. (2014).](https://papers.nips.cc/paper/5423-generative-adversarial-nets)\n",
    "\n",
    "[2] Lloyd, S. & Weedbrook, C. Quantum Generative Adversarial Learning. [Phys. Rev. Lett. 121, 040502 (2018).](https://journals.aps.org/prl/abstract/10.1103/PhysRevLett.121.040502)\n",
    "\n",
    "[3] Benedetti, M., Grant, E., Wossnig, L. & Severini, S. Adversarial quantum circuit learning for pure state approximation. [New J. Phys. 21, (2019).](https://iopscience.iop.org/article/10.1088/1367-2630/ab14b5)\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
Q
Quleaf 已提交
606
   "version": "3.8.0"
Q
Quleaf 已提交
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": true
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}