<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Blueqat (blueqat Inc. / former MDR Inc.) - Medium]]></title>
        <description><![CDATA[Open Source Quantum Computing SDK - Medium]]></description>
        <link>https://medium.com/mdr-inc?source=rss----8d311f05b2c5---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Blueqat (blueqat Inc. / former MDR Inc.) - Medium</title>
            <link>https://medium.com/mdr-inc?source=rss----8d311f05b2c5---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 15:05:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/mdr-inc" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Portfolio Optimization with minimum risk using QAOA]]></title>
            <link>https://medium.com/mdr-inc/portfolio-optimization-with-minimum-risk-using-qaoa-e29e1d66c194?source=rss----8d311f05b2c5---4</link>
            <guid isPermaLink="false">https://medium.com/p/e29e1d66c194</guid>
            <category><![CDATA[monte-carlo]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[quantum-computing]]></category>
            <category><![CDATA[variance]]></category>
            <dc:creator><![CDATA[Gaurav Singh]]></dc:creator>
            <pubDate>Wed, 15 Jul 2020 19:10:51 GMT</pubDate>
            <atom:updated>2020-07-15T19:11:57.134Z</atom:updated>
            <content:encoded><![CDATA[<p>We will look into optimization of portfolio for some stocks which is one of the optimization problems in finance. While creating a stocks portfolio it can get really confusing on which stocks to include and which ones to exclude or how to weigh the different stocks. <strong>We can select the portfolio with maximum return for a given risk or a portfolio with minimum risk for a given return or we can simply select the portfolio with maximum Sharpe ratio.</strong></p><p>A safe bet is to invest in stocks which are least volatile or in statistics language we can say have the least variance. Thus in order to keep a minimum risk portfolio we try to keep it’s variance to the least. Here we will discuss on how to optimize a stocks profile with minimum risk or minimum variance using gate model of Quantum Computation. Here we won’t be looking into returns and will just concentrate on a profile with minimum risk.</p><p>For n number of stocks, we can have 2^n number of portfolios. Selecting the best combination of stocks becomes a NP-Hard problem. The conventional brute force technique would take exponential time to get the optimal solution. Some of the classical algorithms for this optimization are : Brute Force, Genetic Algorithms, Random Sampling, Monte Carlo Simulation (Simulated Annealing).</p><h4>Covariance Matrix :</h4><p>The <strong>covariance matrix</strong> is used to calculate the standard deviation of a portfolio of stocks which in turn is used by portfolio managers to quantify the risk associated with a particular portfolio. Here covariance is a measure of joint variability of two random variables i.e if both the variables move in the same direction, the covariance comes out to be positive otherwise it comes out to be negative. For us to calculate the variance of the portfolio, we need to find the covariance matrix of the stocks. Let say we have the information of the closing price of k stocks for n number of days. We can tabulate a <strong>n x k </strong>matrix giving us information of the stock activity for the number of days.</p><ul><li>Let’s fetch the value of some stocks using pandas_datareader library and put it into a pandas dataframe.</li></ul><pre>import pandas as pd<br>import numpy as np<br>import pandas_datareader.data as web</pre><pre>data = web.DataReader([&#39;BAC&#39;, &#39;GS&#39;, &#39;JPM&#39;, &#39;MS&#39;],data_source=&quot;yahoo&quot;,start=&#39;12/01/2017&#39;,end=&#39;12/31/2017&#39;)[&#39;Adj Close&#39;]<br>data.round(2) # Round the data upto two decimal places</pre><p>We fetch the data of 4 stocks ‘BAC’, ‘GS’, ‘JPM’, ‘MS’ :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*3CInOMd6Eh1E_M9hZz_8NA.png" /></figure><ul><li>Next, we find the covariance matrix out of the above table. For understanding on how to calculate the covariance matrix please refer to : <a href="https://blog.quantinsti.com/calculating-covariance-matrix-portfolio-variance/">Link</a>. We use the cov() function here to get the desired matrix.</li></ul><pre>cov_matrix=data.cov()<br>cov_matrix.round(2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*9sLt7BRjqnvg_sbOdDUOWw.png" /></figure><p>Here we see that the diagonal elements are the variance for the respective stocks and the non diagonal elements are covariance between the (i,j) stocks.</p><p><strong>The variance of the portfolio is given by : (W(Transpose) * Covariance_Mat * W).</strong></p><p>Here W is the weight of the stocks where the sum of all the weights sum upto 1. We are looking for a problem where we either include a stock or not or a binary solution for the weights, thus for our problem the W vector is a binary vector where 1 denotes a stock being selected and 0 denotes it being excluded. With <strong>W vector</strong> being a binary vector we can convert the above portfolio variance to the form of :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*sofI7e_IAmh4qkguB7e40Q.png" /></figure><p>which can easily be written in QUBO format where the diagonal terms of the above covariance matrix represent the linear terms while the non diagonal terms represent the quadratic terms.</p><p>The QUBO for the above covariance matrix comes out to be :</p><p><strong>0.24x₁ + 18.33x₂ + 0.98x₃ + 0.24x₄ + 2*1.65x₁x₂ + 2*0.45x₁x₃ + 2*0.12x₁x₄ + 2*3.15x₂x₃ + 2*1.49x₂x₄ + 2*0.24x₃x₄.</strong></p><p>We can convert it into Ising hamiltonian format using z = 2x-1, where z is the ising spin (-1,+1) and x is the above binary variable.</p><p>Thus the objective Hamiltonian of the portfolio optimization problem comes out of the Ising hamiltonian format where the spins are replaced by Pauli Z operators. For a detailed view on how to solve a QAOA problem of the form of Ising Hamiltonian , refer to this link: <a href="https://docs.google.com/presentation/d/1zlJEzA3OZPmoGQc0agmwxdnVWQJB96kWEw0A-mqTfIE/edit?usp=sharing"><strong>QAOA for problems in linear algebra</strong></a>.</p><p>Finally we get a solution in the form of above binary vector with those stocks included which reduce the overall variance of the portfolio. The expected return out of this portfolio comes out to be : <strong>W * M</strong>, where W is the binary solution vector and M is the vector with the mean price of the stocks for the n days. This optimization technique only considers the risk. In the next article we will look into the <strong>sharpe ratio</strong> which is used to help investors understand the return of an investment compared to its risk (keeping both the return and the risk in mind) a better measure for portfolio optimization. From here we will look into the <strong>CQR(Chicago Quantum Ratio) </strong>which is an improvement over the sharpe ratio.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*0ovji7rt3JQYo9ILXEsNOw.png" /><figcaption><a href="https://medium.com/engineer-quant/optimal-portfolios-why-and-how-be0cdcf16485">Image Link</a></figcaption></figure><h4>References :</h4><ul><li><a href="https://blog.quantinsti.com/calculating-covariance-matrix-portfolio-variance/">https://blog.quantinsti.com/calculating-covariance-matrix-portfolio-variance/</a></li><li><a href="https://arxiv.org/pdf/2007.01430.pdf">https://arxiv.org/pdf/2007.01430.pdf</a></li><li><a href="https://docs.google.com/presentation/d/1zlJEzA3OZPmoGQc0agmwxdnVWQJB96kWEw0A-mqTfIE/edit?usp=sharing">QAOA for problems in linear algebra</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e29e1d66c194" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mdr-inc/portfolio-optimization-with-minimum-risk-using-qaoa-e29e1d66c194">Portfolio Optimization with minimum risk using QAOA</a> was originally published in <a href="https://medium.com/mdr-inc">Blueqat (blueqat Inc. / former MDR Inc.)</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[review : reading the paper on QAOA combinatorial optimization algorithm on Google’s sycamore…]]></title>
            <link>https://medium.com/mdr-inc/review-reading-the-paper-on-qaoa-combinatorial-optimization-algorithm-on-googles-sycamore-b3e4b214e78d?source=rss----8d311f05b2c5---4</link>
            <guid isPermaLink="false">https://medium.com/p/b3e4b214e78d</guid>
            <category><![CDATA[quantum-computing]]></category>
            <category><![CDATA[sycamore]]></category>
            <category><![CDATA[quantum-computer]]></category>
            <dc:creator><![CDATA[Yuichiro Minato]]></dc:creator>
            <pubDate>Wed, 01 Jul 2020 07:57:07 GMT</pubDate>
            <atom:updated>2020-07-01T08:12:44.851Z</atom:updated>
            <content:encoded><![CDATA[<h3>review : reading the paper on QAOA combinatorial optimization algorithm on Google’s sycamore processor.</h3><p>Google published a paper on quantum computing on April.</p><p>https://arxiv.org/pdf/2004.04197.pdf</p><p>Quantum Approximate Optimization of Non-Planar Graph Problems on a Planar Superconducting Processor</p><p>Google AI Quantum and Collaborators∗ (Dated: April 10, 2020)</p><p>This paper shows the result of experiment on actual quantum computer with combinatorial optimization problem.</p><h3>QAOA</h3><p>Quantum Approximate optimization algorithm is an algorithm for NISQ quantum computer. NISQ is a shor name of Noisy Intermediate Scale Quantum, which has errors and small number of qubits. QAOA is optimized the quantum circuit to work on these kind of near term devices.</p><h3>Quantum Annealing</h3><p>Quantum annealing is an algorithm to simulate the annealing process with quantum effect. Basically we use quantum adiabatic process and prepare two hamiltonians. One is the hamiltonian to solve as cost function and another is the driver/mixer to define how to search the answer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*lP4dDY508dYXjJzZLY_S8g@2x.jpeg" /></figure><p>Quantum annealing is using transverse field ising model and using X for the initial hamiltonian on each qubit.</p><p>The initial state corresponding to the initial hamiltonian X is |+&gt; state and this is first prepared with H gate or rotation gate on the quantum circuit.</p><h3>Eigenvalue and Variational principle</h3><p>To solve combinatorial optimization, the quantum circuit solve the eigenvalue problem with provided cost hamiltonian H.</p><p>And to solve this with numerical optimization, the variational principle applied on the expectation value of H. The variational principle shows the minimum lower limit of the expectation value of hamiltonian H as the eigenvalue E0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*vO7tNPizxNR1s0sjhoT0dw@2x.jpeg" /></figure><h3>NISQ hybrid algorithm</h3><p>NISQ has a lot of error and not possible to get a good result from a long quantum circuit.</p><p>The process is first we do a calc on quantum circuit and get the result from probability distribution. and then get the expectation value of hamiltonian.</p><p>And the optimize it. Because the minimum limit of expectation value is defined by the variational principle we can get closer value to the minimum state. Usually gradient descent algorithm is used to optimize the value of expectation value.</p><h3>NISQ and Hermitian matrix</h3><p>The cost function of hamiltonian is written in Hermitian matrix. Usually to solve the problem, trotter decomposition is used. But this decomposition need a long depth of quantum circuit to run. For NISQ variational algorithm, short circuit is used.</p><p>The Hermitian matrix will be decomposed into a sum of Unitary matrix. And each unitary matrix of hamiltonian of expectation value is acquired independently from the trial of quantum circuit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*bBtGyHy5ywJf2nFGSedyIA@2x.jpeg" /></figure><h3>Time evolution operator</h3><p>To do quantum adiabatic process on quantum circuit, we use time evolution. This operator changing the quantum state according to the hamiltonian.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*f1AMKZkCKzbifVWI05Rwfg@2x.jpeg" /></figure><p>This time the hamiltonian is written in X and ZZ form. Hamiltonian will be converted into the form of rotation gate by the diagonalization.</p><p>The diagonalization will be done with converting the hamiltonian with some rotation gate and finally converted into the arbitrary rotation gate with angles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*smweIfU3xtGPNzTK3ccR1A@2x.jpeg" /></figure><p>Finally the angle is defined as the time, but this time we use variational method and not using the exact time evolution. The angle will be a simple parameter to be adjusted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/1*qPSjfI7KVLrYJzyTvWL1GQ@2x.jpeg" /></figure><p>We just use simply theta for the angle.</p><h3>Ansatz</h3><p>We cannot solve every problem on eigenvalue problem efficiently. Only some sort of problem like chemistry or adiabatic calc can be solved. Because we need Ansatz which is an efficient quantum circuit to find the answer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*QDyIkFim6ChEWgp2dMRg-w@2x.jpeg" /></figure><p>QAOA ansatz is written with cost function (pink) and driver/mixer hamiltonian (blue RX).</p><p>H gate is corresponding to RX operator which makes |+&gt; state as the eigenstate or X hamiltonian.</p><h3>Let’s look at the Google’s paper</h3><p>The Google’s paper is very well written. We can easily understand the process and the result.</p><h3>The model</h3><p>On the paper 3models are shown.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*7qU0V4aYrwVdRP-GtZPJZw@2x.jpeg" /></figure><p>from: https://arxiv.org/pdf/2004.04197.pdf</p><p>The first one is the actual ladder shape of sycamore processor. 2D graph based shape.</p><p>The second one is 3-regular maxcut and it has maximum 3 connection to the neighbor nodes.</p><p>The last one is SK model of full connection.</p><p>The last figure d shows the ansatz. |+&gt; is prepared and blue is the cost function part and red is the X hamiltonian part of transverse-field. “p” is the step of the adiabatic process to simulate the quantum annealing.</p><p>The adiabatic process is analogue, besides QAOA is a digital step. And we need to discritize the step. “p” is the number of digitized step. Generally if the p is bigger the result will be better.</p><h3>The cost hamiltonian</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*RYxZ2DNRqt1HbNOir4pCkA@2x.jpeg" /></figure><p>from: https://arxiv.org/pdf/2004.04197.pdf</p><p>The cost is written with ZZ which each expectation value is +1 or -1. w is weight and takes -1 or +1.</p><h3>The time evolution / parameterized hamiltonian</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*CNRPBYhFHKupuJOp8s6_Hg@2x.jpeg" /></figure><p>from: https://arxiv.org/pdf/2004.04197.pdf</p><p>The time evolution of hamiltonian C is like above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*67qQMpLBhIGpoSUS4PHb0w@2x.jpeg" /></figure><p>from: https://arxiv.org/pdf/2004.04197.pdf</p><p>And the driver hamiltonian X is also written in the form of time evolution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*wcWcVci2NDw364gsOJmGLg@2x.jpeg" /></figure><p>from: https://arxiv.org/pdf/2004.04197.pdf</p><p>Finally QAOA will be done start from eigen state of initial hamiltonian X and then apply parameterized adiabatic process.</p><h3>The network connection</h3><p>The hardware qubit location is 2D grid. But for each combinatorial optimization problem they need much more connection. Google’s sycamore processor, they are doing a technique using swap network and combining a new gate set of SYC with arbitrary 1qubit rotation. This set realize the swap and time evolution of ZZ at the same time. And finally realize a full connection of network using swap.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*2q9sNegtiXMrkzee4bLy_Q@2x.jpeg" /></figure><p>from: https://arxiv.org/pdf/2004.04197.pdf</p><p>SYC gate is also called fsim gate and combination of iswap dagger and controlled phase gate.</p><h3>Optimization process using gradient descent</h3><p>The paper also shows the process to optimize the process of variational hybrid algorithm.</p><p>The blue star shows the local/global minimum. And we can see the calculation process start from red square to the final state of red point finally going the minimum state.</p><p>from: https://arxiv.org/pdf/2004.04197.pdf</p><h3>The result</h3><p>The result is very simple.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*OPKimjQeG2pgPIhEQbYhOA@2x.jpeg" /></figure><p>from: https://arxiv.org/pdf/2004.04197.pdf</p><p>The result on the paper is very simple. The square is the ideal simulation without noise. The SK model with full connection is going to random with 17qubits. Hardware grid is not bad. It is doing a similar scale out as the simulation.</p><p>It is showing what we can do with actual machine. We can learn a lot of things from this paper.</p><p>Let’s enjoy quantum life!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3e4b214e78d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mdr-inc/review-reading-the-paper-on-qaoa-combinatorial-optimization-algorithm-on-googles-sycamore-b3e4b214e78d">review : reading the paper on QAOA combinatorial optimization algorithm on Google’s sycamore…</a> was originally published in <a href="https://medium.com/mdr-inc">Blueqat (blueqat Inc. / former MDR Inc.)</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Looking at Paddle Quantum, a quantum computation included in deep learning framework.]]></title>
            <link>https://medium.com/mdr-inc/looking-at-paddle-quantum-a-quantum-computation-included-in-deep-learning-framework-ef2917392611?source=rss----8d311f05b2c5---4</link>
            <guid isPermaLink="false">https://medium.com/p/ef2917392611</guid>
            <category><![CDATA[paddle-quantum]]></category>
            <category><![CDATA[quantum-computer]]></category>
            <dc:creator><![CDATA[Yuichiro Minato]]></dc:creator>
            <pubDate>Wed, 03 Jun 2020 02:40:28 GMT</pubDate>
            <atom:updated>2020-06-03T02:40:28.271Z</atom:updated>
            <content:encoded><![CDATA[<p>Baidu announced that they publish paddle quantum in paddle paddle deep learning framework. Let’s take a brief look at this framework.</p><p><a href="https://github.com/PaddlePaddle/Quantum">PaddlePaddle/Quantum</a></p><h4>NISQ variational algorithm + deep learning optimization</h4><p>Basically existing quantum computer is working on hybrid system with classical computer.</p><p>First you do quantum circuit to get expectation value of state vector behind the calculation and get the expectation value from the measurement and optimize it to get lower value of expectation.</p><p>On this process the quantum circuit contains a lot of variational parameters as angles and deep learning tensor calculation is very similar to that.</p><p>So the deep learning framework is used to simulate the quantum circuit and get the expectation value and optimize it with optimizer like sgd/adam.</p><h4>QAOA on Paddle Quantum</h4><p>It looks that the tutorials contains basic tutorial on VQE and QAOA.</p><p><a href="https://github.com/PaddlePaddle/Quantum/blob/master/tutorial/QAOA_En.ipynb">PaddlePaddle/Quantum</a></p><p>Looking at this QAOA example. It is solving max-cut problem with paddle quantum as QAOA.</p><p>Making the network structure with networkx and convert it to the Z hamiltonian.</p><p>Also using X mixer as mixer and convert both X mixer and Cost hamiltonian with ZZ into time evolution operator.</p><p>Finally using Adam to optimize angle parameters and get the least expectation value as variational algorithm.</p><h4>Similar concept as tensorflow quantum</h4><p>The basic concept is similar to the one of tensorflow quantum. The tutorials are very basic things. As these deep learning framework published quantum hybrid calc, many users will start working on quantum hybrid system and soon go to machine learning and achieve something new, I think.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef2917392611" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mdr-inc/looking-at-paddle-quantum-a-quantum-computation-included-in-deep-learning-framework-ef2917392611">Looking at Paddle Quantum, a quantum computation included in deep learning framework.</a> was originally published in <a href="https://medium.com/mdr-inc">Blueqat (blueqat Inc. / former MDR Inc.)</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rotating a qubit using QML]]></title>
            <link>https://medium.com/mdr-inc/rotating-a-qubit-using-qml-17e0eb213d11?source=rss----8d311f05b2c5---4</link>
            <guid isPermaLink="false">https://medium.com/p/17e0eb213d11</guid>
            <category><![CDATA[quantum-computing]]></category>
            <category><![CDATA[scipy]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[rotation]]></category>
            <dc:creator><![CDATA[Gaurav Singh]]></dc:creator>
            <pubDate>Sat, 30 May 2020 12:36:37 GMT</pubDate>
            <atom:updated>2020-05-30T12:55:35.694Z</atom:updated>
            <content:encoded><![CDATA[<h3>Rotating a qubit using QML with Blueqat</h3><p>In this article, we will be looking into qubit rotation or rotating a |0&gt; state to |1&gt; state using QML optimization where we optimize the parameters of the Rotation operators Rx and Ry in order to achieve the state |1&gt;.</p><p>We will be using Blueqat SDK on <a href="https://quantumcomputing.com/">quantumcomputing.com</a> (<strong>Strangeworks</strong>) which is a cloud based quantum computing service.</p><ul><li>You can start by creating an account on quantumcomputing.com by going to the given link : <a href="https://quantumcomputing.com/beta">https://quantumcomputing.com/beta</a>.</li><li>Next, go to <a href="https://app.quantumcomputing.com/">https://app.quantumcomputing.com/</a> and create a new project there (Empty Python Project).</li></ul><p><a href="https://app.quantumcomputing.com/">StrangeWorks - Portal</a></p><p>You can also work out this using Blueqat SDK on the local machine. You can install blueqat using python with the pip command :</p><pre>pip3 install blueqat</pre><p><a href="https://github.com/Blueqat/Blueqat">Blueqat/Blueqat</a></p><p>The task is to rotate |0&gt; state to |1&gt; state. We will be using Rx and Ry as ansatz to explore the state space on the Bloch Sphere.</p><p>To get started we first import the libraries needed for the program :</p><pre>import numpy as np<br>from blueqat import Circuit<br>from scipy.optimize import minimize<br>from strangeworks.blueqat import StrangeworksBackend</pre><p>Next, we will be writing the function for the state preparation which is done by using Rx and Ry rotation operators as ansatz.</p><pre>def state_prep(state,params):<br>    state.rx(params[0])[0]<br>    state.ry(params[1])[0]<br>    return state</pre><p>We use the criterion of expectation value in order to rotate the qubit to |1&gt; state. Thus we take the expectation value as the cost function which needs to be minimized in order to achieve the state |1&gt;. For this, we measure the expectation value of <strong>σᴢ operator</strong> or do the measurement in the computational basis. We know that the expectation value of <strong>σᴢ operator </strong>lies in [-1,1] with the minimum expectation value for the state |1&gt; i.e <strong>-1</strong>.</p><p>Thus, we try to optimize the parameters of both the ansatz to achieve the minimum expectation value i.e <strong>-1</strong> in order to achieve the rotated state. The function for the cost value or the expectation value is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kQoBQie_9cCdettv39tdbw.png" /></figure><pre>def exp(params):<br> state=Circuit()<br> state_prep(state,params)<br> state.m[:]<br> shots=1000<br> b=state.run(shots=shots)<br> exp_value=(b[&#39;0&#39;]-b[&#39;1&#39;])/shots<br> return exp_value</pre><p>Next we try to optimize the above parameters using the Scipy.optimize minimum function with initial parameters as [0.1,0.2] and the learning rate being 0.05.</p><pre>init_params=np.array([0.1,0.2])</pre><pre>result=minimize(exp,init_params, method=&quot;Powell&quot; , tol=0.05)</pre><pre>print(f&#39;The expectation value after optimization is {result.fun}&#39;)</pre><p>Thus the results for the states and params on each iteration are:</p><pre>Counter({&#39;0&#39;: 983, &#39;1&#39;: 17})</pre><pre>[0.1, 0.2]</pre><pre>Counter({&#39;0&#39;: 992, &#39;1&#39;: 8})</pre><pre>[0.1, 0.2]</pre><pre>Counter({&#39;0&#39;: 730, &#39;1&#39;: 270})</pre><pre>[1.1, 0.2]</pre><pre>Counter({&#39;1&#39;: 960, &#39;0&#39;: 40})</pre><pre>[2.718034, 0.2     ]</pre><pre>Counter({&#39;0&#39;: 790, &#39;1&#39;: 210})</pre><pre>[5.33606803, 0.2       ]</pre><pre>Counter({&#39;1&#39;: 949, &#39;0&#39;: 51})</pre><pre>[2.718034, 0.2     ]</pre><pre>Counter({&#39;1&#39;: 933, &#39;0&#39;: 67})</pre><pre>[2.718034, 0.2     ]</pre><pre>Counter({&#39;1&#39;: 655, &#39;0&#39;: 345})</pre><pre>[2.718034, 1.2     ]</pre><pre>Counter({&#39;1&#39;: 553, &#39;0&#39;: 447})</pre><pre>[ 2.718034, -1.418034]</pre><pre>Counter({&#39;1&#39;: 954, &#39;0&#39;: 46})</pre><pre>[2.718034, 0.2     ]</pre><pre>Counter({&#39;1&#39;: 925, &#39;0&#39;: 75})</pre><pre>[ 2.718034,   -0.41803397]</pre><pre>Counter({&#39;1&#39;: 890, &#39;0&#39;: 110})</pre><pre>[2.718034, 0.581966]</pre><pre>Counter({&#39;1&#39;: 968, &#39;0&#39;: 32})</pre><pre>[ 2.71803400e+00, -8.22658533e-04]</pre><pre>Counter({&#39;0&#39;: 788, &#39;1&#39;: 212})</pre><pre>[ 5.336068,   -0.20164532]</pre><pre>Counter({&#39;1&#39;: 949, &#39;0&#39;: 51})</pre><pre>[ 2.71803400e+00, -8.22658533e-04]</pre><pre>Counter({&#39;0&#39;: 783, &#39;1&#39;: 217})</pre><pre>[ 5.336068,   -0.20164532]</pre><pre>Counter({&#39;0&#39;: 507, &#39;1&#39;: 493})</pre><pre>[-1.51803403,  0.32411523]</pre><pre>Counter({&#39;1&#39;: 957, &#39;0&#39;: 43})</pre><pre>[ 2.71803400e+00, -8.22658533e-04]</pre><pre>Counter({&#39;0&#39;: 706, &#39;1&#39;: 294})</pre><pre>[1.10000004, 0.12329257]</pre><pre>Counter({&#39;1&#39;: 915, &#39;0&#39;: 85})</pre><pre>[ 3.71803397, -0.07753009]</pre><pre>Counter({&#39;1&#39;: 999, &#39;0&#39;: 1})</pre><pre>[ 3.11343772 -0.03115306]</pre><pre>Counter({&#39;1&#39;: 998, &#39;0&#39;: 2})</pre><pre>[ 3.11343772 -0.03115306]</pre><pre>Counter({&#39;1&#39;: 778, &#39;0&#39;: 222})</pre><pre>[3.11343772 0.96884694]</pre><pre>Counter({&#39;0&#39;: 531, &#39;1&#39;: 469})</pre><pre>[ 3.11343772 -1.64918706]</pre><pre>Counter({&#39;1&#39;: 1000})</pre><pre>[ 3.11343772, -0.03115306]</pre><pre>Counter({&#39;1&#39;: 918, &#39;0&#39;: 82})</pre><pre>[ 3.11343772, -0.64918704]</pre><pre>Counter({&#39;1&#39;: 975, &#39;0&#39;: 25})</pre><pre>[3.11343772 0.35081294]</pre><pre>Counter({&#39;1&#39;: 1000})</pre><pre>[ 3.11343772, -0.01112575]</pre><pre>Counter({&#39;1&#39;: 997, &#39;0&#39;: 3})</pre><pre>[3.11343772, 0.0890108 ]</pre><pre>Counter({&#39;1&#39;: 1000})</pre><pre>[ 3.11343772, -0.01112575]</pre><pre>Counter({&#39;1&#39;: 955, &#39;0&#39;: 45})</pre><pre>[ 3.50884144, -0.04145615]</pre><pre>Counter({&#39;1&#39;: 892, &#39;0&#39;: 108})</pre><pre>[2.47366106, 0.03794987]</pre><pre>Counter({&#39;1&#39;: 999, &#39;0&#39;: 1})</pre><pre>[ 3.11343772, -0.01112575]</pre><pre>Counter({&#39;1&#39;: 978, &#39;0&#39;: 22})</pre><pre>[2.86906479, 0.00761947]</pre><pre>Counter({&#39;1&#39;: 999, &#39;0&#39;: 1})</pre><pre>[ 3.2644685,  -0.02271093]</pre><pre>Counter({&#39;1&#39;: 999, &#39;0&#39;: 1})</pre><pre>[ 3.16360143, -0.01497368]</pre><pre>The expectation value after optimization is -1.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GS2mp6u9dxpzZqqyP2f6Ug.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qQEEyD8S5iy4eVs2dihVSw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VS9KDXaOZoyk2LkiCJ6keg.png" /><figcaption>QuantumComputing.com</figcaption></figure><p>We can see the state transitioning from |0&gt; to |1&gt; on the histogram in the above diagrams on quantumcomputing.com (Strangeworks) and also see the change in parameters in the circuit diagram above.</p><p>Thus we see the rotation of a qubit from |0&gt; to |1&gt; using expectation value as the cost function and optimizing the parameters for the ansatz.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17e0eb213d11" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mdr-inc/rotating-a-qubit-using-qml-17e0eb213d11">Rotating a qubit using QML</a> was originally published in <a href="https://medium.com/mdr-inc">Blueqat (blueqat Inc. / former MDR Inc.)</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From SGD to Adam]]></title>
            <link>https://medium.com/mdr-inc/from-sgd-to-adam-c9fce513c4bb?source=rss----8d311f05b2c5---4</link>
            <guid isPermaLink="false">https://medium.com/p/c9fce513c4bb</guid>
            <category><![CDATA[stochastic-gradient]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <category><![CDATA[adam]]></category>
            <dc:creator><![CDATA[Gaurav Singh]]></dc:creator>
            <pubDate>Sun, 24 May 2020 11:41:40 GMT</pubDate>
            <atom:updated>2020-05-24T14:11:32.118Z</atom:updated>
            <content:encoded><![CDATA[<p>Gradient Descent is the most famous algorithm to optimize parameters in Neutral Networks and many other Machine learning algorithms. Most of the audience seek gradient descent as a way to optimize their ML models.</p><p>Gradient Descent is a way to minimize the loss function J(θ) which is parametrized by the model parameters θ∊R^n, where n is the number of parameters in the hypothesis function. Here we optimize the parameters by going opposite to the direction of the gradient of the loss function J(θ) with respect to the parameters. Let’s consider the loss function as a 3-D hilly terrain with heights and depths like in the figure below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jr7VkztlUFzB93YYPvSC8w.png" /></figure><p><a href="https://medium.com/@DBCerigo/on-why-gradient-descent-is-even-needed-25160197a635">Image Link</a></p><p>We follow the direction of the slope in the above terrain going downhill and try to find the deepest valley. These represent the local and the global minimums where the loss function i.e the squared difference of the predicted value and the actual value is the minimum.</p><p>There are three basic kinds of variants of gradient descent depending on the amount of data we use for the gradient descent:</p><ol><li>Batch Gradient Descent</li><li>Stochastic Gradient Descent</li><li>Mini-Batch gradient descent</li></ol><p>We will be focusing on SGD(Stochastic Gradient Descent) and traverse to one of the most favourable gradient descent optimization algorithm Adaptive Moment Estimation (Adam).</p><h3>Stochastic Gradient Descent (SGD):</h3><p>In the stochastic gradient descent we update all the parameters for each training example x(i) and the label y(i)individually, instead of computing the gradient of the cost function with respect to the parameters for the whole training set.</p><p><strong>θ=θ-α∇J(θ;x(i),y(i))</strong></p><p>SGD is generally noisier than typical Gradient Descent as it usually takes a higher number of iterations to reach the minima, because of its randomness in its descent. Even though it requires a higher number of iterations to reach the minima than typical Gradient Descent, it is still computationally much less expensive than typical Gradient Descent. SGD is also better than the typical batch gradient descent because it doesn’t have the redundancy by doing one update at a time. We see that SGD has frequent updates having high variance and thus we see a lot of fluctuations in the loss vs iterations graph as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*BS5UuWEE_qXzoWBDQumgDA.png" /></figure><p>Image Link : <a href="https://en.wikipedia.org/wiki/Stochastic_gradient_descent">https://en.wikipedia.org/wiki/Stochastic_gradient_descent</a></p><p>In the batch gradient descent technique we slowly and smoothly reach the minimum we are looking for while in the SGD we tend to jump to a lot of local minimums due to the above fluctuations and ultimalely it makes it a bit complicated to converge to the exact minimum. This can be improved by slowly decreasing the learning rate and thus we get the same convergence as batch gradient descent.</p><p>When we try to code the SGD what we have to keep in mind is to reshuffle the training data at every iteration. Let’s take data variable as the training data set.</p><pre>for i in range(iterations):<br>    np.random.shuffle(data)<br>    for j in data:<br>        gradient=evaluate_gradient(loss_func,j,data)   #evaluate_gradient is the function for the calculation of gradient.<br>        parameters=parameters-a.gradient <br>#a is the learning rate<br>#parameters are the features set which have to be updated.</pre><p>Although SGD and other gradient descent variants are a good bet but we have to face certain <strong>challenges</strong>. Let say we have a sparse data set where some features are frequently occurring and others are rare, then opting for a same learning rate for all the parameters will not be a good idea.We would want to make a larger update for the rarely occurring ones as compared to the frequently occurring features. Another challenge is to choose a proper learning rate. If we choose a very large learning rate, we try to dwindle around the minimum and if we choose a very small learning rate the convergence gets really slow. In the neural networks domain one of the issue we face with the highly non convex functions is that one gets trapped in the numerous local minimas.</p><p>Thus in order to deal with these challenges there are some gradient descent optimization algorithms that have come into place. Out of these <strong>Adaptive Moment Estimation (Adam) </strong>is the best optimizer at present. We will look into Adam optimizer which inherits itself from Adagrad and RMSProp, so we will look into all these optimizers sequentially.</p><h3>Adagrad:</h3><p>Adagrad optimizer helps us in solving one of the challenges we saw above connected to the sparse data set, by adapting the learning rate to the parameters, by having a low learning rate for the parameters associated to frequently occurring features and larger updates to the ones with infrequent features. One of the big application of this was to improve the robustness of the SGD which is quite widely used in large scale neural networks at Google.</p><p>So how it differ from the trivial SGD is that, in SGD we have a common learning rate for all the parameters and thus we are able to update all the parameters θ at once. But in Adagrad we try to have a different learning rate for each parameter θ at every timestamp. So the procedure is to have a per-parameter update and vectorize it.</p><p><strong>gᵢ = ∇J(θᵢ), </strong>where g is the gradient wrt to each parameter θᵢ.</p><p>Thus the SGD update comes out to be:</p><p><strong>θᵢ=θᵢ-α.gᵢ </strong>where we are updating all the parameters at one timestamp<strong>.</strong></p><p>How Adagrad is different is that it modifies the <strong>learning rate α </strong>for every parameter <strong>θᵢ</strong> based on all the past gradients that have been calculated so far for each <strong>θᵢ</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/0*vc6jz6eb2qLSz5jw.png" /></figure><p>Here Gᵢᵢ is an i*i dimensional diagonal matrix where the diagonal terms (i,i) represent the sum of the squares of the gradients w.r.t θᵢ until that timestamp and ϵ is the smoothing out constant to avoid the division by 0 and has a value of 10^(-8).</p><p>Next we can vectorize the above equation by doing a matrix vector multiplication between G and g, as the above matrix is diagonal matrix with the sum of squares of past gradients along its diagonal.</p><p>Next we can vectorize the above equation by doing a matrix vector multiplication between G and g, as the above matrix is diagonal matrix with the sum of squares of past gradients along its diagonal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/0*JnpigsKW5LORGv4m.png" /></figure><p>Thus we have a method to automatically tune in the learning rate. But we have a disadvantage here that as the G is positive cause of the squared sum being added in all the diagonals, the accumulated sum keeps on increasing during the training and thus the learning rate becomes infinitesimally small.</p><p>Thus we resort to another <strong>RMSprop method</strong> in order to solve the Adagrad’s diminishing learning rate.</p><h3>RMSprop with Adagrad:</h3><p>In order to decrease the monotonically learning rate in the above Adagrad algorithm, we try to take a decaying average of all the past squared gradients in a recursive fashion. Thus the running average of the squared gradients depends only on the previous average and the current gradient, the running gradient being denoted by E[g²]ᴛ at time t.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*k7s_k5HQ5OZW95o5.png" /></figure><p>As we see that the parameter update term in the Adagrad is of the form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/0*NCrjzEGYa35nTije.png" /></figure><p>We replace the G term here with the above E[g²]ᴛ which is nothing but root mean squared error-criterion of the gradient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ALOYtCe_u3I34cJR.png" /></figure><p>For the learning to work much better, we set the above values for the parameters and divide the gradient by square root of the above term. Thus we get the value of γ to be 0.9 and thus (1-γ) becomes 0.1</p><p>Thus the paramter update term becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7uJ0gcXK4zG_pYiV.png" /></figure><h3>Adam (Adaptive Moment Estimation):</h3><p>How Adam differs from the above adaptive learning algorithms is that we try to use both RMSprop and Momentum gradient descent optimization algorithms where we try to store both (exponentially decaying average of the past squared gradients and also the exponentially decaying average of past gradients). We thus compute the decaying average of past squared gradients and past gradients:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xSBhhUgJuxAbu_PQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d4z6F204ady2leqB.png" /></figure><p>where <strong>m</strong> is the decaying average of past gradients and <strong>v</strong> is the decaying average of past squared gradients.</p><p>Initially m and v are started with 0 vectors and as the decay rates are small enough in the beginning where (both the betas are close to 1), we see that both these are biased towards 0.</p><p>Thus we work on these biases by computing bias-corrected terms:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VqrghRKiWhNcNMn1.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1Bahspy9cCV_8zRT.png" /></figure><p>And finally we update the parameters similar to the previous optimization technique:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ADI_BAwrJzkQLbJd.png" /></figure><p>The value of β1 is 0.9, β2 is 0.999 and 10^(-8) for ϵ for good enough value for the learning rate according to the authors of Adam.</p><p>Let’s code the <strong>Adam Optimizer</strong> in Python. Let’s start with a function x³+3x²+4x. Taking the above values for all the constants and initiating θ=0, m_t=0,v_t=0.</p><pre>import math<br>a=0.01<br>b_1=0.9<br>b_2=0.999<br>e=1e-8</pre><pre>def function(x):<br>    return x*x*x-3*x*x+4*x<br>def gradiant(x):<br>    return 3*x*x-6*xt=0<br>theta=0<br>m_t=0<br>v_t=0<br>i=0</pre><pre>iter=1000</pre><pre>while(i&lt;iter):</pre><pre>    t=t+1    <br>    grad=gradiant(theta)<br>    m_t=b_1*m_t+(1-b_1)*grad<br>    v_t=b_1*v_t+(1-b_2)*grad*grad    <br>    m_cap_t=m_t/(1-b_1**t)<br>    v_cap_t=v_t/(1-b_2**t)    <br>    theta=theta-(a*m_cap_t)/(math.sqrt(v_cap_t)+e)<br>    i=i+1<br>print(theta)</pre><p>Comparison of Adam to other optimization algorithms:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/0*zKIH-3pSjclDGfM5.png" /></figure><p><a href="https://arxiv.org/abs/1412.6980">Image Link</a></p><p>Thus we looked into SGD (Stochastic Gradient Descent) and it’s improvement by using adaptive learning algorithm Adam.</p><h3>References:</h3><ul><li>H. Robinds and S. Monro, “A stochastic approximation method,” Annals of Mathematical Statistics, vol. 22, pp. 400–407, 1951.</li><li>Zeiler, M. D. (2012). ADADELTA: An Adaptive Learning Rate Method. Retrieved from <a href="https://arxiv.org/abs/1212.5701">http://arxiv.org/abs/1212.5701</a></li><li>Sebastian Ruder : <a href="https://arxiv.org/abs/1609.04747">https://arxiv.org/abs/1609.04747</a></li><li>Kingma, D. P., &amp; Ba, J. L. (2015). Adam: a Method for Stochastic Optimization. International Conference on Learning Representations, 1–13.</li><li><a href="https://machinelearningmastery.com/adam-optimization-algorithm-for-deep-learning/">https://machinelearningmastery.com/adam-optimization-algorithm-for-deep-learning/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9fce513c4bb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mdr-inc/from-sgd-to-adam-c9fce513c4bb">From SGD to Adam</a> was originally published in <a href="https://medium.com/mdr-inc">Blueqat (blueqat Inc. / former MDR Inc.)</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time Evolution Operators]]></title>
            <link>https://medium.com/mdr-inc/time-evolution-operators-be2968493b86?source=rss----8d311f05b2c5---4</link>
            <guid isPermaLink="false">https://medium.com/p/be2968493b86</guid>
            <category><![CDATA[entanglement]]></category>
            <category><![CDATA[operators]]></category>
            <category><![CDATA[pauli]]></category>
            <category><![CDATA[quantum-mechanics]]></category>
            <category><![CDATA[quantum-computing]]></category>
            <dc:creator><![CDATA[Gaurav Singh]]></dc:creator>
            <pubDate>Fri, 15 May 2020 08:22:52 GMT</pubDate>
            <atom:updated>2020-05-29T07:00:27.170Z</atom:updated>
            <content:encoded><![CDATA[<p>In Quantum Mechanics, we know that every system has many quantum states. As a passage of time new states are evolved. What we wish to do is to find a relation between these initial states and the evolved states. For this purpose we use a linear operator which evolves the states over time which is famously called the <strong>Time Evolution Operator</strong>. Let us see the representation of a time evolution operator.</p><p>Let us start with an initial state <strong>|ψ(t₀)&gt;</strong> and let the final state be <strong>|ψ(t)&gt;</strong> at time t. Let’s take a Unitary operator <strong>U(t,t₀)</strong> which is linear operator which depends on t and t₀. The final state is obtained by the Unitary operator and the initial state in such a way:</p><h4>|ψ(t)&gt; = U(t,t₀) |ψ(t₀)&gt;</h4><p>where t &gt; t₀. Let’s see a simple case, when the time t=t₀. This means that the state isn’t changed and thus we can say that U(t₀,t₀)=I where I is the Identity matrix. We obtain the structure of the Unitary operator by inputting the final state <strong>|ψ(t)&gt; </strong>into the time dependent <strong>Schrodinger equation</strong> which is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*tvUG5VbefV1VFeuodyb4xg.png" /></figure><p>where i= square root of -1, h is the Planck’s constant <strong>d/dt</strong> is the rate of change with respect to time, <strong>ψ</strong> being the wavefunction at time t and H is the hamiltonian operator.</p><p>Next we input the state <strong>|ψ(t)&gt; </strong>from the Unitary operator equation above into the schrodinger equation and try to solve the Schrodinger equation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*H9lJ_HGPu05mlLh3EHjwtA.png" /></figure><p>And thus we are left with the equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*D4HViE8SMKKe6npqY80cWw.png" /></figure><p>This equation is a first order differentiation equation and solving it we get the value of unitary operator as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*yG3W4s8podsG4mKGZyuD-w.png" /></figure><p>Taking h=1 and t₀=0 the equation comes out to be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/1*HrVKQhKI6hmTsp_2uh4qZA.png" /></figure><p>Thus we see the evolution of the quantum state as:</p><p><strong>|ψ(t)&gt; = exp{-itH} |ψ(0)&gt;</strong></p><p>Now let us look at the time evolution of some of the famous logic gates.</p><p>For us to work on a Quantum Circuit we need to extract the matrix for the Unitary operators for these gates. For the conversion of the exp{-iθA} we use the <strong>Taylor-Maclaurin</strong> series which tells that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*xks_RqoNupxDe4uJemTBEw.png" /></figure><p>Using this equation we can convert the expansion series for <strong>exp{iθ}</strong> into <strong>Cos(θ)+iSin(θ)</strong> as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*vO1ddtNxzCWHzBrE4et9qg.png" /></figure><p>Using the beautiful property of the Pauli gates where if A is a Pauli gate and if we multiply it with itself, we get a I (Identity matrix).</p><p>And thus if we take <strong>exp{-iθA}</strong> , in the above equation we get <strong>I</strong> at places where we have even powers (element 1,3,5…) and A gate at the places where we have odd powers (element 2,4,6…) . Thus <strong>exp{-iθA}</strong> comes out to be:</p><blockquote><strong>Cos(θ)I-i.Sin(θ)A</strong></blockquote><p>as the terms at the odd places make up the expansion of <strong>cos function</strong> and the elements at the even places make up the expansion of <strong>sin function</strong>.</p><h4><strong>Single Qubit gates Z, X, Y:</strong></h4><p>The time evolution unitary operator for the Z gate is <strong>exp{-iθZ}</strong> where θ corresponds to time. This is also referred as <strong>Rᴢ(θ)</strong> which is rotation about the Z axis by an <strong>angle θ</strong>.</p><p><strong>exp{-iθZ} = Cos(θ/2)I-i.Sin(θ/2)Z</strong>, where Z is the Pauli matrix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*wGXAwU7voxP6OMP0s6z7Zg.png" /></figure><p>where ϕ goes from [0,π].</p><p>Similarly :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*mDk65OnW0GGivsWGOnb6JA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*OQB4u4G4wkmwM71kSBJiuw.png" /></figure><p>where θ goes from [0,π].</p><p>Here we see that the time evolution of these single qubit gates correspond to the rotation about the respective axis.</p><h4><strong>Let us now look at the two qubit gates ZZ, XX and YY:</strong></h4><p>It seems these operators are commonly used in certain algorithms like QAOA to reduce the depth of the circuit and thus we also look at the time evolution of these important operators.</p><p>Again following the rule we used before we can write :</p><p><strong>Rzz(ϕ) = exp{iZ⊗Zϕ} = cos(ϕ)I⊗I-sin(ϕ)Z⊗Z</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*BamcYgyUfPtGAlZ_o8G00A.png" /></figure><p>We can implement this matrix for a two qubit state by applying a sequence of <strong>CX.(I⊗Rz(θ)).CX</strong></p><p>We see that Rzz(θ) changes the <strong>global</strong> <strong>phase</strong> of the <strong>|00&gt;,|01&gt;,|10&gt;,|11&gt;</strong> states according to the above given matrix and thus creating a relative phase for the superposition of these states.</p><p>Similarly <strong>Rxx(θ)</strong> can be written as <strong>cos(ϕ)I⊗I-sin(ϕ)X⊗X.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*KqIawTpX16WnLAwmYHtaAg.png" /></figure><p>And <strong>Ryy(ϕ)</strong> comes out to be <strong>cos(ϕ)I⊗I-sin(ϕ)Y⊗Y.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*Eym8phbQuVxoBKUZwhd2dg.png" /></figure><h4>Obtaining Rxx(θ) and Ryy(θ) from Rzz(θ):</h4><p>We can obtain these two matrices by actually diagonalizing the operators XX and YY. As we know that <strong>X=HZH and Y=SXS†.</strong> We can bring both the operators in Z form.</p><p><strong>Let us see it for XX gate.</strong></p><p><strong>exp{-iX⊗Xθ}</strong> can be written as <strong>exp{-iHZH⊗HZHθ} </strong>which can be further simplified as <strong>exp{-iH⊗H.Z⊗Z.H⊗Hθ}.</strong></p><p>Thus we can write Rxx(θ) as <strong>H⊗H.exp{-iZ⊗Zθ}.H⊗H.</strong></p><p>Now it is easy to implement Rxx(θ) on a Quantum Circuit which can be done as : <strong>H⊗H.CX.(I⊗Rz(θ)).CX.H⊗H</strong></p><p>Similarly we can get the Ryy(θ) by following <strong>Y=SXS†</strong> and thus getting it easily done by <strong>S⊗S.H⊗H.CX.(I⊗Rz(θ)).CX.H⊗H.S†⊗S†.</strong></p><p><strong>But why are the Rxx and Ryy operators so important?</strong></p><p>Let’s see how the unitary evolution of these gates change the quantum states.</p><p>Let’s take states |00&gt;,|01&gt;,|10&gt;,|11&gt;.</p><p>Applying Rxx(θ) to these states.</p><pre><strong>Rxx(θ)|00&gt; = cos(θ)|00&gt;-isin(θ)|11&gt;<br>Rxx(θ)|01&gt; = cos(θ)|01&gt;-isin(θ)|10&gt;<br>Rxx(θ)|10&gt; = cos(θ)|10&gt;-isin(θ)|01&gt;<br>Rxx(θ)|11&gt; = cos(θ)|11&gt;-isin(θ)|00&gt;</strong></pre><p>We see that these gates helped in achieving entanglement of some form and we get <strong>maximal entanglement</strong> or the bells states when <strong>θ becomes π/4</strong>. This is lot advantageous to the trivial <strong>H.CX </strong>way of creating entanglement because that only creates bell states while these two operators create different types of entanglements.</p><p>So here we discussed the basics of Time evolution Operator and tried to create time evolution operators for some famous gates and saw their significance.</p><h4>References:</h4><ul><li>Time Evolution : <a href="https://en.wikipedia.org/wiki/Time_evolution">https://en.wikipedia.org/wiki/Time_evolution</a></li><li>Time evolution in QM <a href="http://physics.mq.edu.au/~jcresser/Phys301/Chapters/Chapter15.pdf">http://physics.mq.edu.au/~jcresser/Phys301/Chapters/Chapter15.pdf</a></li><li>Quantum Logic Gate : <a href="https://en.wikipedia.org/wiki/Quantum_logic_gate">https://en.wikipedia.org/wiki/Quantum_logic_gate</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be2968493b86" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mdr-inc/time-evolution-operators-be2968493b86">Time Evolution Operators</a> was originally published in <a href="https://medium.com/mdr-inc">Blueqat (blueqat Inc. / former MDR Inc.)</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Tensors (Quantum Circuit Simulation)]]></title>
            <link>https://medium.com/mdr-inc/introduction-to-tensors-quantum-circuit-simulation-220721c68307?source=rss----8d311f05b2c5---4</link>
            <guid isPermaLink="false">https://medium.com/p/220721c68307</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[quantum-computing]]></category>
            <category><![CDATA[tensor]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Gaurav Singh]]></dc:creator>
            <pubDate>Thu, 14 May 2020 14:41:55 GMT</pubDate>
            <atom:updated>2020-05-14T16:58:00.505Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s scenario most of the work in Quantum Computing is being done in the software layer ranging from Optimization, Machine Learning, Hybrid Quantum Classical Algorithms like QAOA, VQE which seem to be the potential game changers in the NISQ era (next 5–10 years). In order to run these Quantum circuits we either need a functional Quantum Hardware which is not feasible for most of the players or a Quantum Circuit Simulator running on a conventional computer for us to observe the properties of Quantum Mechanics like Superposition and Entanglement. We are trying to compete through these with the conventional computers and communications and in order to achieve this we seek new algorithms and circuits with revolutionary behaviour like the Shor’s algorithm on prime factorization. Most of the time success of these algorithms and their potential speed ups are limited due to the cost of simulation on the conventional systems. Thus, along with working on new designs for Quantum Information processing hardware, more efficient simulations can help in getting sharper bounds on the Quantum algorithms.</p><p>What we are trying to achieve on a classical computer is a randomized simulation of a Quantum Circuit as the outcome of a quantum computation is probabilistic. So in order to work this out we create a classical randomized algorithm whose output distribution is similar to a simulated Quantum Computation. What happens in a simulated Quantum Circuit is that we start with a predefined input state which generally is a |0&gt; state whose vector representation being ( 1 , 0 ) and the circuit has certain width depending on the number of initial qubits. The depth of the circuit is defined by the number of gates or the unitary matrices being applied to the given system. The gates can be a 1-qubit gate, 2-qubit to 3-qubit gates. And finally the qubits are measured and we get the classical outputs depending on the amplitudes.</p><h4>So what is the cost of simulation on a conventional system?</h4><p>In order to simulate a Quantum Circuit, one may use a naive brute force calculation of the quantum amplitudes which have an exponential overhead. Classes of Circuits which have an efficient simulation are often restricted by “gate library”, but do not impose restrictions on how the gates are interconnected or sequenced. Another way to impose restriction on the class of quantum circuits is to limit the amount of entanglement in the intermediate states which is performed by the Controlled gates. The goal here is to study the complexity of running a classical simulation of the Quantum Circuit.</p><h4>Complexity of Quantum Circuit Simulators :</h4><p>A common approach for applying gates (matrices) is to do in the form of matrix multiplications where a gate A followed by a gate B on a given qubit can be done in a naive way using <strong>A X B. </strong>So if we have a qubit state with <strong>m</strong> number of qubits, the amplitudes may be represented by a 2ᵐ X 1 vector and the corresponding gate matrices being 2ᵐ X 2ᵐ matrix. So what is the complexity of multiplying two such matrices? We see that the compexity of such an operation being <strong>O(2^(3m))</strong> where m is the number of qubits. We can see the same from the given code example below.</p><pre>#Checking matrix multiplication complexity.</pre><pre>import numpy as np<br>A = np.random.random(size=(10,10))<br>B = np.random.random(size=(10,10))<br>C = np.zeros(10,10)<br>for i in range(10):<br>    for j in range(10):<br>        for k in range(10):<br>            C[i,j]= A[i,k] * B[k,j]</pre><p>Here we see that the number of iterations happening are 10*10*10. So if we take matrices of size <strong>2ᵐ X 2ᵐ</strong> for a given qubit state with 2ᵐ amplitudes. The time complexity for one such operation with two matrices comes out to be <strong>O(2^(3m))</strong>. Our conventional computer can carry out <strong>2 billion instructions</strong> per second that is 10⁹ instructions/sec. This will very easily cross the billion limit by increasing the qubits.</p><p>One improved way on this is to start by multiplying the gate matrix to the qubit vector. Here we see that when a matrix is multiplied to a vector, we see that the time complexity becomes O(2^(2m)). And similarly when a new operator/matrix is multiplied to the modified state vector the time complexity remains the same. Thus we succeeded in improving the time complexity from <strong>O(2^(3m)) </strong>to<strong> O(2^(2m)). </strong>This is because of the fact that matrix multiplication is not constant with respect to associativity.</p><p>Now what we see that if we want to apply a 1-qubit or a 2-qubit gate to a given m qubit vector state which has an amplitude length of 2ᵐ, we see that we have to do padding of the given matrix by multiplying it with <strong>I matrices</strong> to fill up the sparse matrix with values, for our conventional computer to do the matrix multiplication. So let’s say we have two Unitary matrices Uᵏ and Uʲ which apply on a and b number of qubits respectively. Uᵏ being <strong>2ᵃ x 2ᵃ</strong> and Uʲ being <strong>2ᵇ x 2ᵇ</strong>. If a and b are &lt; m, we need to fill the given sparse matrix by values and we multiply with <strong>I matrices</strong> for the same.</p><p>But we succeeded in reducing the complexity from O(2^(3m)) to O(2^(2m))<strong>. But is it enough? </strong>Let’s see. Let’s take a qubit vector state of 20 qubits. 20 qubits look really small right? Our amplitude vector has 2²⁰ (1048576) elements. Applying a single qubit gate which is mere 2² x 2² will be really slow. Let’s see how. We need to scale this 1 qubit gate to 2²⁰ x 2²⁰ by filling the sparse matrix with values which the simulator automatically does by multiplying by I matrices again and again. Finally we reach an equal enough matrix. Now the time complexity of this matrix operation on the state being <strong>2^(2*20)</strong> which is whooping <strong>1.0995116e+12</strong>. This will surely take more than 1000 seconds for just one operation. As quantum simulator follows the probabilistic nature of Quantum Computation, if we run it large number of times, the result will surely take days which is way way slower than what we wanted to achieve.</p><p>But we should be able to reduce the calculation of the 2^m amplitudes to O(2^m) in some cases. But How? <strong>Due to the fact that the matrix multiplication is not constant with associativity, we can think a bit more and </strong>extend it to autodifferentiation (backprop in NN’s), <strong>tensor networks</strong> (tensor contractions) and QC simulators. So let’s bring tensors in order to improve our performance.</p><h4><strong>What are Tensors?</strong></h4><p>A tensor is a <strong>generalization of vectors and matrices</strong> and is easily understood as a multidimensional array. A scalar being a 0 dim tensor, a vector being 1 dimensional tensor, a matrix 2 order tensor and and 3 dimension and more array is referred to as Tensor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*fYh-wGiANwmA9B8CPoWCzg.png" /></figure><p>The indices here in the diagrammatic notation represent a dimension <a href="https://www.tensors.net/tutorial-1">Link</a>. A tensor has an <strong>order</strong> and a <strong>shape</strong>. The order being the number of dimensions and the shape being the number of entities in the dimensions. So intuitively, we can say that a 3D tensor like a book where the matrix is represented by the page and the number of pages in the book being the third dimension just like a cuboid.</p><p>We can further form networks comprised of multiple tensors, where an index shared by two tensors denotes a <strong>contraction</strong> (or summation) over this index:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*iGhLawlPYIWniHQwLlmTlQ.png" /></figure><p>The left is equivalent to a matrix multiplication between matrices <strong><em>A</em></strong> and<strong><em> B</em></strong>, while the example on the right produces a rank-3 tensor <strong><em>D</em></strong> via the contraction of a network with three tensors <a href="https://www.tensors.net/tutorial-1">Image Link</a>.</p><p>This is called <strong>Tensor Contraction</strong>. We can achieve this contraction by permutation and reshaping over the indices which we will be seeing in a later article. The goal is to <strong>to approximate a single high order tensor as a tensor network composed of many low order tensors. </strong>This latter representation is very efficient seeing the high complexity of a single high dimensional tensor.</p><p>So how is a Tensor helpful in a Quantum Circuit Simulation. Let’s take a N dimensional tensor with every dimension being size 2.</p><p>We can represent a 1 qubit state as a 1 - dimensional tensor, it being an array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*8U94anMYfjo8TtRTDluQww.png" /></figure><p>A 2-qubit state can be written as a 2 D tensor which would be denoted by a matrix with two indices (i,j) ∈ [0,1] .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*FoNdl9f1q_rf4xjunYOIcg.png" /></figure><p>A 3 qubit state being written as a 3D Tensor which has 3 indices where all the indices have a size 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*3McM9-hpnf2DNiaWYi8ONw.png" /></figure><p>It can be seen as nested matrices, where matrices are one above the other and i denoting the height and j,k denoting a matrix dimensions. So if we want to find out the amplitude of <strong>𝛹<em>011</em></strong><em> </em>we go to the 0th row of the cube matrix and then go to the <strong>1st row</strong> of the obtained matrix followed by the <strong>1st column</strong>.</p><p>Let’s see how we can find the amplitude of |011&gt; using both normal array and a tensor object.</p><p>Let’s use Blueqat SDK for the same.</p><p><a href="https://github.com/Blueqat/Blueqat">Blueqat/Blueqat</a></p><pre>from blueqat import Circuit<br>a=Circuit()<br>a.h[:]<br>a.m[:]<br>b=a.run()<br>print(b)<br># b represents a length 8 vector.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZkGPcTnn9mOqgORBZt-Nuw.png" /></figure><p>In order to find the amplitude of |011&gt;.</p><pre>i=int(0b011)<br>print(b[i])</pre><pre>(0.3535533905932737+0j)</pre><p>Now we try to reshape this to a 3D Tensor.</p><pre>b=b.reshape((2,2,2))<br>print(b)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*dV9Hm_TWMddOWDaob07Bvw.png" /></figure><p>We can just access the amplitude by running:</p><pre>v[0,1,1]</pre><p><strong>So how using tensors is a boon in reducing time complexity?</strong> Let say we want to compute U|𝛹&gt; = |𝛷&gt; where 𝛹 being the initial qubit state and U is applied to 2 qubits (being a 2 qubit gate). Let the initial state is a 3 qubit state and the U is a 2 qubit transformation. A 2 qubit gate is a 4 x 4 shape matrix and thus for us to create a tensor out of it, we need a 4 order size-2 tensor as we have 4 indices for each number in the matrix i,j,k,l. So the U = Uɪᴊᴋʟ and the 3 qubit state can be represented with three indices as |𝛹&gt;ᴀʙᴄ. Now if the 2 qubit matrix U acts on the state 0 and 2, the following is the multiplication of the tensors corresponding to the subspaces :</p><p>𝛷ᴊᴀʟ = Uɪᴊᴋʟ 𝛹ɪᴀᴋ</p><p>So what happens here is that we multiply 𝛹 and U is the subspaces we wanted to apply that is at 0 and 2. What we did was only involve the states in the indices 0 and 2 and multiplying it by the submatrices at the same indices. The ove tensor operation has the complexity <strong>O(2^(m+2))</strong> which is what we were trying to achieve. This all happens due to <strong>Tensor Contractions i.e manipulating the tensors by permutation and reshaping the indices following by further binary Tensor contractions.</strong></p><p>So the Tensor contractions helped us in going around the initial overhead where we had to use the whole 2ᵐ x 2ᵐ matrix for a 2 qubit operation. This is just for us to get the amplitude updates. “Tensor networks” are a larger chain of these tensor contractions we did above and are helpful in improving the Quantum Circuit simulation complexity.</p><p>Next we will discuss how different gates act to these tensor operations and how they improve the multiplication efficiently and how the time complexity changes with scaling the qubits. Also we will come across TensorFlowQuantum which is a library for hybrid quantum-classical machine learning and further get deeper into ML and Quantum Computing.</p><p><strong>References:</strong></p><ul><li>TensorFlow : <a href="https://www.tensorflow.org/tutorials/customization/basics">https://www.tensorflow.org/tutorials/customization/basics</a></li><li>Simulating quantum computation by contracting tensornetworks : <a href="http://web.eecs.umich.edu/~shiyy/mypapers/treewidth-sicomp.pdf">http://web.eecs.umich.edu/~shiyy/mypapers/treewidth-sicomp.pdf</a></li><li>Introduction to Tensors : <a href="https://www.tensors.net/tutorial-1">https://www.tensors.net/tutorial-1</a></li><li>Complexity Theory: <a href="https://sites.google.com/view/quantum-computer-programming/schedule">https://sites.google.com/view/quantum-computer-programming/schedule</a></li><li><a href="https://www.springer.com/gp/book/9783030239213">https://www.springer.com/gp/book/9783030239213</a></li><li><a href="https://machinelearningmastery.com/introduction-to-tensors-for-machine-learning/">https://machinelearningmastery.com/introduction-to-tensors-for-machine-learning/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=220721c68307" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mdr-inc/introduction-to-tensors-quantum-circuit-simulation-220721c68307">Introduction to Tensors (Quantum Circuit Simulation)</a> was originally published in <a href="https://medium.com/mdr-inc">Blueqat (blueqat Inc. / former MDR Inc.)</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reverse playback of QAOA using blueqat quantum computing SDK 0.3.14]]></title>
            <link>https://medium.com/mdr-inc/reverse-playback-of-qaoa-using-blueqat-quantum-computing-sdk-0-3-14-e40708763e5e?source=rss----8d311f05b2c5---4</link>
            <guid isPermaLink="false">https://medium.com/p/e40708763e5e</guid>
            <category><![CDATA[blueqat]]></category>
            <category><![CDATA[quantum-computing]]></category>
            <dc:creator><![CDATA[Yuichiro Minato]]></dc:creator>
            <pubDate>Tue, 12 May 2020 13:10:42 GMT</pubDate>
            <atom:updated>2020-05-12T13:10:31.480Z</atom:updated>
            <content:encoded><![CDATA[<p>The new release of blueqat now support QAOA mixer, RXX,RYY,RZZ ising coupling gate and the reverse playback of quantum circuit. Now I do some trial on Quantum Adiabatic process with variational QAOA algorithm on gate model quantum computing.</p><h3>Install Blueqat</h3><p>Install blueqat from pip,</p><pre>!pip install -U blueqat</pre><p>The hamiltonian is like below and the initial state is |+&gt; corresponding to the initial mixer X.</p><pre>from blueqat import Circuit<br>from blueqat import vqe<br>from blueqat.pauli import X,Y,Z</pre><pre>h = 5*Z[0]-2*Z[0]*Z[1]<br>step = 2</pre><pre>result = vqe.Vqe(vqe.QaoaAnsatz(h,step)).run()<br>print(result.most_common())<br>print(result.circuit)</pre><p>The result is,</p><pre>(((1, 1), 0.8144445064787001),)</pre><pre>Circuit(2).h[:].cx[0, 1].rz(49.460289478707516)[1].cx[0, 1].rz(-123.6507236967688)[0].rx(4.758485377427176)[:].cx[0, 1].rz(64.56773083408335)[1].cx[0, 1].rz(-161.41932708520838)[0].rx(0.7862442700373741)[:]</pre><p>This circuit include CX-RZ-CX which is the time evolution of ZZ hamiltonian.</p><p>As CX-RZ-CX = RZZ, the quantum circuit is,</p><pre>Circuit(2).h[:].rzz(49.460289478707516)[0,1].rz(-123.6507236967688)[0].rx(4.758485377427176)[:].rzz(64.56773083408335)[0,1].rz(-161.41932708520838)[0].rx(0.7862442700373741)[:].m[:].run(shots=1000)</pre><p>And we get the similar result.</p><pre>Counter({&#39;11&#39;: 829, &#39;00&#39;: 56, &#39;10&#39;: 115})</pre><p>The relation between the hamiltonian and time evolution operator is clear using RZZ.</p><h3>Reverse Playback of the circuit</h3><p>QAOA is using quantum adiabatic process to exchange two hamiltonian. The initial hamiltonian is usually chosen by the constraint of the problem. Here XYmixer of (XX+YY)/2 is chosen.</p><p>Usually the process is from easy problem to difficult problem.</p><p>Here we try the reversed process from difficult problem to easy problem.</p><h3>Problem</h3><p>The hamiltonian is the simple shape with Z and ZZ operator.</p><pre>from blueqat import Circuit<br>from blueqat import vqe<br>from blueqat.pauli import X,Y,Z</pre><pre>h = 5*Z[0]-2*Z[0]*Z[1]<br>step = 2<br>init = Circuit().h[0].cx[0,1].x[0]<br>mixer = 0.5*X[0]*X[1] + 0.5*Y[0]*Y[1]</pre><pre>result = vqe.Vqe(vqe.QaoaAnsatz(h,step,init,mixer)).run()<br>print(result.most_common())<br>print(result.circuit)</pre><p>The result and the circuit is,</p><pre>(((1, 0), 0.9970150121543512),)</pre><pre>Circuit(2).h[0].cx[0, 1].x[0].cx[0, 1].rz(39.00633185153547)[1].cx[0, 1].rz(-97.51582962883867)[0].h[0].h[1].cx[0, 1].rz(-8.988636280080764)[1].cx[0, 1].h[0].h[1].rx(-1.5707963267948966)[0].rx(-1.5707963267948966)[1].cx[0, 1].rz(-8.988636280080764)[1].cx[0, 1].rx(1.5707963267948966)[0].rx(1.5707963267948966)[1].cx[0, 1].rz(34.522866650015565)[1].cx[0, 1].rz(-86.30716662503892)[0].h[0].h[1].cx[0, 1].rz(-8.64561683891384)[1].cx[0, 1].h[0].h[1].rx(-1.5707963267948966)[0].rx(-1.5707963267948966)[1].cx[0, 1].rz(-8.64561683891384)[1].cx[0, 1].rx(1.5707963267948966)[0].rx(1.5707963267948966)[1]</pre><h3>Playback</h3><p>The adiabatic process should be reversible. Now prepare the |10&gt; state first and apply the reverse circuit of QAOA, the result would be |00&gt; which is the initial state of the qubit.</p><pre>#prepare the |10&gt; state and apply dagger() to get the reversed circuit</pre><pre>result2 = (Circuit().x[0] + result.circuit.dagger()).m[:].run(shots=100)<br>print(result2)</pre><pre>Counter({&#39;00&#39;: 100})</pre><p>The result successfully playback to |00&gt; !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e40708763e5e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mdr-inc/reverse-playback-of-qaoa-using-blueqat-quantum-computing-sdk-0-3-14-e40708763e5e">Reverse playback of QAOA using blueqat quantum computing SDK 0.3.14</a> was originally published in <a href="https://medium.com/mdr-inc">Blueqat (blueqat Inc. / former MDR Inc.)</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quantum Machine Learning (Quantum Deep Learning) with MERA/MPS model on Blueqat quantum computing…]]></title>
            <link>https://medium.com/mdr-inc/quantum-machine-learning-quantum-deep-learning-with-mera-mps-model-on-blueqat-quantum-computing-9e12eea34c22?source=rss----8d311f05b2c5---4</link>
            <guid isPermaLink="false">https://medium.com/p/9e12eea34c22</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[quantum-computer]]></category>
            <dc:creator><![CDATA[Yuichiro Minato]]></dc:creator>
            <pubDate>Sat, 09 May 2020 06:15:52 GMT</pubDate>
            <atom:updated>2020-05-09T06:49:44.258Z</atom:updated>
            <content:encoded><![CDATA[<h3>Quantum Machine Learning with MERA/MPS model on Blueqat quantum computing SDK</h3><p>Like Tensorflow follows quantum computing and NISQ variational circuit like tensorflow quantum,</p><p><a href="https://github.com/tensorflow/quantum">GitHub - tensorflow/quantum: Hybrid Quantum-Classical Machine Learning in TensorFlow</a></p><p>I just tried to implement two model on blueqat with simple implementation, let’s look at how to create.</p><h3>MERA/TTN</h3><p>The model is from tensor network field. Here the tree structure of quantum state can be written in quantum circuit.</p><pre>|0&gt; --[input]--U3--*--<br>                   |<br>|0&gt; --[input]--U3--X--U3--*--<br>                          |<br>|0&gt; --[input]--U3--*--    |<br>                   |      |<br>|0&gt; --[input]--U3--X--U3--X--[m]-[expt]-[loss]-[output]</pre><p>Here I used U3 gate which has 3 angle parameters and CX gate to operate on single quantum state and entanglement among multiple qubits.</p><pre>#MERA circuit<br>def mera(a):<br><br>    u = Circuit()<br>    u.u3(a[0],a[1],a[2])[0]<br>    u.u3(a[3],a[4],a[5])[1]<br>    u.u3(a[6],a[7],a[8])[2]<br>    u.u3(a[9],a[10],a[11])[3]<br>    u.cx[0,1].cx[2,3]<br>    u.u3(a[12],a[13],a[14])[1]<br>    u.u3(a[15],a[16],a[17])[3]<br>    u.cx[1,3]<br><br>    return u</pre><p>Finally to get the value we do measurement of Z axis to estimate the state vector indirectly and get the expectation value.</p><p>For the quantum computer we use sampling to run the circuit many times and get the expectation value of hamiltonian, but it takes a lot of time, here we use state vector directly to get the expectation value of Z hamiltonian.</p><p>This process is VQE step and after this, we use loss function for training</p><h3>Input data and target data</h3><p>The input data is quantum circuit here. If you enter the classical data of bit as 01, the data will be converted into quantum circuit using X gate to flip the initial state for quantum circuit.</p><p>The MERA circuit including parameters as angle on U3 gate randomly at first.</p><p>After the circuit is run and the expectation value is calculated, we can use loss function with target label.</p><p>Besides the input data is implemented as quantum circuit, the target label is scalar value. By evaluating the error rate using loss function with expectation value of Z measurement and target label, we can now do the optimization process.</p><h3>Optimization</h3><p>Using numerical differentiation, the gradient can be acquired. With the gradient we can update the angle parameters inside of the quantum circuit.</p><p>Repeatedly doing this process we can go to the much more lower point of function to get the local/global minimum of function.</p><p>Here we use stochastic gradient descent to randomly select the data from the data set and do gradient descent.</p><h3>Training Process</h3><p>Let’s do the training process on blueqat. First we import some tools and set the initial parameters to optimize.</p><pre>from blueqat import Circuit<br>import matplotlib.pyplot as plt<br>import numpy as np<br>import pandas as pd<br>import time<br>%matplotlib inline<br><br>np.random.seed(39)<br><br>#initial parameters<br>ainit = [np.random.rand()*np.pi*2 for i in range(18)]</pre><p>Next we prepare some functions to calculate expectation value, loss function. The last one is to convert data to gate circuit.</p><pre>#expectation value<br>def E(sv):<br>    return sum(np.abs(sv[:8])**2)-sum(np.abs(sv[8:])**2)<br><br>#loss function<br>def L(p,t):<br>    return (p-t)**2<br><br>#data to gate<br>def ix(l):<br>    u = Circuit(4)<br>    for i in l:<br>        u.x[i]<br>    return u</pre><p>And prepare the training data and validation data.</p><pre>#training data<br>inp = [[0,1],[2,3],[0],[3]]<br>tgt = [1,1,-1,-1]<br><br>#validation data<br>inp_c = [[1],[2],[0,2],[1,3]]<br>tgt_c = [-1,-1,1,1]</pre><p>And let’s start training,</p><pre>#initial parameters<br>a = ainit.copy()<br><br>#result list<br>ar = []<br><br>h = 0.01<br>e = 0.01<br><br>#iterations<br>nsteps = 800<br><br>start = time.time()<br>for i in range(nsteps):<br>    r = np.random.randint(0,len(inp))<br><br>    c = ix(inp[r])+mera(a)<br>    loss = L(E(c.run()),tgt[r])<br><br>    ar.append(loss)<br><br>    at = [0 for i in range(len(a))]   <br>    for j in range(len(a)):<br>        aa = a.copy()<br>        aa[j] += h<br>        loss2 = L(E((ix(inp[r])+mera(aa)).run()),tgt[r])<br>        at[j] = a[j] - e*(loss2 - loss)/h<br><br>    a = at<br><br>plt.plot(ar)<br>plt.show()<br><br>print(time.time() - start)</pre><p>After the process, we get the figure and check the accuracy of the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*dyws5BOkUvpugqoNdO8oUA.png" /></figure><pre>#training accuracy<br>np.mean([E((ix(inp[i])+mera(a)).run())/tgt[i] for i in range(len(inp))])</pre><p>0.9760245973174358</p><pre>#validation accuracy<br>np.mean([E((ix(inp_c[i])+mera(a)).run())/tgt_c[i] for i in range(len(inp_c))])</pre><p>0.9769492668551134</p><h3>MPS</h3><p>Matrix Product State is the very basic structure of tensor network. Using U3 and CX we can implement this,</p><pre>|0&gt; --[input]--U3--*--<br>                   |<br>|0&gt; --[input]--U3--X--U3--*--<br>                          |<br>|0&gt; --[input]---------U3--X--U3--*<br>                                 |<br>|0&gt; --[input]----------------U3--X--[m]-[expt]-[loss]-[output]</pre><p>The model is,</p><pre>#MPS circuit<br>def mps(a):<br><br>    u = Circuit()<br>    u.u3(a[0],a[1],a[2])[0]<br>    u.u3(a[3],a[4],a[5])[1]<br>    u.u3(a[6],a[7],a[8])[2]<br>    u.u3(a[9],a[10],a[11])[3]<br>    u.cx[0,1]<br>    u.u3(a[12],a[13],a[14])[1]<br>    u.cx[1,2]<br>    u.u3(a[15],a[16],a[17])[2]<br>    u.cx[2,3]<br><br>    return u</pre><p>Basic parameters are the same as MERA structure</p><pre>start = time.time()<br><br>#initial parameters<br>a = ainit.copy()<br><br>#result list<br>ar = []<br><br>h = 0.01<br>e = 0.01<br><br>for i in range(nsteps):<br>    r = np.random.randint(0,len(inp))<br><br>    loss = L(E((ix(inp[r])+mps(a)).run()),tgt[r])<br>    ar.append(loss)<br><br>    at = [0 for i in range(len(a))]<br>    for j in range(len(a)):<br>        aa = a.copy()<br>        aa[j] += h<br>        loss2 = L(E((ix(inp[r])+mps(aa)).run()),tgt[r])<br>        at[j] = a[j] - e*(loss2 - loss)/h<br><br>    a = at<br><br>plt.plot(ar)<br>plt.show()<br>print(time.time() - start)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*5YbA0wZxjH_6dS7K6M6QDA.png" /></figure><p>And the accuracy is,</p><pre>#training accuracy<br>np.mean([E((ix(inp[i])+mps(a)).run())/tgt[i] for i in range(len(inp))])</pre><p>0.9697437828925157</p><pre>#validation accuracy<br>np.mean([E((ix(inp_c[i])+mps(a)).run())/tgt_c[i] for i in range(len(inp_c))])</pre><p>0.9696755262709482</p><h3>Future work</h3><p>Today we checked MERA/MPS model by scrath on blueqat. It looks that the optimization process will be better done by using existing deep learning tools like keras or torch.optim. Using these efficient tools we can get much more faster optimized process for quantum machine learning, because the training process is very heavy for state vector increase as 2^N for the number of qubit N.</p><p>This is very basic structure and small dataset. We need much more bigger data set and efficient model.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e12eea34c22" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mdr-inc/quantum-machine-learning-quantum-deep-learning-with-mera-mps-model-on-blueqat-quantum-computing-9e12eea34c22">Quantum Machine Learning (Quantum Deep Learning) with MERA/MPS model on Blueqat quantum computing…</a> was originally published in <a href="https://medium.com/mdr-inc">Blueqat (blueqat Inc. / former MDR Inc.)</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Autograd of quantum computing on pytorch and tensorflow with blueqat]]></title>
            <link>https://medium.com/mdr-inc/autograd-of-quantum-computing-on-pytorch-and-tensorflow-with-blueqat-76505fe2a27c?source=rss----8d311f05b2c5---4</link>
            <guid isPermaLink="false">https://medium.com/p/76505fe2a27c</guid>
            <category><![CDATA[quantum-computer]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[Yuichiro Minato]]></dc:creator>
            <pubDate>Fri, 01 May 2020 17:37:56 GMT</pubDate>
            <atom:updated>2020-05-01T17:37:15.325Z</atom:updated>
            <content:encoded><![CDATA[<p>For solving quantum chemistry or combinatorial optimization problem we usually use vqe or qaoa. This is quantum-classical hybrid system and to update or optimize the parameter in the circuit we usually use classical method. Here I just introduce way to optimize angle parameter using auto grad function of pytorch/tensorflow to update it using optimizer in these deep learning tools.</p><p><strong>Numerical differentiation</strong></p><p>With function f(x) and small change of h, we have,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*3sfbfQeLe0mqZpd8-8mIGQ@2x.jpeg" /></figure><p>An example of f(x) = x^2 , x=1 and h=0.1 the derivative is,</p><pre>x = 1<br>h = 0.1<br>((x+h)*(x+h)-x*x)/h</pre><pre>#=&gt;2.100000000000002</pre><p>On the network or circuit, there are lot of variational parameters. Partial differentiation is to get the derivative of one variable and the gradient see <br>these partial differentiation as vector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*J6DjvMtozFDLNchWKO-TxQ.jpeg" /></figure><p>Using this gradient we can update the value of each parameter going to the lower bound.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*MF719YnaKLzoueWeLShfxg.jpeg" /></figure><h3>Gradient Descent on blueqat</h3><p>Using our blueqat quantum sdk,</p><pre>!pip install blueqat</pre><p>Here is a simple example to get the both expectation value of &lt;psi | Z | psi&gt; and &lt;psi | X | psi&gt; using the ansatz as RY gate (I just selected this rotation gate that complex number not appear).</p><pre>from blueqat import Circuit<br>import matplotlib.pyplot as plt<br>import numpy as np<br>%matplotlib inline</pre><pre>def abs_sq(k):<br>    return np.square(np.abs(k))</pre><pre>#expectaion value of Z<br>def exptz(a):<br>    res = Circuit().ry(a)[0].run()<br>    expt = abs_sq(res[0])-abs_sq(res[1])<br>    return expt</pre><pre>#expectation value of X<br>def exptx(a):<br>    res = Circuit().ry(a)[0].h[0].run()<br>    expt = abs_sq(res[0])-abs_sq(res[1])<br>    return expt</pre><pre>#derivative of Z<br>def dfxz(a,h):<br>    return (exptz(a+h) - exptz(a))/h</pre><pre>#derivative of X<br>def dfxx(a,h):<br>    return (exptx(a+h) - exptx(a))/h</pre><pre>#grad on each<br>def gradz(a,h,e=1):<br>    for i in range(1000):<br>        a.append(a[i] - e*dfxz(a[i],h))<br>    return a</pre><pre>def gradx(a,h,e=1):<br>    for i in range(1000):<br>        a.append(a[i] - e*dfxx(a[i],h))<br>    return a</pre><pre>#initialize<br>ainit = [np.random.rand()*2*np.pi]<br>a = ainit.copy()<br>h = 0.001<br>e = 0.01</pre><pre>ra = gradz(a,h,e)<br>print(ra[-1])</pre><pre>plt.plot(list(map(exptz, ra)))<br>plt.show()</pre><pre>a = ainit.copy()</pre><pre>ra = gradx(a,h,e)<br>print(ra[-1])</pre><pre>plt.plot(list(map(exptx,ra)))<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*p7Lwd84XMeLSHOUIlojiTg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*fokWu_U33Ye-QB47yTMr3Q.png" /><figcaption>optimization of Z (left) and X(right)</figcaption></figure><p>This is using quantum variational principle to get the minimum value of each hamiltonian and it is VQE with gradient descent.</p><h3>Loss Function</h3><p>Instead of using variational principle here we try to use loss function.</p><pre>from blueqat import Circuit<br>import matplotlib.pyplot as plt<br>import numpy as np<br>%matplotlib inline</pre><pre>def abs_sq(k):<br>    return np.square(np.abs(k))</pre><pre>#expectation value<br>def expt(a):<br>    res = Circuit().ry(a)[0].run()<br>    return abs_sq(res[0])-abs_sq(res[1])</pre><pre>#loss function<br>def loss(res,tar):<br>    return np.square(res-tar)</pre><pre>#derivative<br>def dfx(a,h):<br>    return (loss(expt(a+h),-1) - loss(expt(a),-1))/h<br>#    return (expt(a+h)-expt(a))/h</pre><pre>#grad<br>def grad(a,h,e):<br>    for i in range(1000):<br>        a.append(a[i] - e*dfx(a[i],h))<br>    return a</pre><pre>#initizalize<br>ainit = [np.random.rand()*2*np.pi]<br>a = ainit.copy()<br>h = 0.001<br>e = 0.01</pre><pre>ra = grad(a,h,e)<br>print(ra[-1])</pre><pre>arr = [loss(expt(i),-1) for i in ra]</pre><pre>plt.plot(arr)<br>plt.show()</pre><pre>print(arr[-1])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*nuVplpmppZlxR3MeFRmfXQ.png" /></figure><p>This is simply going to zero value to minimize the loss function of target value as -1 for Z measurement.</p><p>If you want to change optimizers you can do like,</p><pre>#momentum sgd<br>def msgd(a,h,e,tgt,alpha):<br>    p_delta = 0<br>    for i in range(100):<br>        update = -e*dfx(a[i],h,tgt) + alpha*p_delta<br>        a.append(a[i] + update)<br>        p_delta = update<br>    return a</pre><pre>#initialization<br>a = ainit.copy()<br>h = 0.001<br>e = 0.01</pre><pre>alpha = 0.9<br>tgt = -1</pre><pre>result = msgd(a,h,e,tgt,alpha)<br>arr = [loss(expt(i),tgt) for i in result]</pre><pre>plt.plot(arr)<br>plt.show()</pre><p>This is momentum SGD, other famous optimizers like Adam, Adagrad, etc… can be implemented like that.</p><h3>autograd with pytorch</h3><p>If you implement all of these quantum circuit on pytorch tensor calculation, you can get the gradient using auto grad function.</p><pre>import torch</pre><p>The quantum logic gate on quantum computing is a matrix and one of tensor. We can use pytorch to see state vector as tensor vector and gate for tensor matrix.</p><p>To use the auto grad function, first you mention about the variable to get the grad.</p><pre>x = torch.ones(2, 2, requires_grad=True)</pre><p>and it is ready to get the gradient</p><pre>tensor([[1., 1.],<br>        [1., 1.]], requires_grad=True)</pre><p>by applying some calculation on tensor, you can get grad using .backward()</p><pre>y = x+3<br>z = y*y<br>out = z.mean()</pre><p>now out is a scalar,</p><pre>out.backward()</pre><p>and</p><pre>x.grad</pre><p>you can get</p><pre>tensor([[2., 2.],<br>        [2., 2.]])</pre><p>this is auto grad. Let’s see a simple auto grad with pytorch on vqe.</p><pre>import matplotlib.pyplot as plt<br>import torch.optim as optim<br>import numpy as np<br>%matplotlib inline</pre><pre>x = torch.tensor([1., 0.])<br>a = torch.tensor([0.2],requires_grad=True)<br>arr = []</pre><pre>#the first variable is list of paramters.<br>op = optim.Adam([a],lr=0.05)</pre><pre>for _ in range(100):<br>    y = [[torch.cos(a/2),-torch.sin(a/2)],[torch.sin(a/2),torch.cos(a/2)]]<br>    z = [x[0]*y[0][0]+x[1]*y[0][1],x[0]*y[1][0]+x[1]*y[1][1]]</pre><pre>expt = torch.abs(z[0])**2 - torch.abs(z[1])**2<br>    arr.append(expt)</pre><pre>op.zero_grad()<br>    expt.backward()<br>    op.step()<br>    <br>plt.plot(arr)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*iQhDL1DjrGVDCahPDdkT1g.png" /></figure><p>We used Adam for optimizer. Optimizing the expectation value of Z measurement on VQE.</p><p>With pytorch and optuna you can get the optimized hyper parameter on optimizer automatically using bayesian optimization and TPE/SMBO.</p><p>reference : <a href="https://qiita.com/yoshiyoshi0505/items/2e39ffdab305dba95164">https://qiita.com/yoshiyoshi0505/items/2e39ffdab305dba95164</a></p><pre>import torch<br>import matplotlib.pyplot as plt<br>import torch.optim as optim<br>import numpy as np<br>import optuna</pre><pre>%matplotlib inline</pre><pre>def get_optimizer(trial, params):<br>  optimizer_names = [&#39;Adam&#39;, &#39;MomentumSGD&#39;, &#39;rmsprop&#39;]<br>  optimizer_name = trial.suggest_categorical(&#39;optimizer&#39;, optimizer_names)<br>    <br>  weight_decay = trial.suggest_loguniform(&#39;weight_decay&#39;, 1e-5, 1e-3)</pre><pre>if optimizer_name == optimizer_names[0]: <br>    adam_lr = trial.suggest_loguniform(&#39;adam_lr&#39;, 1e-5, 1e-1)<br>    optimizer = optim.Adam(params, lr=adam_lr, weight_decay=weight_decay)<br>    <br>  elif optimizer_name == optimizer_names[1]:<br>    momentum_sgd_lr = trial.suggest_loguniform(&#39;momentum_sgd_lr&#39;, 1e-5, 1e-1)<br>    optimizer = optim.SGD(params, lr=momentum_sgd_lr, momentum=0.9, weight_decay=weight_decay)<br>  else:<br>    optimizer = optim.RMSprop(params)<br>  return optimizer</pre><pre>def Ygate(a):<br>    return [[torch.cos(a/2),-torch.sin(a/2)],[torch.sin(a/2),torch.cos(a/2)]]</pre><pre>def gate(x,A):<br>    return [x[0]*A[0][0] + x[1]*A[0][1], x[0]*A[1][0] + x[1]*A[1][1]]</pre><pre>def exptZ(z):<br>    return torch.abs(z[0])**2 - torch.abs(z[1])**2</pre><pre>x = torch.tensor([1.,0.])<br>arr = []</pre><pre>EPOCH = 500</pre><pre>def objective(trial):<br>    a = torch.tensor([0.2000000],requires_grad=True)<br>    b = torch.tensor([0.2000000],requires_grad=True)</pre><pre>op = get_optimizer(trial,[a,b])<br>    j = 0<br>    <br>    for i in range(EPOCH):<br>        y1 = Ygate(a)<br>        y2 = Ygate(b)<br>        z1 = gate(x, y1)<br>        z2 = gate(z1, y2)<br>        <br>        loss = (exptZ(z2)+1)**2<br>        op.zero_grad()<br>        loss.backward()<br>        op.step()<br>        j += 1<br>        <br>        if loss &lt; 0.0001:<br>            break</pre><pre>return j</pre><pre>TRIAL_SIZE = 100<br>study = optuna.create_study()<br>study.optimize(objective, n_trials=TRIAL_SIZE)</pre><p>as one of example of solution,</p><pre>study.best_params</pre><pre>#=&gt;{&#39;optimizer&#39;: &#39;MomentumSGD&#39;,<br> &#39;weight_decay&#39;: 4.6361008402133846e-05,<br> &#39;momentum_sgd_lr&#39;: 0.07830196695880046}</pre><p>By using it, easily get the optimized hyper parameter.</p><pre>import torch<br>import matplotlib.pyplot as plt<br>import torch.optim as optim<br>import numpy as np<br>%matplotlib inline</pre><pre>def Ygate(a):<br>    return [[torch.cos(a/2),-torch.sin(a/2)],[torch.sin(a/2),torch.cos(a/2)]]</pre><pre>def gate(x,A):<br>    return [x[0]*A[0][0] + x[1]*A[0][1], x[0]*A[1][0] + x[1]*A[1][1]]</pre><pre>def exptZ(z):<br>    return torch.abs(z[0])**2 - torch.abs(z[1])**2</pre><pre>x = torch.tensor([1.,0.])<br>a = torch.tensor([0.2000000],requires_grad=True)<br>arr = []</pre><pre>op = optim.Adam([a],lr=0.05)</pre><pre>for _ in range(100):<br>    y = Ygate(a)<br>    z = gate(x, y)<br>    <br>    expt = exptZ(z)<br>    arr.append(expt)</pre><pre>op.zero_grad()<br>    expt.backward()<br>    op.step()<br>    <br>plt.plot(arr)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*iQhDL1DjrGVDCahPDdkT1g.png" /></figure><h3>Gradient Tape of Tensorflow</h3><p>On tensorflow we can do almost the same,</p><pre>import tensorflow as tf<br>import matplotlib.pyplot as plt<br>%matplotlib inline</pre><pre>def Ry(a):<br>    return [[tf.math.cos(a/2),-tf.math.sin(a/2)],[tf.math.sin(a/2),tf.math.cos(a/2)]]</pre><pre>def exptZ(x,a):<br>    z = tf.tensordot(x,Ry(a),1)<br>    return tf.abs(z[0])**2 - tf.abs(z[1])**2</pre><pre>a = tf.Variable(.2)<br>x = tf.constant([1.,0.])</pre><pre>opt = tf.keras.optimizers.SGD(lr=.1)<br>arr= []</pre><pre>expt = lambda : exptZ(x,a)</pre><pre>for _ in range(100):<br>    arr.append(expt().numpy())<br>    opt.minimize(expt, var_list=[a])</pre><pre>plt.plot(arr)<br>plt.show()</pre><pre>print(arr[-1])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*WqHCBNi-FxT9PeFdG6br4Q.png" /></figure><h3>Ready for quantum machine learning</h3><p>By using these gradient, we can do quantum machine learning with loss function (this time we used variational method). Google is offering tensorflow quantum for this purpose. Pytorch and Tensorflow is not supporting the full complex number on calculation, so we need some additional support for it. Quantum machine learning will be developed in next 3years I think.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76505fe2a27c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mdr-inc/autograd-of-quantum-computing-on-pytorch-and-tensorflow-with-blueqat-76505fe2a27c">Autograd of quantum computing on pytorch and tensorflow with blueqat</a> was originally published in <a href="https://medium.com/mdr-inc">Blueqat (blueqat Inc. / former MDR Inc.)</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>