<?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[Stories by David Morcuende on Medium]]></title>
        <description><![CDATA[Stories by David Morcuende on Medium]]></description>
        <link>https://medium.com/@morcu?source=rss-782cc2dab484------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*uir3cmhczEoHUWNsMCGJ5A.jpeg</url>
            <title>Stories by David Morcuende on Medium</title>
            <link>https://medium.com/@morcu?source=rss-782cc2dab484------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 12:06:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@morcu/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Solving a Sudoku as a Coloring Problem using Qiskit and QAOA]]></title>
            <link>https://morcu.medium.com/solving-a-sudoku-as-a-coloring-problem-using-qiskit-and-qaoa-ef27720a85b0?source=rss-782cc2dab484------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef27720a85b0</guid>
            <category><![CDATA[sudoku]]></category>
            <category><![CDATA[qiskit]]></category>
            <category><![CDATA[graph]]></category>
            <category><![CDATA[quantum-computing]]></category>
            <category><![CDATA[qaoa]]></category>
            <dc:creator><![CDATA[David Morcuende]]></dc:creator>
            <pubDate>Thu, 28 Sep 2023 08:30:01 GMT</pubDate>
            <atom:updated>2023-09-28T08:30:01.947Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vBi73WeB8jr8EzPV2MtOhg.png" /></figure><blockquote>Dive into the innovative realm where Sudoku puzzles meet quantum computing. Discover how Qiskit and QAOA can transform a classic game into a colorful quantum challenge.</blockquote><h3>Motivation:</h3><p>Sudoku, a logic-based number-placement puzzle, has entertained and challenged individuals for decades. Its timeless simplicity paired with intricate logical sequences have made it a favorite amongst many. However, beyond being a mere puzzle, Sudoku has implications in computer science, particularly when treated as a coloring problem. This article dives into how we can leverage the power of quantum computers, using Qiskit and the Quantum Approximate Optimization Algorithm (QAOA), to solve a Sudoku puzzle.</p><h3>The Problem: Sudoku</h3><p>A Sudoku puzzle is represented as a square grid divided into smaller squares called cells. The challenge is to fill each cell with a number, obeying specific rules to ensure a unique solution. In a standard 3x3 Sudoku, the grid consists of 9x9 cells, divided into 9 blocks of 3x3 cells. The rules are:</p><ol><li>Every row must have numbers 1 to 9, with no repetition.</li><li>Every column must also have numbers 1 to 9, without repetition.</li><li>Each of the 9 blocks must have numbers 1 to 9, with no repetition.</li></ol><p>For our exploration, we will use a smaller 2x2 Sudoku, which is a 4x4 grid with rules analogous to the standard 3x3 version.</p><h3>Sudoku as a Coloring Problem:</h3><p>At its core, Sudoku can be seen as a graph coloring problem. Here, each cell represents a node, and nodes are connected by edges if they belong to the same row, column, or block. The challenge then is to color each node such that no two adjacent nodes (nodes connected by an edge) have the same color. In the Sudoku context, colors are numbers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*S5bSqV84MbdhabOAfJI-Gg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*yaVFRoyqwgPPUPkX1d6kHQ.png" /><figcaption>Solved sudoku alongside its graph representation with colors.</figcaption></figure><p><em>Note: In the Sudoku graph image, the nodes are connected to all the nodes in their row and column. That is, the first node in position 0 is connected with the nodes in positions 1, 2, and 3. It is also connected with the nodes in its cell, at positions 1, 4, and 5, as well as with the nodes in its column, at positions 4, 8, and 12.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/125/1*agKpZeRWGpptgdg6BrOpig.png" /><figcaption>Positions in the 4x4 grid</figcaption></figure><h3>QUBO: Quadratic Unconstrained Binary Optimization:</h3><p>To translate our Sudoku problem into a language quantum computers can understand, we use QUBO. A QUBO problem aims to find a vector of binary variables that minimizes a quadratic function. For Sudoku, our binary variables represent whether a particular number (color) is present in a given cell or not.</p><h3>Sudoku Constraints to QUBO:</h3><p>The representation of QUBO (Quadratic Unconstrained Binary Optimization) for Sudoku constraints can be quite intricate, but I’ll try to detail it in simpler terms.</p><p>The QUBO representation for Sudoku constraints in a 4x4 grid involves defining binary variables X<em>ijk</em>​ where:</p><ul><li><em>i</em> represents the row index (1–4).</li><li><em>j</em> represents the column index (1–4).</li><li><em>k</em> represents the number (1–4).</li></ul><p>This encoding means that if a cell at the <em>ith</em> row and <em>jth</em> column contains the number <em>k</em>, then X<em>ijk</em>​ would be 1, otherwise 0.</p><p>Let’s break down the QUBO formulation for a 4x4 Sudoku puzzle.</p><ol><li><strong>Cell Constraint</strong>: This ensures that each cell contains exactly one number.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/223/1*RCKNcexvz3xVDcnNs19iug.gif" /></figure><p><strong>2. Row Constraint:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/1*9vEkchGisZy2-Wwb73lpxw.gif" /></figure><p><strong>3. Column Constraint</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/246/1*eGpqGiAk3OKVR0JCnyqd_g.gif" /></figure><p><strong>4. Subgrid Constraint</strong>: For a 4x4 Sudoku, there are four 2x2 subgrids. This ensures that no number repeats within any subgrid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*p9aoCdtnRnlXbiM26T_46w.gif" /></figure><p>Here, <em>a</em> and <em>b</em> iterate over the subgrids, and <em>δi</em> and <em>δj</em> iterate over the cells within a subgrid.</p><p>The complete QUBO Hamiltonian for the 4x4 Sudoku puzzle is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/1*DHR1I799qH6Is-4DSQPIGA.gif" /></figure><p>This Hamiltonian will be minimized when all Sudoku constraints are satisfied.</p><h3>Quantum Approximate Optimization Algorithm (QAOA):</h3><p>The Quantum Approximate Optimization Algorithm (QAOA) is a quantum algorithm designed to find approximate solutions to combinatorial optimization problems. The central idea behind QAOA is to harness the power of quantum interference to explore the vast solution space of optimization problems efficiently.</p><p>How it Works:</p><ol><li><strong>Encoding the Problem</strong>: The optimization problem is encoded as a QUBO (Quadratic Unconstrained Binary Optimization) or Ising model, which can then be represented by a Hamiltonian, <em>H</em>. The Hamiltonian is a crucial concept in quantum mechanics and, in this context, defines the energy landscape of the problem.</li><li><strong>Quantum Evolution</strong>: Starting from an easily prepared quantum state, the quantum system is evolved under the influence of two Hamiltonians: the problem Hamiltonian <em>H</em> and a mixer Hamiltonian. These evolutions are parameterized by angles, which are varied classically to find the optimal quantum state that represents the solution.</li><li><strong>Sampling and Measurement</strong>: After the quantum evolution, the quantum state is measured to obtain a sample solution. Repeated measurements provide different solutions, and the best one can be chosen as the output.</li></ol><p>Implementations: Many quantum software platforms, such as Qiskit, provide tools and libraries to implement the QAOA and test it on quantum hardware.</p><h3>COBYLA Optimizer:</h3><p>COBYLA (Constrained Optimization BY Linear Approximations) is an optimizer that doesn’t require gradient information and is thus well-suited for noisy quantum computations, making it a popular choice in quantum computing.</p><h3>THE Solution:</h3><p>Once we grasp the fundamental concepts and methodologies outlined above, we can then apply them to a simplified problem. The primary reason for this simplification is to sidestep the limitations posed by dimensionality constraints when executing the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*IZlHzalT8hMlKh3JzJh4ag.png" /></figure><p>To visually represent our problem as a graph, the code provided below illustrates how a smaller graph can be perceived and utilized in a manner analogous to our main problem.</p><pre>def draw_graph(n, e):<br>    G = nx.Graph()<br>    G.add_nodes_from([i for i in range(1, n+1)])<br>    G.add_edges_from(e)<br>    nx.draw(G, with_labels=True)<br>    return G<br><br>n = 5<br>e = [(1,2), (1,5), (2,3), (2,4), (2,5), (3,4), (4,5)]<br>G = draw_graph(n,e)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*LFo2OjDMk888JsB8aMgC8Q.png" /></figure><h4>Constructing the QUBO Model for Graph Coloring</h4><p>To transform the graph coloring problem into a Quadratic Unconstrained Binary Optimization (QUBO) format, we need a matrix representation. This matrix, denoted as Q, will act as a cost function where the solution attempts to minimize the “penalties” or conflicts between nodes with the same colors.</p><pre><br>num_nodes = G.number_of_nodes()<br>num_color = 3<br>P = 4<br>Q = np.eye(num_nodes * num_color)<br>for i in range(1, num_nodes +1):<br>    l = num_color * i + 1<br>    for j in range(l-num_color,l):<br>        for k in range(l-num_color, l):<br>            if k==j:<br>                Q[j-1][k-1] = -P<br>            else:<br>                Q[j-1][k-1] = P<br><br><br><br>for i, j in G.edges:<br>    for k in range(1, num_color+1):<br>        # (node -1) * num_color + k<br>        m = (i-1) * num_color + k<br>        o = (j-1) * num_color + k<br>        Q[m-1][o-1] = P/2<br>        Q[o-1][m-1] = P/2        <br><br>print(Q)<br></pre><p>The matrix Q produced:</p><pre>[[-4.  4.  4.  2.  0.  0.  0.  0.  0.  0.  0.  0.  2.  0.  0.]<br> [ 4. -4.  4.  0.  2.  0.  0.  0.  0.  0.  0.  0.  0.  2.  0.]<br> [ 4.  4. -4.  0.  0.  2.  0.  0.  0.  0.  0.  0.  0.  0.  2.]<br> [ 2.  0.  0. -4.  4.  4.  2.  0.  0.  2.  0.  0.  2.  0.  0.]<br> [ 0.  2.  0.  4. -4.  4.  0.  2.  0.  0.  2.  0.  0.  2.  0.]<br> [ 0.  0.  2.  4.  4. -4.  0.  0.  2.  0.  0.  2.  0.  0.  2.]<br> [ 0.  0.  0.  2.  0.  0. -4.  4.  4.  2.  0.  0.  0.  0.  0.]<br> [ 0.  0.  0.  0.  2.  0.  4. -4.  4.  0.  2.  0.  0.  0.  0.]<br> [ 0.  0.  0.  0.  0.  2.  4.  4. -4.  0.  0.  2.  0.  0.  0.]<br> [ 0.  0.  0.  2.  0.  0.  2.  0.  0. -4.  4.  4.  2.  0.  0.]<br> [ 0.  0.  0.  0.  2.  0.  0.  2.  0.  4. -4.  4.  0.  2.  0.]<br> [ 0.  0.  0.  0.  0.  2.  0.  0.  2.  4.  4. -4.  0.  0.  2.]<br> [ 2.  0.  0.  2.  0.  0.  0.  0.  0.  2.  0.  0. -4.  4.  4.]<br> [ 0.  2.  0.  0.  2.  0.  0.  0.  0.  0.  2.  0.  4. -4.  4.]<br> [ 0.  0.  2.  0.  0.  2.  0.  0.  0.  0.  0.  2.  4.  4. -4.]]</pre><p>In this matrix, each node in the graph has its own set of binary variables representing different colors. The goal is to minimize the value produced by this matrix multiplied by a vector of our binary variables.</p><h4>Modeling with DOcplex</h4><p><strong>DOcplex</strong> is a native Python modeling library for optimization. Here, we model our QUBO problem using DOcplex and then convert it to a quantum-friendly format:</p><pre>from docplex.mp.model import Model<br>from qiskit_optimization.translators import from_docplex_mp<br><br>mdl = Model(name =&quot;GC&quot;)<br>x = [mdl.binary_var(&#39;x%s&#39; % i) for i in range (len(Q))]<br>objective = mdl.sum([x[i]* Q[i,j] * x[j] for i in range(len(Q)) for j in range(len(Q))])<br>mdl.minimize(objective)<br>qp = from_docplex_mp(mdl)<br><br>print(qp.prettyprint())</pre><pre>Problem name: GC<br><br>Minimize<br>  -4*x0^2 + 8*x0*x1 + 4*x0*x12 + 8*x0*x2 + 4*x0*x3 - 4*x1^2 + 4*x1*x13 + 8*x1*x2<br>  + 4*x1*x4 - 4*x10^2 + 8*x10*x11 + 4*x10*x13 - 4*x11^2 + 4*x11*x14 - 4*x12^2<br>  + 8*x12*x13 + 8*x12*x14 - 4*x13^2 + 8*x13*x14 - 4*x14^2 + 4*x2*x14 - 4*x2^2<br>  + 4*x2*x5 + 4*x3*x12 - 4*x3^2 + 8*x3*x4 + 8*x3*x5 + 4*x3*x6 + 4*x3*x9<br>  + 4*x4*x10 + 4*x4*x13 - 4*x4^2 + 8*x4*x5 + 4*x4*x7 + 4*x5*x11 + 4*x5*x14<br>  - 4*x5^2 + 4*x5*x8 - 4*x6^2 + 8*x6*x7 + 8*x6*x8 + 4*x6*x9 + 4*x7*x10 - 4*x7^2<br>  + 8*x7*x8 + 4*x8*x11 - 4*x8^2 + 8*x9*x10 + 8*x9*x11 + 4*x9*x12 - 4*x9^2<br><br>Subject to<br>  No constraints<br><br>  Binary variables (15)<br>    x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14</pre><p>This produces a clear representation of our problem, highlighting the objective function (which we wish to minimize).</p><h4>Seeking Solutions with QAOA</h4><p>Quantum Approximate Optimization Algorithm (QAOA) is a quantum algorithm that helps find the solution to combinatorial problems like ours. With Qiskit, we can run QAOA:</p><pre>algorithm_globals.random_seed = 12345<br>qaoa_mes = QAOA(sampler=Sampler(), optimizer=COBYLA())<br>qaoa = MinimumEigenOptimizer(qaoa_mes)<br><br>qaoa_result = qaoa.solve(qp)<br>print(qaoa_result.prettyprint())</pre><pre>objective function value: -20.0<br>variable values: x0=0.0, x1=1.0, x2=0.0, x3=0.0, x4=0.0, x5=1.0, x6=1.0, x7=0.0, x8=0.0, x9=0.0, x10=1.0, x11=0.0, x12=1.0, x13=0.0, x14=0.0<br>status: SUCCESS</pre><p>This tells us the most optimal solution found by the QAOA: an objective function value of -20, with specific binary variable values.</p><h4>Assigning Colors to Nodes</h4><p>Given our results, how do we interpret them in terms of our graph coloring problem? With the function assign_color, we can take the quantum result and convert it into recognizable colors:</p><pre>def assign_color(result, num_color):<br>    colors = [&quot;BLUE&quot;, &quot;GREEN&quot;, &quot;RED&quot;, &quot;YELLOW&quot;, &quot;ORANGE&quot;, &quot;PINK&quot;, &quot;BLACK&quot;, &quot;BROWN&quot;, &quot;WHITE&quot;, &quot;PURPLE&quot;, &quot;VIOLET&quot;]<br>    color_map = list()<br>    for pos, val in enumerate(result.x):<br>      if int(val) == 1:    <br>            node = pos//num_color + 1<br>            color = pos%num_color<br>            color_map.append(colors[color])<br>            print(&quot;for node %s with bin var %s the assigned color is %s&quot;%(node, pos, colors[color]))<br>    return color_map<br>    <br>qaoa_color_map = assign_color(qaoa_result,3)</pre><pre>for node 1 with bin var 1 the assigned color is GREEN<br>for node 2 with bin var 5 the assigned color is RED<br>for node 3 with bin var 6 the assigned color is BLUE<br>for node 4 with bin var 10 the assigned color is GREEN<br>for node 5 with bin var 12 the assigned color is BLUE</pre><p>Each node in our graph has now been assigned a unique color such that adjacent nodes do not have the same color — solving our graph coloring problem!</p><h4>Visualizing the Solution</h4><p>Lastly, to make this journey visually appealing, we can draw our graph with the colored nodes:</p><pre><br>def draw_color_graph(n, e, color_map):<br>    G= nx.Graph()<br>    G.add_nodes_from([i for i in range(1, n+1)])<br>    G.add_edges_from(e)<br>    nx.draw(G, node_color=color_map, node_size=600, with_labels= True)<br><br>    return G<br><br>gra = draw_color_graph(n, e, qaoa_color_map)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*QN5rqEi141EIYM3mMgw8tg.png" /></figure><p>This graphical representation showcases the power and utility of quantum computing in solving problems like graph coloring. Not only does it provide a solution, but it also ensures that the solution is both aesthetically pleasing and meets our conditions of no two adjacent nodes sharing the same color!</p><p><em>Note: For the actual solution of the Sudoku problem, these calculations would need to be made considering that there is an initial state where certain cells have been provided to us filled with a number.</em></p><h3>Summary and Conclusion:</h3><p>In this exploration, we’ve viewed Sudoku, a traditionally simple logic puzzle, through the lens of quantum computing and combinatorial optimization. We demonstrated how a Sudoku puzzle can be framed as a graph coloring problem and then modeled for quantum computation using QUBO. Leveraging the capabilities of Qiskit and the QAOA algorithm, we sought solutions that respect Sudoku’s inherent constraints. This approach not only offers an intriguing perspective on solving Sudoku but also underscores the vast potential of quantum algorithms in tackling complex combinatorial challenges. As quantum technology continues to evolve, its applicability in diverse domains, from games to real-world problems, becomes increasingly evident.</p><p>Notebook: <a href="https://github.com/Morcu/sudoku-colouring-problem-QAOA/blob/main/Sudoku_QAOA.ipynb">https://github.com/Morcu/sudoku-colouring-problem-QAOA/blob/main/Sudoku_QAOA.ipynb</a></p><h3>Diving Deeper: Practical Applications of the Coloring Problem</h3><p>While the coloring problem has its roots in pure mathematics, it’s fascinating to see how it intertwines with real-world scenarios. When people hear about the coloring problem, they might picture a playful activity involving crayons and a coloring book. However, in the context of graph theory and combinatorics, the coloring problem plays a crucial role in solving some of the most intricate issues we face in diverse fields. Here are some of the practical applications:</p><ol><li><strong>Frequency Assignment for Cellular Networks</strong>: In the realm of telecommunications, the coloring problem aids in the frequency assignment for cell towers. Ensuring that two geographically close towers don’t use the same frequency band is crucial to avoid interference. This problem is analogous to ensuring neighboring nodes (representing towers) in a graph don’t share the same color (frequency).</li><li><strong>Register Allocation in Computer Compilers</strong>: When a computer program gets compiled, the compiler must allocate memory registers for variables. If two variables are used at the same time, they can’t be stored in the same register. The graph coloring problem helps in efficiently allocating these registers, where each variable is a node, and an edge indicates concurrent use.</li><li><strong>Examination Scheduling</strong>: In educational institutions, scheduling exams so that no two subjects with common students occur at the same time can be represented as a coloring problem. Here, subjects are nodes, and an edge between two nodes indicates that there’s a common student between those subjects.</li><li><strong>Traffic Signal Schedulin</strong>g: Imagine traffic intersections where signals need to be scheduled in a way that they don’t conflict with one another. By representing each signal as a node and edges between conflicting signals, the coloring problem can help in optimizing signal timings.</li><li><strong>Sport Scheduling</strong>: In sports leagues, teams need to be scheduled in a way that they don’t play multiple games simultaneously or in quick succession. This scheduling issue can be visualized as a coloring problem, ensuring adequate rest and logistical feasibility.</li><li><strong>Map Coloring</strong>: This is the classic problem that gave birth to the entire concept. It revolves around coloring a map in such a way that no two adjacent regions share the same color. This has implications not just in cartography but in determining territories, zones, or divisions in various applications.</li></ol><p>These are just a few glimpses into the myriad ways in which the coloring problem, a concept that seems so abstract at first, finds its practical footing in our day-to-day world. From ensuring clear cell phone calls to optimizing computer programs, this mathematical challenge continues to shape and improve numerous aspects of modern life.</p><h3>Links</h3><ul><li><a href="https://qiskit.org/">https://qiskit.org/</a></li><li><a href="https://en.wikipedia.org/wiki/Sudoku">https://es.wikipedia.org/wiki/Sudoku</a></li><li><a href="https://qiskit.org/ecosystem/optimization/locale/es_UN/tutorials/11_using_classical_optimization_solvers_and_models.html">https://qiskit.org/ecosystem/optimization/locale/es_UN/tutorials/11_using_classical_optimization_solvers_and_models.html</a></li><li><a href="https://qiskit.org/documentation/stubs/qiskit.algorithms.QAOA.html">https://qiskit.org/documentation/stubs/qiskit.algorithms.QAOA.html</a></li><li><a href="https://leeds-faculty.colorado.edu/glover/Quantum%20Bridge%20Analytics%20I%20-%20QBA%20Part%201.pdf">https://leeds-faculty.colorado.edu/glover/Quantum%20Bridge%20Analytics%20I%20-%20QBA%20Part%201.pdf</a></li><li><a href="https://anonymousket.medium.com/quantum-optz-graph-coloring-b820d7bfdca3">https://anonymousket.medium.com/quantum-optz-graph-coloring-b820d7bfdca3</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef27720a85b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why I Built a Provider for Accessing Amazon Braket Hardware With Qiskit]]></title>
            <link>https://medium.com/qiskit/why-i-built-a-provider-for-accessing-amazon-braket-hardware-with-qiskit-c37f723730e3?source=rss-782cc2dab484------2</link>
            <guid isPermaLink="false">https://medium.com/p/c37f723730e3</guid>
            <category><![CDATA[qiskit]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[quantum-computing]]></category>
            <category><![CDATA[amazon-web-services]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[David Morcuende]]></dc:creator>
            <pubDate>Fri, 10 Jun 2022 14:02:47 GMT</pubDate>
            <atom:updated>2022-06-23T10:10:53.700Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*49Kb3-W7jdeAxtyYIGF07w.png" /><figcaption>Qiskit jobs run on Amazon Braket (Screenshot: David Morcuende)</figcaption></figure><p>Qiskit’s goal is to build a global quantum computing community — so it made sense to me that Qiskitters should be able to use the Qiskit software development kit to program any quantum computer. That’s why I connected Qiskit to the Amazon Braket service.</p><p>Like <a href="https://qiskit.org/documentation/apidoc/ibmq_runtime.html">Qiskit Runtime</a>, Amazon Braket is a fully managed quantum computing service from AWS that offers access to quantum computing hardware. Programming the processors on Braket once required learning a different programming framework. So, as part of my <a href="https://github.com/qiskit-advocate/qamp-spring-22/issues/6">Qiskit Advocate Mentorship Program project</a>, I built a provider that allows users to program Braket backends, both real quantum hardware and simulators, using Qiskit. I hope that this effort will help build an even stronger Qiskit community — and help strengthen the quantum community as a whole.</p><p>But first, about me: I’m a computer scientist based in Madrid, Spain. My coding story began with machine learning and artificial intelligence, especially with virtual assistants, and I moved on to building other things, such as founding my own startup. I soon realized that I wanted to work on projects and products that helped people. I found out about IBM Quantum and attended a Qiskit hackathon, where I met a lot of other folks working in quantum. I started studying quantum computing on my own, and eventually I became a Qiskit Advocate. What I’ve loved about being a part of the Qiskit Community is that even someone like me without much of a physics background can make an impact with the help of a strong, welcoming community.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_lLCQmfH6MR-vrkaHDykYA.png" /><figcaption>Braket processors and simulators (Screenshot: David Morcuende)</figcaption></figure><p>As a Qiskit Advocate, I was able to take part in the Qiskit Advocate Mentorship Program and saw that connecting Qiskit to Amazon Braket was as a potential project. I knew that there were a lot of quantum frameworks, a lot of devices, and a lot of platforms, but not many links connecting them. My project envisioned allowing Qiskit users to access other devices without having to learn a new software development kit, beginning with the hardware offered as part of Amazon Braket.</p><p>My mentor Iskandar Sitdikov and I first had to learn about Braket. Braket has a python-based SDK, plus local backends executed on a local computer and backends available on the cloud. We began to translate it all into Qiskit code. We built a provider — essentially the mediator between AWS and Qiskit that maps Braket commands to the corresponding Qiskit commands. All of this required creating translations between the Qiskit gates and the Braket gates. Perhaps the biggest challenge was simply figuring out how to connect to another cloud service. We had to read a lot of documentation to ensure we were doing everything right.</p><p>We also made sure that the Qiskit provider would allow us to run Amazon Braket Hybrid Jobs, which enable users to run algorithms incorporating both quantum and classical computation — similar to what Qiskit Runtime does. Hybrid Jobs similarly containerizes programs and gives priority access to quantum processing units for these jobs.</p><p>I’m excited about this project because it fits perfectly into Qiskit’s mission to democratize quantum computing. The IBM Quantum hardware we typically access with Qiskit consists solely of superconducting processors, and accessing other architectures such as photonic quantum computers, trapped ions, or even quantum annealers all required learning a new language or a new framework. But being able to access any of these hardware architectures with one programming language helps everyone interested in quantum, from developers hoping to learn how to program different processors to scientists looking for an easy way to benchmark one processor against another.</p><p>I can’t wait to see what developers can do with these new providers and backends. You can check out a tutorial on how to get started using the Qiskit Braket provider here:</p><p><a href="https://github.com/qiskit-community/qiskit-braket-provider/blob/main/docs/tutorials/0_tutorial_qiskit-braket-provider_overview.ipynb">qiskit-braket-provider/0_tutorial_qiskit-braket-provider_overview.ipynb at main · qiskit-community/qiskit-braket-provider</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c37f723730e3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/qiskit/why-i-built-a-provider-for-accessing-amazon-braket-hardware-with-qiskit-c37f723730e3">Why I Built a Provider for Accessing Amazon Braket Hardware With Qiskit</a> was originally published in <a href="https://medium.com/qiskit">Qiskit</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Paquetes de Python]]></title>
            <link>https://morcu.medium.com/paquetes-de-python-18d544b3c0f9?source=rss-782cc2dab484------2</link>
            <guid isPermaLink="false">https://medium.com/p/18d544b3c0f9</guid>
            <category><![CDATA[virtualenv]]></category>
            <category><![CDATA[pipenv]]></category>
            <category><![CDATA[virtual-environment]]></category>
            <category><![CDATA[poetry]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[David Morcuende]]></dc:creator>
            <pubDate>Fri, 04 Mar 2022 15:48:15 GMT</pubDate>
            <atom:updated>2022-03-04T15:48:15.534Z</atom:updated>
            <content:encoded><![CDATA[<p>Que es esto de los paquetes de python y como los gestiono.</p><p>Python tiene muchas cosas buenas, pero la gestion de modulos no es su fuerte….</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*gCarEe5KH4zUuKltIe18Dw.png" /><figcaption><a href="https://xkcd.com/1987/">https://xkcd.com/1987/</a></figcaption></figure><p>Cada vez que queremos usar una libreria en python tenemos que instalarla</p><pre>pip install pandas</pre><p>Pero que es lo que esta haciendo en realidad:</p><ol><li>Bajarselo de un repo, por defecto Pypi</li><li>Instalarlo, normalmente en una ruta del tipo</li></ol><p>Location: /usr/local/lib/python2.7/site-packages</p><p>Pip show NOMBRE_DEL_PAQUETE te muestra donde lo instala</p><h4>Instala local no global</h4><p>Pero esto es una mala praxis ya que el paquete se instala globalmente y muchos paquetes dependen de otros y las versiones de los mismos pueden colisionar, incluso si estas desarrollando una aplicación quieres que funcione con versiones especificas de Python.</p><p>Para no tener que volarnos la cabeza con versiones y paquetes llegan para salvarnos <strong>virtualenv, pipenv y poetry</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*PZBhjqesxUAgmSLzLFSYmQ.gif" /></figure><h4>Virtualenv</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*FjqLQ08MEk6jSKxpzjCcVw.jpeg" /></figure><blockquote>Create, activate, install, repeat</blockquote><p>Es una herramienta para crear entornos de python aislados, es decir entornos limpios en los que poder instalar paquetes sin que interfieran con otras instalaciones u otros proyectos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*Au7eQ3Ap71KIlsE-mBFm5g.gif" /></figure><p>Principales problemas:</p><ul><li>Es difícil manejar varias versiones de python</li><li>Hay que acordarse de activarlo</li><li>Dónde guardas la carpeta que contiene el entorno? En el propio directorio de codigo de la aplicación?</li><li>Si tienes un espacio aka “ “ en alguna parte de la ruta donde esta el entorno virtual, Python se pierde y no es capaz de activarlo</li><li>Hay que actualizar los requisitos de los paquetes vease requirements.txt de forma manual.</li></ul><h4>Pipenv</h4><p>Para salvarnos tenemos a Pipenv</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kEDHRc4rKuNlWHL-VaQfvA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*7_F_zIPOsy60EEYAZiCoEw.gif" /></figure><p>Ventajas:</p><ul><li>Puedes settear versiones</li><li>No tienes que preocuparte por dónde crear el entorno</li><li>Los paquetes se actualizan automáticamente <em>Pipfile</em> &amp;<em> Pipfile.lock</em></li></ul><h4>Poetry</h4><p>Poetry tambien viene a salvarnos</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*Lh4EnzbOjNr4qwAMzmVHBg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*6DksZQB0mcmAmxj4YRBhzA.gif" /></figure><p>Ventajas:</p><ul><li>Puedes settear versiones</li><li>No tienes que preocuparte por donde crear el entorno</li><li>Los paquetes se actualizan automáticamente <em>pyproject.toml</em></li><li>ADEMÁS puedes publicar los paquetes directamente a Pypi</li></ul><h4>Pipenv &amp; Poetry</h4><p>Entonces si Pipenv y Poetry nos solucionan el problema cual usamos???</p><p>Aunque los 2 hagan prácticamente lo mismo hay que tener en cuenta ciertas cosas:</p><ol><li>Pipenv es muuuuuuuuuuuy lento</li><li>Pipenv falla al resolver dependencias sobre todo en paquetes en alfa o beta</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*H2Fa4zjPOBG0V9wgPSnhjQ.png" /></figure><p><strong>Tenemos un claro vencedor POETRY</strong></p><p>Peeero solo unos apuntes:</p><ul><li>No instales poetry en el mismo entrono en el que tienes instalados los paquetes python de tu aplicación ya que poetry ES una aplicacion Python, no confundas sus dependencias con las de tus aplicaciones</li><li>Es opensource contribuye añadiendo descripciones de bugs o features, incluso desarrolla!!!</li><li>Afirmacion controvertida, si quieres entornos de python aislados usa Docker</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*e_nd6d8q-utEdoSxDCc7Mw.gif" /></figure><h4>ANEXO, REGALO o COMO QUIERAS LLAMARLO</h4><p>Si lo único que quieres es probar algo rapido y no volver a ver ese maldito entorno virtual, os presento….</p><h4>Dispenv- Disposable Python Environments</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*eu9YjhhT-3TNkCgj6mcTkQ.gif" /></figure><h4>Contact</h4><ul><li><a href="/service/mailto:david.morcuende.c@gmail.com">david.morcuende.c@gmail.com</a></li><li><a href="https://www.linkedin.com/in/david-morcuende-cantador-883a22155/">David Morcuende Linkedin</a></li></ul><h4>Buy me a coffe</h4><figure><a href="https://www.paypal.com/donate?hosted_button_id=7P4X4ZB4UN5VE"><img alt="" src="https://cdn-images-1.medium.com/max/147/1*wuk9g08uOqNokdUB0_lLHw.gif" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18d544b3c0f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to approach a text classification problem (part 3/3)]]></title>
            <link>https://morcu.medium.com/how-to-approach-a-text-classification-problem-part-3-3-51d706a51948?source=rss-782cc2dab484------2</link>
            <guid isPermaLink="false">https://medium.com/p/51d706a51948</guid>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[David Morcuende]]></dc:creator>
            <pubDate>Fri, 27 Aug 2021 09:03:52 GMT</pubDate>
            <atom:updated>2021-08-27T09:03:52.019Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*NE6fcjvY0ViAovj7gO9B2Q.png" /></figure><p>This is the last part of the text classification problem (<a href="https://morcu.medium.com/how-to-approach-a-text-classification-problem-part-1-3-a5743b41d0f7?sk=393449c0bf7adfe7f3993f1d97f59ce8">First one</a>)(<a href="https://morcu.medium.com/how-to-approach-a-text-classification-problem-part-2-3-c840fb025b52">Second One</a>).</p><p>LET’S SERVE OUR MODEL IN PRODUCTION</p><p>To serve a model we only need to:</p><ul><li>Clean the input text</li><li>Load the tokenizer</li><li>Load the model</li><li>Predict</li></ul><p>EASY? Right?</p><p>Ok, let’s see how to <strong>make a prediction</strong> with the model and then we will built a<strong> REST api</strong> to serve it in the <strong>Cloud.</strong></p><p>Lots of buzzwords… Let’s see what does them mean!</p><h3>Using the model to predict</h3><p>The code above is the one we will use to make the predictions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8262e4583f7cb4d728c60d9a0f381cc/href">https://medium.com/media/a8262e4583f7cb4d728c60d9a0f381cc/href</a></iframe><h3>What does serve mean?</h3><p>Basicaly serve means having a piece of code running somewhere where it is accesible by a client through an API.</p><p>Ok, dificult stuff lets get an image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/0*JxLR1HCIO9uWxXAj.png" /><figcaption><a href="https://medium.com/@perrysetgo/what-exactly-is-an-api-69f36968a41f">https://medium.com/@perrysetgo/what-exactly-is-an-api-69f36968a41f</a></figcaption></figure><p>To enable that API we will use the python library Flask. It will allow us to serve the model in an endpoint and even render a simple web with HTML.</p><blockquote>Just as an annotation in case that someone isn’t familiar with the terms.<strong> Difference between</strong> <em>POST </em>and <em>GET</em>: essentially GET is used to retrieve remote data, and POST is used to insert/update remote data.</blockquote><p>Now that we understand all the concepts, we want to build a web app like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IFhjl70l_fi6OIyOJ2l3Tg.png" /></figure><p>That can classify a given text</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1ttZvzYRsv8gx3Ju-Rbgiw.png" /></figure><h3>THE CODE</h3><p>You can find all the code in this repo: <a href="https://github.com/Morcu/ml-on-gcp">https://github.com/Morcu/ml-on-gcp</a></p><p>All the needed files and directories should look like this</p><pre>app<br>├── app<br>│   ├── __init__.py<br>│   ├── templates<br>│   │   └── public<br>│   │       └── index.html<br>│   │   classify.py<br>│   │   utils.py<br>│   └── views_routes.py<br>├── modeldata<br>│   ├── model.h5<br>│   └── tokenizer.json<br>├── app.ini<br>├── readme.md<br>├── requirements.txt<br>└── run.py </pre><p>For the local execution you can install the requirements and run on your terminal:</p><pre>flask run</pre><pre>And open the browser with the URL: <strong>http://127.0.0.1:5000/</strong></pre><blockquote>To create a virtual env you can use:<strong> python3 -m venv NAME_OF_ENV</strong></blockquote><blockquote>To install the requirements:<strong> pip install -r requirements.txt</strong></blockquote><h4>Classification code</h4><p>Just as we have seen above, it loads the models and make a prediction</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3accc11aed7be68474071db3990bd803/href">https://medium.com/media/3accc11aed7be68474071db3990bd803/href</a></iframe><h4>Utils code</h4><p>We already saw this code in the last part of this tutorial, so… No comments</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e34cdd94ca97c38a0a7be9a2273238f/href">https://medium.com/media/4e34cdd94ca97c38a0a7be9a2273238f/href</a></iframe><h4>REST API code</h4><p>As we have seen there is a GET method, the method that renders our web APP’s code, and a POST method, the one who makes a call to the <strong>get_class_ml </strong>function that gives us the classification result for the input text.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7088b4514715538d93a913ba9216892/href">https://medium.com/media/d7088b4514715538d93a913ba9216892/href</a></iframe><p>And how do we call that function??</p><p>We need to get to our endpoint (the <a href="http://127.0.0.1:5000/">http://127.0.0.1:5000/</a>) and use the <strong>/task</strong> in the URL with a POST call.</p><pre>For example: <strong>curl --location--request POST &#39;http://127.0.0.1:5000/task&#39;</strong></pre><p>And how do we pass the info?</p><p>Easy, we have to set some params in JSON format</p><pre>{<br>    &quot;text&quot;: &quot;the text we want to classify&quot;<br>}</pre><pre>So the final curl will be:<br><strong>curl --location --request POST &#39;http://127.0.0.1:5000/task&#39; \</strong></pre><pre><strong>--header &#39;Content-Type: application/json&#39; \</strong></pre><pre><strong>--data-raw &#39;{&quot;text&quot;:&quot;the text we want to classify&quot;}&#39;</strong></pre><h4>Web APP code</h4><p>We do not really have to understand this code, it just set the boxes and the button and it makes the request to our server.</p><blockquote>THE ONLY THING WE HAVE TO CARE ABOUT IS THE ENDPOINT ON <strong>LINE 39</strong> it is our computer’s endpoint, we will have to change it when we serve it.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e28b0c3e49f09eae2f37ebea4fa2ad39/href">https://medium.com/media/e28b0c3e49f09eae2f37ebea4fa2ad39/href</a></iframe><h4>Deploying on Google CLoud Platform (GCP): Production ready</h4><p>First of all we will need to create an account in <a href="https://console.cloud.google.com/?hl=es">https://console.cloud.google.com/</a></p><p>There we will need to go to Compute Engine</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L96_CIZyf3tT1KeJ65qNiA.png" /></figure><p>Go to create instance</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*RPyWzHFTNeA0VtIZCSkF-Q.png" /></figure><p>Set the <strong>Name</strong>, the <strong>Region</strong>, the<strong> type of machine</strong> you want for this purpose we will change the<strong> Boot Disk</strong> to a Deep Learning one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*k062TkHTuSOWcZy7QiRFWg.png" /></figure><p>And dont forget to enable the API access and the HTTP and HTTPS traffic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*8jmn5oZ_MK1hDQaUb5w7Dw.png" /></figure><p>Once we have all set, the machine will be in the state <strong>creating, when it is created you will see something like this.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z-wm572-zpnyi-jJ3YL-Ig.png" /></figure><blockquote>Write down the <strong>External IP</strong> we will need it for the serving part</blockquote><p>Let’s open the SSH console.</p><ol><li>Create the venv</li><li>Activate the env</li><li>Clone the repo</li><li>Rename the repo</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D1NwL-ySYQPmuS3HFihS2w.png" /></figure><pre>python3 -m venv env<br>source env/bin/activate<br>git clone https://github.com/Morcu/ml-on-gcp.git<br>mv ml-on-gcp/ app</pre><p>5. Go into the app directory</p><p>6. Upgrade pip and install the requirements (it may take a while)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*ZpadGvyAgWLoz9Bj3W2Qqw.png" /></figure><pre>cd app<br>pip install --upgrade pip</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*5mScvZxmibgu1PkBNjbTWQ.png" /></figure><pre>python<br>&gt;&gt;&gt; import nltk<br>&gt;&gt;&gt; nltk.download(&#39;stopwords&#39;)</pre><p>7. Change the index.html url</p><pre>nano app/templates/public/index.html</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PhcGePxl3pn03v9VbMEyeQ.png" /></figure><p>8. Install nginx and allow the rule in the firewall</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*lSHkWFPHf7njo_7Fh4iJvQ.png" /></figure><pre>sudo ufw enable<br>sudo apt install nginx<br>sudo ufw allow &#39;Nginx HTTP&#39;<br>sudo ufw status</pre><p>9. Create systemd unit file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fRn1o2Q50M5Zz5t-gpNHFw.png" /><figcaption>sudo nano /etc/systemd/system/app.service</figcaption></figure><pre>[Unit]<br>Description=A simple Flask uWSGI application<br>After=network.target<br><br>[Service]<br>User=&lt;yourusername&gt;<br>Group=www-data<br>WorkingDirectory=/home/&lt;yourusername&gt;/app<br>Environment=&quot;PATH=/home/&lt;yourusername&gt;/env/bin&quot;<br>ExecStart=/home/&lt;yourusername&gt;/env/bin/uwsgi --ini app.ini<br><br>[Install]<br>WantedBy=multi-user.target</pre><p>Replace the username with yours, in my example it is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*oX90RVhQ7EC0_QP-dSmh2w.png" /></figure><p>10. Start the process, enable it, and check the status</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wmytb9hFg0Be-gUeh3_JPQ.png" /></figure><pre>sudo systemctl start app<br>sudo systemctl enable app<br>sudo systemctl status app</pre><p>11. Configure Nginx</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PL-so3FAyEeyi2CKn814PA.png" /><figcaption>sudo nano /etc/nginx/sites-available/app</figcaption></figure><pre>server {<br>    listen 80;<br>    server_name &lt;your_external_ip_address&gt;;<br><br>    location / {<br>        include uwsgi_params;<br>        uwsgi_pass unix:/home/&lt;username&gt;/app/app.sock;<br>    }<br>}<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*K93kKHp4Z3JhIbG493_1Rg.png" /></figure><p>12. link the server block to sites-enabled</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K89s855du6bNmMJWg_soKA.png" /></figure><pre>sudo ln -s /etc/nginx/sites-available/app /etc/nginx/sites-enabled<br>sudo nginx -t<br>sudo systemctl restart nginx</pre><h3>THA’S IT we have our app on a public endpoint</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tr06xU6pqCdj9ClxfwM69g.png" /></figure><h4>Code</h4><ul><li><a href="https://github.com/Morcu/ml-on-gcp">https://github.com/Morcu/ml-on-gcp</a></li></ul><h4>Contact</h4><ul><li><a href="/service/mailto:david.morcuende.c@gmail.com">david.morcuende.c@gmail.com</a></li><li><a href="https://www.linkedin.com/in/david-morcuende-cantador-883a22155/">David Morcuende Linkedin</a></li></ul><h4>Buy me a coffe</h4><figure><a href="https://www.paypal.com/donate?hosted_button_id=7P4X4ZB4UN5VE"><img alt="" src="https://cdn-images-1.medium.com/max/147/1*wuk9g08uOqNokdUB0_lLHw.gif" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51d706a51948" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to approach a text classification problem (part 2/3)]]></title>
            <link>https://morcu.medium.com/how-to-approach-a-text-classification-problem-part-2-3-c840fb025b52?source=rss-782cc2dab484------2</link>
            <guid isPermaLink="false">https://medium.com/p/c840fb025b52</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[classification]]></category>
            <dc:creator><![CDATA[David Morcuende]]></dc:creator>
            <pubDate>Sun, 21 Feb 2021 10:31:42 GMT</pubDate>
            <atom:updated>2021-02-21T10:31:42.838Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yhDeNGCnIqNI44P4iC1JMQ.png" /></figure><p>This is the second part of the text classification problem (<a href="https://morcu.medium.com/how-to-approach-a-text-classification-problem-part-1-3-a5743b41d0f7?sk=393449c0bf7adfe7f3993f1d97f59ce8">First one</a>).</p><p>In this post we are going to generate a model for the clasification problem with:</p><ul><li><strong>scikit-learn: </strong>SVC, MultinomialNB, LogisticRegression.</li><li><strong>Tensorflow: </strong>LSTM, CNN.</li></ul><p>First We Import the needed classes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cee8a1a95ceadb84fb745fd09911f2ca/href">https://medium.com/media/cee8a1a95ceadb84fb745fd09911f2ca/href</a></iframe><p>Just as we did in the previous post, we are going to read the text and clean it (it is widely explained in the<a href="https://morcu.medium.com/how-to-approach-a-text-classification-problem-part-1-3-a5743b41d0f7?sk=393449c0bf7adfe7f3993f1d97f59ce8"> First post</a>)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d517f8bd947abb9cf71c6df68f7f18a/href">https://medium.com/media/0d517f8bd947abb9cf71c6df68f7f18a/href</a></iframe><pre>[&#39;politics&#39;,<br> &#39;exploration&#39;,<br> &#39;intelligence&#39;,<br> &#39;weapons&#39;,<br> &#39;headhunters&#39;,<br> &#39;transportation&#39;,<br> &#39;logistics&#39;]</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d66078a23f51bbe3e6a35a121382887f/href">https://medium.com/media/d66078a23f51bbe3e6a35a121382887f/href</a></iframe><pre>CPU times: user 4.79 s, sys: 34.9 ms, total: 4.83 s<br>Wall time: 5.18 s</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*lmYQajOfmCOQzkrp0QyWLg.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/293201980a0b4c201c7f4ba6f5c8d77a/href">https://medium.com/media/293201980a0b4c201c7f4ba6f5c8d77a/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*qmcik_NErhhStMQMrbsgoQ.png" /></figure><h3>Modeling</h3><p>To do a model exploration we are going to start with a baseline of models testing MultinomialNB, SVC and logistic regression, all of them with a conversion of the text to TF-IDF. Among them, the cross-validation method will be used to verify which of them gives us the best results and the final test will be carried out on that.</p><p>This baseline model will be compared to an LSTM model and a convolutional one.</p><p>We import all the sklearn dependencies.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5a4d37dde9d4b29b1267ac285cb03b5/href">https://medium.com/media/d5a4d37dde9d4b29b1267ac285cb03b5/href</a></iframe><p>In order to train the models, we will first vectorize the text, this generates an array with a “1” if the word appears in the text.</p><p>We will also use TF-IDF (term frequency–inverse document frequency). This technique provides us with a numerical representation of the terms within the text.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e7d76007c34261bb4e6acf71871e46d/href">https://medium.com/media/3e7d76007c34261bb4e6acf71871e46d/href</a></iframe><pre>[&#39;aa&#39;, &#39;aaa&#39;, &#39;aaaa&#39;, &#39;aaaaaaaaaaaa&#39;, &#39;aaah&#39;, &#39;aaef&#39;, &#39;aah&#39;, &#39;aalborg&#39;, &#39;aamir&#39;, &#39;aammmaaaazzzzzziinnnnggggg&#39;]</pre><pre>[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/540991c9e1e3a7dbaf4078a8d14b8e22/href">https://medium.com/media/540991c9e1e3a7dbaf4078a8d14b8e22/href</a></iframe><pre>array([6.08295596, 5.70566172, 8.56786261, ..., 8.56786261, 8.56786261, 8.1623975 ])</pre><pre>array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])</pre><p>How is TF*IDF calculated? The TF (term frequency) of a word is the frequency of a word (i.e. number of times it appears) in a document. When you know TF, you’re able to see if you’re using a term too much or too little. For example, when a 100-word document contains the term “aalborg” 12 times, the TF for the word ‘aalborg’ is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*KPFjL8MARiOoHW-WWd1M9A.gif" /></figure><p>The IDF (inverse document frequency) of a word is the measure of how significant that term is in the whole corpus.</p><p>Let’s say the size of the corpus is 10,000,000 million documents. If we assume there are 0.3 million documents that contain the term “aalborg”, then the IDF (i.e. log {DF}) is given by the total number of documents (10,000,000) divided by the number of documents containing the term “aalborg” (300,000).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*rzwpTlJqBRbOjf8tKgBiUg.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*ZU_Xr5mMJLmoMh8pOx5Efw.gif" /></figure><p>Baseline models</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79b5500fdbdf130bc2e794c5b6c60399/href">https://medium.com/media/79b5500fdbdf130bc2e794c5b6c60399/href</a></iframe><p>To evaluate the performance of the 3 models, we will use the cross validation technique, which consists of training with a series of data and leaving another series to validate. The selection of the number of data that is chosen is a variable to choose. I attach a graphic where you can see an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*L90fdYb2oT0BOP2CCMSIbg.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2da7d7994772b0a96e759005e8c0fdac/href">https://medium.com/media/2da7d7994772b0a96e759005e8c0fdac/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*h4JS4nWXmXke6HEyi2SxlQ.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06468944faea61b5544ff37e2af03ef5/href">https://medium.com/media/06468944faea61b5544ff37e2af03ef5/href</a></iframe><pre>model_name<br>LogisticRegression    0.934610<br>MultinomialNB         0.929186<br>SVC                   0.943398<br>Name: accuracy, dtype: float64</pre><p>After analyzing the 3 models we see that SVC behaves better than the others and in a more stable way, so a more exhaustive test will be carried out with this model.</p><p>To carry out this test, the data processed with TF-IDF will be used and the data will be separated to obtain 70% of the data to train the model and 30% of data that the model has not seen to validate what right or wrong that generalizes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7005f94d3a7e210b83450637a364f810/href">https://medium.com/media/7005f94d3a7e210b83450637a364f810/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*tAN1TzVPx0DppKlOdcR5Rw.png" /></figure><p>As can be seen in the confusion matrix in the model, it generalizes quite well, noting that the “Headhunters” class has a certain deviation to predict incorrectly as “Exploration”.</p><p>Next we will analyze precision, recall and f1-score.</p><p>But before analyzing it, we must understand what each value refers to:</p><ul><li>precision: the number of cases classified correctly over the total number of those that should be correct If the number of false positives has a high impact, this is the metric that needs to be paid more attention</li><li>recall: the number of cases classified as positive above all that was positive what was predicted vs what was not predicted correctly. If you need to reduce false negatives, this is the metric to pay the most attention to.</li><li>f1score: it is a balance between the previous 2</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1dc779c34b418201cde2199562f0e49/href">https://medium.com/media/a1dc779c34b418201cde2199562f0e49/href</a></iframe><pre>precision    recall  f1-score   support<br><br>   exploration       0.96      0.95      0.96       199<br>   headhunters       0.91      0.97      0.94       179<br>  intelligence       0.96      0.94      0.95       133<br>     logistics       0.99      0.96      0.97       137<br>      politics       0.97      0.96      0.97       185<br>transportation       0.93      0.96      0.95       165<br>       weapons       0.99      0.94      0.97       163<br><br>      accuracy                           0.96      1161<br>     macro avg       0.96      0.96      0.96      1161<br>  weighted avg       0.96      0.96      0.96      1161</pre><p>As we can see, the model behaves very well and is robust.</p><h4>Tensorflow</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6d9a26ab21882bfa52ed62c03a0c894/href">https://medium.com/media/f6d9a26ab21882bfa52ed62c03a0c894/href</a></iframe><p>Let’s check if there are GPUs available to make training more efficient.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b09c7e5bfcaec963a02a0758ce19cf9d/href">https://medium.com/media/b09c7e5bfcaec963a02a0758ce19cf9d/href</a></iframe><pre>Num GPUs Available:  1<br>[name: &quot;/device:CPU:0&quot;<br>device_type: &quot;CPU&quot;<br>memory_limit: 268435456<br>locality {<br>}<br>incarnation: 11162430468200319055<br>, name: &quot;/device:XLA_CPU:0&quot;<br>device_type: &quot;XLA_CPU&quot;<br>memory_limit: 17179869184<br>locality {<br>}<br>incarnation: 233496321260097046<br>physical_device_desc: &quot;device: XLA_CPU device&quot;<br>, name: &quot;/device:GPU:0&quot;<br>device_type: &quot;GPU&quot;<br>memory_limit: 6961726752<br>locality {<br>  bus_id: 1<br>  links {<br>  }<br>}<br>incarnation: 15285252465848281027<br>physical_device_desc: &quot;device: 0, name: GeForce RTX 2070, pci bus id: 0000:01:00.0, compute capability: 7.5&quot;<br>, name: &quot;/device:XLA_GPU:0&quot;<br>device_type: &quot;XLA_GPU&quot;<br>memory_limit: 17179869184<br>locality {<br>}<br>incarnation: 17115642552350290797<br>physical_device_desc: &quot;device: XLA_GPU device&quot;<br>]<br><br><br>[PhysicalDevice(name=&#39;/physical_device:GPU:0&#39;, device_type=&#39;GPU&#39;)]</pre><p>If we have GPU we configure tensorflow so that it uses the memory of it without limits.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16cefd13829641e0abad3a21a4f60d30/href">https://medium.com/media/16cefd13829641e0abad3a21a4f60d30/href</a></iframe><p>In this case, due to the neural network architecture, instead of classifying the classes in a numerical way, we will make a one-hot encoding in which each column will refer to each class, so that each neuron from the output of the neuroal network is identified with a class and the neuron with the highest value will be the one that identifies the predicted class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*GAkV7XIp11W2-sz3Bz_olQ.gif" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe8ee6a8c961e26b695cf89611866a04/href">https://medium.com/media/fe8ee6a8c961e26b695cf89611866a04/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*HkMw_mH3oA21hOe52mQgsQ.png" /></figure><p>So, there will be 7 columns showing wich class each row belongs to, and therefore 7 output neurons.</p><p>Due to this particular problem, we know that each text belong only to ONE class so each row only can have <strong>ONE and only ONE class</strong> (column wiht a “1&quot;), this is called a M<strong>ulticlass classification. </strong>If our problem could have more thatn one class it would be a<strong> Multilabel classification.</strong></p><p>Let’s Tokenize again (as before, we vectorize the input) using the Tokenizer library of keras.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce6ef8c16aab9e88a65b0c51f9eec504/href">https://medium.com/media/ce6ef8c16aab9e88a65b0c51f9eec504/href</a></iframe><pre>[4, 4318, 127, 2696, 2, 1845, 906, 3803, 3, 4, 11450, 2640, 127, 2175, 2, 1329, 10290, 3, 4798, 7039, 8635, 4319, 145, 4798, 7039, 3,<br> 1459, 416, 132, 1098]</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5712f177e3b74716cf1065456c235d5f/href">https://medium.com/media/5712f177e3b74716cf1065456c235d5f/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*Yq4GdZhZOepWd3QKCMfFLQ.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fdce9dee867cd78fbbc626ec8f36ae9/href">https://medium.com/media/9fdce9dee867cd78fbbc626ec8f36ae9/href</a></iframe><pre>151.14913414318946<br><br>6050</pre><p>As we can see, the length of the texts is in average of 151 and a max of 6050 so, to normalize the input length of the tokenized text sequences we will use a length of 200.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/183e0b0983969f73042a5ff7cc38b147/href">https://medium.com/media/183e0b0983969f73042a5ff7cc38b147/href</a></iframe><p>To test this architecture the tokenized data will be used. The data will be splited with 70% to train the model and 30% to test, the model has not seen how those 30% looks like, so we can check how good or bad it generalizes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c333034d2a0c82bcbb3977ff1b1b9c5/href">https://medium.com/media/2c333034d2a0c82bcbb3977ff1b1b9c5/href</a></iframe><p>The model consists of:</p><ul><li>an embedding layer With the length of the tokens + 1 (adding 1 is for the “unknown” token, any token that is not within the token list) and a length of the embedding vector of 64 (this is a hyperparameter of the model)</li><li>a Bidirectional layer of LSTM of 64 (hyperparameter)</li><li>a Bidirectional layer of LSTM of 32 (hyperparameter)</li><li>a layer of 64 (hyperparameter) fully connected neurons with reluctance activation</li><li>a layer of droput</li><li>a layer of 7 fully connected neurons with softmax activation</li></ul><p>The last layer has 7 neurons referring to the 7 classes that must be predicted and the activation is softmax since it makes a probability distribution over all neurons and the neuron with the highest probability will refer to the associated class being the predicted one.</p><p>The model will use a loss calculation with the <strong>“categorical_crossentropy”</strong> algorithm. To do the training the optimizer for the calculation of the gradient will be <strong>“adam”</strong> and the metric to be calculated will be <strong>“accuracy”.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26171aced5581df7a5848f17f827b617/href">https://medium.com/media/26171aced5581df7a5848f17f827b617/href</a></iframe><p>A training is done with 4 passes of the algorithm using batches of 32 data to avoid overloading the memory</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e713cf77ad135bd4a6373aaa8b16967/href">https://medium.com/media/0e713cf77ad135bd4a6373aaa8b16967/href</a></iframe><pre>Epoch 1/4<br>85/85 [==============================] - 5s 55ms/step - loss: 1.8506 - accuracy: 0.2142 - val_loss: 1.5143 - val_accuracy: 0.3463<br>Epoch 2/4<br>85/85 [==============================] - 3s 38ms/step - loss: 1.1420 - accuracy: 0.5251 - val_loss: 0.9627 - val_accuracy: 0.6503<br>Epoch 3/4<br>85/85 [==============================] - 3s 38ms/step - loss: 0.6128 - accuracy: 0.7843 - val_loss: 0.6739 - val_accuracy: 0.7933<br>Epoch 4/4<br>85/85 [==============================] - 3s 38ms/step - loss: 0.2878 - accuracy: 0.9184 - val_loss: 0.5204 - val_accuracy: 0.8562</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d879cd0cd4b43fc330d8d50d5eb20724/href">https://medium.com/media/d879cd0cd4b43fc330d8d50d5eb20724/href</a></iframe><pre>Model: &quot;sequential&quot;<br>_________________________________________________________________<br>Layer (type)                 Output Shape              Param #   <br>=================================================================<br>embedding (Embedding)        (None, None, 64)          2457408   <br>_________________________________________________________________<br>bidirectional (Bidirectional (None, None, 128)         66048     <br>_________________________________________________________________<br>bidirectional_1 (Bidirection (None, 64)                41216     <br>_________________________________________________________________<br>dense (Dense)                (None, 64)                4160      <br>_________________________________________________________________<br>dropout (Dropout)            (None, 64)                0         <br>_________________________________________________________________<br>dense_1 (Dense)              (None, 7)                 455       <br>=================================================================<br>Total params: 2,569,287<br>Trainable params: 2,569,287<br>Non-trainable params: 0<br>_________________________________________________________________</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3c302e37c11e171c295fbeda1eaabf2/href">https://medium.com/media/f3c302e37c11e171c295fbeda1eaabf2/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*tO4a72RNL-chrE8oFHSwnw.png" /></figure><p>As can be seen in the training graphs, the training model has a lot of acurracy and also in validation, we must be careful with overfitting since we may be overtraining the model and then it will not be able to generalize.</p><p>Let’s move on to the convolutional model</p><h3>Convolutional</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d98d5a12eea1207bee974a766e69b763/href">https://medium.com/media/d98d5a12eea1207bee974a766e69b763/href</a></iframe><pre>Epoch 1/4<br>43/43 [==============================] - 1s 28ms/step - loss: 1.8761 - accuracy: 0.2371 - val_loss: 1.6784 - val_accuracy: 0.3781<br>Epoch 2/4<br>43/43 [==============================] - 1s 21ms/step - loss: 0.6809 - accuracy: 0.8364 - val_loss: 0.3644 - val_accuracy: 0.8906<br>Epoch 3/4<br>43/43 [==============================] - 1s 21ms/step - loss: 0.0619 - accuracy: 0.9860 - val_loss: 0.3042 - val_accuracy: 0.9078<br>Epoch 4/4<br>43/43 [==============================] - 1s 21ms/step - loss: 0.0170 - accuracy: 0.9970 - val_loss: 0.2632 - val_accuracy: 0.9190</pre><p>The model consists of:</p><ul><li>a layer of embedings with the length of the tokens + 1 (adding 1 is for the “unknown” token, any token that is not within the token list) and a length of the embedding vector of 64 (this is a hyperparameter of the model)</li><li>a Convolutional layer of 1 dimension with 50 filters and a kernel dimension of 5 (length of the window in which the convolution is going to move)</li><li>a Flatten layer so that all the parameters are in the form of a list not an array</li><li>a layer of 100 (hyperparameter) fully connected neurons with reluctance activation</li><li>a layer of 7 fully connected neurons with softmax activation</li></ul><p>As in the previous model because there are 7 classes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a91f2f0a6206f83f5d8a58c4931fea3/href">https://medium.com/media/9a91f2f0a6206f83f5d8a58c4931fea3/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*epHPyUoL6_cjdJg9VeXHMg.png" /></figure><p>The results are similar to the previous model but it behaves somewhat better in validation</p><p>We are going to classify the test set to make an analysis of the confusion matrix and the metrics.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45e4c9f9ad4cf4a777a167997d654379/href">https://medium.com/media/45e4c9f9ad4cf4a777a167997d654379/href</a></iframe><p>We obtain the position of the neuron with the highest value and obtain the class to which it belongs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9be0b69d2da2f0d630aa742adb69f46a/href">https://medium.com/media/9be0b69d2da2f0d630aa742adb69f46a/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*lamAtmjX3S0R4UUUlNeWpQ.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/700a5949f63ebc32fcf2ee7895bc2166/href">https://medium.com/media/700a5949f63ebc32fcf2ee7895bc2166/href</a></iframe><pre>precision    recall  f1-score   support<br><br>   exploration       0.89      0.95      0.92       199<br>   headhunters       0.98      0.89      0.93       179<br>  intelligence       0.95      0.79      0.86       133<br>     logistics       0.93      0.92      0.92       137<br>      politics       0.97      0.97      0.97       185<br>transportation       0.81      0.97      0.88       165<br>       weapons       0.95      0.91      0.93       163<br><br>      accuracy                           0.92      1161<br>     macro avg       0.92      0.91      0.92      1161<br>  weighted avg       0.92      0.92      0.92      1161</pre><p>As we can see, the transport part has some shortcomings, but due to the embedding layers and the convolutions it should better abstract the model.</p><h3>Annex: Embeddings</h3><p>Embeddings are dense form representations of words in which similar words have similar encodings and are close to words related to themselves.</p><p>Let’s see an example using the data from the embeddings layer from the last training (convolution). We take the tokenizer data and the weights of the embeddings layer and save them in the vectors and metadata files respectively</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c0edaa611e89866f23a1752dcc57bd2/href">https://medium.com/media/2c0edaa611e89866f23a1752dcc57bd2/href</a></iframe><p>We can use the web <a href="https://projector.tensorflow.org/">https://projector.tensorflow.org/</a> to obtain a graphic projection of our embeddings map, for this we load the files in the “Load” section and mark the icon with an “A” to show us the labels into words.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*vpIWqwScDLtCmS-pzS9OiQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*V-Uaj8bSuUzt6tV62BFDXA.png" /></figure><p>As we can see the label “religious” has close (in cosine distance) the labels “satan”, “jesus” and “independent”.</p><p>Although the best known example of embedings is the representation of the male-female concepts related to that of king and queen for gender in addition to verval times and country-capital.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*cewZ_KttHLLj6NAcf3hFUQ.png" /></figure><h4>Code (soon)</h4><ul><li><a href="https://github.com/morcu">github.com/morcu</a></li></ul><h4>Contact</h4><ul><li><a href="/service/mailto:david.morcuende.c@gmail.com">david.morcuende.c@gmail.com</a></li><li><a href="https://www.linkedin.com/in/david-morcuende-cantador-883a22155/">David Morcuende Linkedin</a></li></ul><h4>Buy me a coffe</h4><figure><a href="https://www.paypal.com/donate?hosted_button_id=7P4X4ZB4UN5VE"><img alt="" src="https://cdn-images-1.medium.com/max/147/1*wuk9g08uOqNokdUB0_lLHw.gif" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c840fb025b52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to approach a text classification problem (part 1/3)]]></title>
            <link>https://morcu.medium.com/how-to-approach-a-text-classification-problem-part-1-3-a5743b41d0f7?source=rss-782cc2dab484------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5743b41d0f7</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[David Morcuende]]></dc:creator>
            <pubDate>Wed, 10 Feb 2021 17:06:37 GMT</pubDate>
            <atom:updated>2021-02-10T17:06:37.229Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*yhDeNGCnIqNI44P4iC1JMQ.png" /></figure><p>In this post I will show you how to approach a text classification problem using a dataset I was given to analyse.</p><p>I was provided with a .zip and the only instructions were: <em>“there are 7 folders, inside each folder there are some files, the name of the folder represent the class”.</em></p><p>I will split hte solution intro 3 parts:</p><ul><li><strong>EDA </strong>(Exploratory data analysis): we will take a look into the files and the data.</li><li><strong>Modeling</strong>: we will define some baseline models with <strong>scikit-learn</strong> and then try to improve them with <strong>Tensorflow</strong>.</li><li><strong>Deploy</strong>: we will deploy the best model (local &amp; <strong>AWS</strong>).</li></ul><p>Some text example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*GgyhW5nKDYuztAMPwD8pyw.png" /></figure><p>Some File names:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*vIglgzHCjv4rhpOrL0mr1w.png" /></figure><h3>EDA</h3><p>First of all we need to set a seed to make the process reproducible and import the needed classes to work with files and load the data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/acff17300989038c5885d5eba691b81c/href">https://medium.com/media/acff17300989038c5885d5eba691b81c/href</a></iframe><p>The files are in a folder called <strong>dataset</strong> in the same folder of this notebook</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d517f8bd947abb9cf71c6df68f7f18a/href">https://medium.com/media/0d517f8bd947abb9cf71c6df68f7f18a/href</a></iframe><pre>[&#39;exploration&#39;,<br> &#39;headhunters&#39;,<br> &#39;intelligence&#39;,<br> &#39;logistics&#39;,<br> &#39;politics&#39;,<br> &#39;transportation&#39;,<br> &#39;weapons&#39;]</pre><p>As they anticipated, there are <strong>7 classes</strong></p><h4>Reading text</h4><p>We know there is text in the files, but we don’t know the extension of the files so we are going to iterate over the folders and files to get the text and save it in a dataframe in 2 columns: the <strong>text</strong> and the <strong>class</strong> it belongs to.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d66078a23f51bbe3e6a35a121382887f/href">https://medium.com/media/d66078a23f51bbe3e6a35a121382887f/href</a></iframe><pre>Wall time: 5.52 s</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*txilMEvAUMAPZqb23KxXnA.png" /></figure><p>Let’s check for null data that we have not been able to read</p><pre>df.shape</pre><pre>(3893, 2)</pre><pre>df.info()</pre><pre>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 3893 entries, 0 to 3892<br>Data columns (total 2 columns):<br> #   Column  Non-Null Count  Dtype <br>---  ------  --------------  ----- <br> 0   text    3893 non-null   object<br> 1   target  3893 non-null   object<br>dtypes: object(2)<br>memory usage: 61.0+ KB</pre><pre>df.isnull().sum()</pre><pre>text      0<br>target    0<br>dtype: int64</pre><p><em>Missingno is a python data visualization library that allows you to get a quick visual summary of the completeness (or lack thereof) of your dataset.</em></p><pre>import missingno as msno<br>msno.matrix(df,color=(0.3,0.36,0.44))</pre><pre>&lt;AxesSubplot:&gt;</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*73GgOf-dL6PmtjHBLzEjXA.png" /></figure><p>We check that we have <strong>3893 text files</strong> and that we have not had any errors when reading the content, at least there is some text in them.</p><p>Let’s see how these texts are distributed among the different classes</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/637a960c567a5feafa37cdc2cf0afe48/href">https://medium.com/media/637a960c567a5feafa37cdc2cf0afe48/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*zbpw84RYpH9miHfWRQeplQ.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a091a7cc9323c0d138e597d4446e1e73/href">https://medium.com/media/a091a7cc9323c0d138e597d4446e1e73/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*sEMrdr0EDtSsAVfaivn8lA.png" /></figure><p>The <strong>“politics”</strong> class is the one with the most files (609, representing 15.6% of all files) and the one with the least is <strong>“intelligence”</strong> (465, representing 11.9% of all files)</p><p>It is appreciated that there is not a great imbalance between the different classes.</p><p>Next we will see how the characters and words are distributed within the files, for this task, we will create a function with parameters to be able to reuse it in the data cleaning process.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6584f773f15fc312b247789bf8536be7/href">https://medium.com/media/6584f773f15fc312b247789bf8536be7/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*GZ-hF8LIdeqtOpXeRKP0YA.png" /></figure><p>As can be seen in the graphics there is a lot of <strong>imbalance</strong> between the files, there are some that have many characters, but the vast majority are below 20,000</p><pre>print_char_word(df,&quot;text&quot;,True)</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*norpuFfnJZnpJj9078LsbA.png" /></figure><p>The same thing happens with words, there are files with many words but the vast majority are below 2,000</p><p>In addition to the characters and words, we will see if there are special characters and stop words (empty words, without meaning) since it will only add noise to the subsequent classification, for this we will create a function that for each class <strong>counts the number of special characters or stop words.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8116e14905ad9c9dfa464f9de434c8bb/href">https://medium.com/media/8116e14905ad9c9dfa464f9de434c8bb/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*k7RNzuvdC5nkonwQIY-hKA.png" /></figure><p>As can be seen there are a considerable number of special characters, especially hyphens “-” and periods “.”</p><p>For the stop words we will use the <strong>stops words from the nltk library</strong>, a natural language processing library for python.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fe3753b7f4a44718d0242d22c0067f7/href">https://medium.com/media/9fe3753b7f4a44718d0242d22c0067f7/href</a></iframe><pre>[nltk_data] Downloading package stopwords to<br>[nltk_data]     C:\Users\video\AppData\Roaming\nltk_data...<br>[nltk_data]   Package stopwords is already up-to-date!</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*m8IQ59Bz8ZjkkXEBFSL-3g.png" /></figure><p>We graph one independently to be able to analyze an example since in the set of 7 it is more difficult to appreciate details.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fcf77700f3c577cb4000587c5021312d/href">https://medium.com/media/fcf77700f3c577cb4000587c5021312d/href</a></iframe><pre>&lt;BarContainer object of 179 artists&gt;</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*HseKYJocc5z0oO0-dbbvig.png" /></figure><p>As with the special characters, there is a very high number of stop words.</p><p>For a better text processing we are going to lower case everything to regularize the words and make sure that 2 words are not different by the mere fact of starting with upper case and delete a series of elements:</p><ul><li>Urls</li><li>HTML markup</li><li>Punctuation symbols</li><li>Numbers</li><li>Stopwords</li><li>Spaces</li></ul><p>In that order, to correctly delete everything.</p><h4>Processing Text</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05fa3bfaa387114cf4b2cd08f47106e5/href">https://medium.com/media/05fa3bfaa387114cf4b2cd08f47106e5/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d5778468686df476c60e23808a2af67/href">https://medium.com/media/0d5778468686df476c60e23808a2af67/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*qyEfsSdHJoaDUk66gIKZ7A.png" /></figure><pre>plot_char_freq(&quot;clean_text&quot;, string.punctuation, character=True, title=&#39;Caracteres especiales&#39;)</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*a-W9yBD4a-f-qac6TlR3oA.png" /></figure><pre>plot_char_freq(&quot;clean_text&quot;, STOPWORDS, character=False, title=&#39;Stop words&#39;)</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*6Mo1bji2hHKao0i5LmmL8Q.png" /></figure><pre>print_char_word(df,&quot;clean_text&quot;,True)</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*gqUDyN0nTpUT5daxRPHY-A.png" /></figure><p>As we can see, there are no longer punctuation symbols or stop words and the number of words has dropped considerably, in the order of 500 words (although we still have texts with a number of words way above the average)</p><p>After the cleaning, we check if there are <strong>empty texts</strong> and we convert them to null to be able to eliminate them easily.</p><p>We also check for <strong>duplicates</strong> and remove them so there is no redundancy</p><pre>df = df.replace(r&#39;^\s*$&#39;, np.nan, regex=True)</pre><pre>np.where(df.applymap(lambda x: x == &#39;&#39;))</pre><pre>(array([], dtype=int64), array([], dtype=int64))</pre><pre>df.isnull().sum()</pre><pre>text          4<br>target        0<br>clean_text    5<br>dtype: int64</pre><pre>duplicate = df[df.duplicated()]<br>duplicate</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*yqGsyVhR6RhDVHmDRl52Xg.png" /></figure><pre>df = df.dropna()<br>df = df.drop_duplicates()</pre><p>Having cleaned the data and eliminated the nulls and duplicates, we are going to prepare the categories to be classified, for this we are going to change the <strong>“target” column to a category column</strong> to easily convert it to numeric categories.</p><pre>df[&quot;target&quot;] = df[&quot;target&quot;].astype(&#39;category&#39;)<br>df[&quot;target_cat&quot;] = df[&quot;target&quot;].cat.codes</pre><pre>df.head()</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*H1wjArtu9OYunP9QtvWcIA.png" /></figure><p>In the next post we will explore models using the <strong>scikit-learn</strong> library to have some base models, we will build models with <strong>Tensorflow</strong> and we will compare them to see which one works best.</p><p>There will also be an annex explaining what the <strong>Embeddings</strong> are.</p><h4>Code (soon)</h4><ul><li><a href="https://github.com/morcu">github.com/morcu</a></li></ul><h4>Contact</h4><ul><li><a href="/service/mailto:david.morcuende.c@gmail.com">david.morcuende.c@gmail.com</a></li><li><a href="https://www.linkedin.com/in/david-morcuende-cantador-883a22155/">David Morcuende Linkedin</a></li></ul><h4>Buy me a coffe</h4><figure><a href="https://www.paypal.com/donate?hosted_button_id=7P4X4ZB4UN5VE"><img alt="" src="https://cdn-images-1.medium.com/max/147/1*wuk9g08uOqNokdUB0_lLHw.gif" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5743b41d0f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Shor’s algorithm can break RSA]]></title>
            <link>https://morcu.medium.com/how-shors-algorithm-can-break-rsa-b365676363c1?source=rss-782cc2dab484------2</link>
            <guid isPermaLink="false">https://medium.com/p/b365676363c1</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[quantum]]></category>
            <category><![CDATA[quantum-computing]]></category>
            <category><![CDATA[qiskit]]></category>
            <category><![CDATA[rsa]]></category>
            <dc:creator><![CDATA[David Morcuende]]></dc:creator>
            <pubDate>Wed, 05 Aug 2020 15:32:15 GMT</pubDate>
            <atom:updated>2021-02-10T17:08:02.365Z</atom:updated>
            <content:encoded><![CDATA[<p>An explanation of the maths behind RSA, shor’s algorithm and how quantum computing can break the encryption.</p><h3>How asymmetric encryption works — E.G RSA</h3><p>RSA works with a pair of keys to encrypt-decrypt. A public key which everybody can access to encrypt the messages and a private key, only owned by the proprietary and it is used to decrypt the messages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MIDKsVzlkJsCfCePL1v6tg.png" /></figure><p>Alice uses Bob’s public key to encrypt the message</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*FWpDor6m2eME51TSgodCsA.png" /></figure><p>Bob receives the messages and decrypt it with his private key</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*UyBZIe5VurzwHYan7D1USA.png" /></figure><p>Lest make a comparison with a mailbox.</p><p>Everybody knows where Bob’s mailbox is (public key), but only Bob have the key to open it (private key).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*bXGX-XR3hUjEHpDjEDc1YQ.png" /></figure><h3>The algorithm</h3><p>The algorithm is based on the fact that finding the factors of a large composite number is difficult: when the factors are prime numbers, the problem is called prime factorization. It is also a key pair (public and private key) generator.</p><blockquote>Note that we are going to use small numbers so this will be a simplified version.</blockquote><p>The required length for the algorithm to work is at least 1024 bits. For example, find the factors of 15 is easy (3,5) but find the factors of this number with 250 digits (829 bits) It’s not.</p><p>2140324650240744961264423072839333563008614715144755017797754920881418023447140136643345519095804679610992851872470914587687396261921557363047454770520805119056493106687691590019759405693457452230589325976697471681738069364894699871578494975937497937</p><p>So the algorithm is similar to put a lock on your door and bars on your windows, it doesn’t guarantee you wont have stuff stolen from your home, but does make it take more time and more work.</p><h4>Let’s get into the maths</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZtIrZTUw-OjeF-Oy4tq5hw.png" /></figure><p>This is the smallest possible value for the modulus n for which the RSA algorithm works.</p><p>Now say we want to encrypt the message m = 7</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*EODyzqyZ9XUfyW50pEqMcw.png" /></figure><p>The ciphertext C = 13. And the decrypted text is m = 7</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/1*lMn1xQvC2prCl8HKmEY4yw.png" /></figure><h3>Breaking the algorithm</h3><p>It all starts with a big number, N, that you’ll need to find the factors of to break into some encrypted data.</p><p>As you don’t know what those factors are, you can make a guess, a number g that is less than N. We don’t need the guess to be a pure factor of N it could also be a number that shares some factors with N.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*AVrtDG3DDBdE6Yo4UxUh2Q.png" /></figure><p>Numbers that share factors are ok because of Euclid’s algorithm a method to check for and find common factors. So, to find a factor of N, we don’t have to guess a factor of N — guessing numbers that share factors with N works, too, thanks to Euclid. If the algorithm finds any shared factors with N we can just divide N by this factor and get the other factor.</p><p>But for the big numbers used in encryption, it’s astronomically unlikely that any single guess will share a factor with N. So, we are going to use a mathematical trick to get a better guess.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*4QH7CLB99C7pbyOyfYuMmw.png" /></figure><h4>Mathematical trick 1</h4><p>For any pair of whole numbers that don’t share a factors, if you multiply one of them by itself enough times, you’ll eventually arrive at some whole number multiple of the other number, plus 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*Ah44VHGYkI0qEaFBQ4BZPw.png" /></figure><p>So for our number N and our not so good g guess we’re guaranteed that some power of g is equal to some multiple of N, plus 1 .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*28xDCkfXaYk0ncy6dO0X-w.png" /></figure><p>If we rearrange this equation we get.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*pYECHxVPYr-k5zYjGRPN0w.png" /></figure><p>And we can find shared factors using Euclid’s algorithm</p><blockquote>If this is it why couldn’t we use this to get our factors of N and break the encryption?</blockquote><p><strong>Problems</strong></p><ol><li>One of the new guesses might itself be a multiple of N, in which case the other would be a factor of m and neither would be useful to us in any way.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*YDQY8VvF6RDr_9xMzL64qg.png" /></figure><ol><li>The power “p” might be an odd number , in which case p/2 isn’t a whole number and so our guess taken to the power of p/2 probably isn’t a whole number either.</li></ol><p>for a random starting guess, it turns out that at least 3/8 ths of the time (37.5%) neither of these problems happens</p><p>3. The biggest problem is, How do we find p?</p><p>For a clasical computer, calculate how many times do we have to multiply a number for itself to get a multiple of N + 1 is really hard.</p><h3>The Quantum advantage</h3><p>Unlike a normal computation which gives only one answer for a given input, a quantum computation can simultaneously calculate a bunch of possible answers for a single input by using a quantum superposition.</p><p>The key behind fast quantum computations is to set up a quantum superposition that calculates all possible answers at once while being cleverly arranged so that all of the wrong answers destructively interfere with each other.</p><p>Unlike a normal computation which gives only one answer for a given input, a quantum computation can simultaneously calculate a bunch of possible answers for a single input by using a quantum superposition.</p><p>The key behind fast quantum computations is to set up a quantum superposition that calculates all possible answers at once while being cleverly arranged so that all the wrong answers destructively interfere with each other.</p><p>For doing that we will use Shor’s algorithm!!!</p><h4>Mathematical trick 2</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/1*IfUXgwScaCjN5wNdsTMbDQ.png" /></figure><p>If we take our guess to a random power , it’s probably going to be some other number more than a multiple of N lets say “r” more, if we raise our guess to that random power plus p, it’s again “r” more than a multiple of N . If we raise our guess to that random power plus 2 p, it’s again “r” more than a multiple of N. And so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*Ki0urr-3pCJ8Sm3S8INOSw.png" /></figure><p>So the power p that we’re looking for has a repeating property where if we take another power and add (or subtract) p to it, the amount more than a multiple of N stays the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*_0ebKBvrTZeOJ7LiiAC0QQ.png" /></figure><h4>Quantum</h4><p>If we take the superposition of all possible powers and measure the “amount more than a multiple of N part, then we’ll randomly get one of the possible “amounts more than a multiple of N” as the output. This means we must be left with a superposition of purely the powers that could have resulted in a remainder of “r”.</p><p>And in our case, because of the repeating property, those powers are all numbers that are “p” apart from each other. So the numbers repeat with a frequency of 1/p.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*Jn1hoeLZiMh6wovamVE_qg.png" /></figure><p><em>Fourier transform</em></p><blockquote>Fourier transform is a mathematical transform that decomposes a function (often a function of time, or a signal) into its constituent frequencies.</blockquote><p><em>Quantum Fourier transform</em></p><p>When you put IN a superposition of numbers, you get out a superposition of superpositions and the sine waves add together or subtract and cancel out. If you put in a superposition of numbers that are all separated by an amount p, all those sine waves interfere so that what you get out, is the single quantum state representing 1/p!!</p><p>As long as p is even we can now finally raise our guess to the power p over two and add or subtract one, and as long as we don’t get an exact multiple of N, we are guaranteed to have a number that shares factors with N. And therefore we can use Euclid’s algorithm those factors</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*eidaATCM3560VbP5p6Nz3A.png" /></figure><h3>Let’s Code</h3><blockquote>This code is from a lab from <a href="https://qiskit.org/events/summer-school/">Qiskit summer school</a>. The code will be python, and we will use qiskit for the circuit implementation. We will factor N=15</blockquote><h3>1. Initializing the qubits</h3><p>We will need to initialize our qubits as described above by applying a Hadamard gate on each of the 𝑛 measurement qubits. We will also set the target qubits to |1⟩, since that is the eigenstate onto which the unitary operator 𝑈 will be applied. Here, |1⟩ is initialized by applying an 𝑋 gate on the last qubit.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a30a06ec17f7a4964224feea3ab9b23/href">https://medium.com/media/0a30a06ec17f7a4964224feea3ab9b23/href</a></iframe><h3>2. Modular exponentiation</h3><p>We have created a function called a_x_mod15 below which takes in two arguments, a and x, and implements the unitary operator</p><p>𝑈=𝑎𝑥 mod 15</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97c980ca88c00e799402f967e5a14d41/href">https://medium.com/media/97c980ca88c00e799402f967e5a14d41/href</a></iframe><blockquote>Note that the function a_x_mod15 creates a 4-qubit unitary controlled by an additional fifth qubit. In order to use this gate, you will need to append it to your quantum circuit using Qiskit&#39;s circuit.append() function by passing in the five qubits in a list containing the control qubit first, followed by the four target qubits.</blockquote><h3>3. Implementing the inverse quantum Fourier transform</h3><p>The last step before measuring the first 𝑛n qubits is the implementation of the inverse quantum Fourier transform.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9eb1da1555d3fab004020e05de2d54e/href">https://medium.com/media/c9eb1da1555d3fab004020e05de2d54e/href</a></iframe><h3>4. Shor Program</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65ee90e0c89b04c8efcf7f22b18b8a64/href">https://medium.com/media/65ee90e0c89b04c8efcf7f22b18b8a64/href</a></iframe><p>You will get a circuit like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*BZKWqvvPThcj0H4rlYuQLQ.png" /></figure><p>In order to run your quantum circuit and get the measurement outcomes, you simply need to run Qiskit&#39;s execute function as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e65e812edf47c19406969def85c7fc0b/href">https://medium.com/media/e65e812edf47c19406969def85c7fc0b/href</a></iframe><blockquote>Note: We are using the qiskit simulator we are not running the circuit on a real quantum device.</blockquote><p>We get this result</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*JB1o36Cl994zR0goBKrloA.png" /></figure><p>We can now convent the values from binary to Numbers</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6efb83050270fa00d3009ddfe1531329/href">https://medium.com/media/6efb83050270fa00d3009ddfe1531329/href</a></iframe><pre>Measured 8<br>Measured 12<br>Measured 4<br>Measured 0</pre><blockquote>Note: The values on the picture are writen from the less significant bit (botton number) to the most significant bit (top number)</blockquote><p>We can finaly postprocess clasically our solutiuon checking the constraints</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05456fc990d41cad9afce5045e2cb964/href">https://medium.com/media/05456fc990d41cad9afce5045e2cb964/href</a></iframe><pre>Measured 8<br>(1, 15)<br>Measured 12<br>(5, 3)<br>Measured 4<br>(5, 3)<br>Measured 0<br>(1, 15)</pre><p>And we finally get the Factors 3 and 5!!!!!</p><h3>Why haven’t I lost my security on the Internet yet?</h3><p>That is because the biggest actual quantum implementations of Shor’s algorithm don’t have enough memory to hold more than a few bits, which only allows factoring small numbers.</p><p>To break the number I wrote at the beginning of the post, the one with 250 digits, will take 5900 quantum bits that’s far away of todays quantum computers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jiEQp13mAyPTyo8q.jpg" /></figure><h3>Code (soon)</h3><ul><li><a href="https://github.com/morcu">github.com/morcu</a></li></ul><h3>Contact</h3><ul><li><a href="/service/mailto:david.morcuende.c@gmail.com">david.morcuende.c@gmail.com</a></li><li><a href="https://www.linkedin.com/in/david-morcuende-cantador-883a22155/">David Morcuende Linkedin</a></li></ul><h4>Bibliography</h4><p><a href="https://qiskit.org/events/summer-school/">https://qiskit.org/events/summer-school/</a></p><p><a href="https://qiskit.org/textbook/preface.html">https://qiskit.org/textbook/preface.html</a></p><p><a href="https://www.youtube.com/watch?v=AQDCe585Lnc">https://www.youtube.com/watch?v=AQDCe585Lnc</a></p><p><a href="https://www.di-mgt.com.au/rsa_alg.html">https://www.di-mgt.com.au/rsa_alg.html</a></p><p><a href="https://www.youtube.com/watch?v=lvTqbM5Dq4Q">https://www.youtube.com/watch?v=lvTqbM5Dq4Q</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b365676363c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Classifying environmental audio recordings]]></title>
            <link>https://morcu.medium.com/classifying-environmental-audio-recordings-9500a2112234?source=rss-782cc2dab484------2</link>
            <guid isPermaLink="false">https://medium.com/p/9500a2112234</guid>
            <category><![CDATA[conv2d]]></category>
            <category><![CDATA[image-classification]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[sound-classification]]></category>
            <dc:creator><![CDATA[David Morcuende]]></dc:creator>
            <pubDate>Wed, 01 Jul 2020 19:34:36 GMT</pubDate>
            <atom:updated>2020-07-03T14:27:13.486Z</atom:updated>
            <content:encoded><![CDATA[<h3>Classifying Environmental Audio Recordings</h3><p>Making a machine learning model to classify 50 different environmental audio recordings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*qbm59CMEatqzt5K-KN_3rQ.png" /></figure><h4><strong>Dataset</strong></h4><p>The dataset that has been used is the <a href="https://github.com/karolpiczak/ESC-50">ESC-50</a> dataset</p><p>The ESC-50 dataset is a labeled collection of 2000 environmental audio recordings suitable for benchmarking methods of environmental sound classification.</p><p>If we load the data we can see that there are 7 columns but we only need the audio filenames and the category.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-explore%2Fv%2F1%26cellId%3D3&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-explore%2Fv%2F1%26cellId%3D3&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fdavid-morcuende-c%2Fprofile_images%2F838c26273259477c91c825f1e213f085%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5f9b520759f2d98fcd2272ee9896746/href">https://medium.com/media/e5f9b520759f2d98fcd2272ee9896746/href</a></iframe><p>So we are deleting the unnecessary columns and creating a new one with the encoded categories.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-explore%2Fv%2F1%26cellId%3D6&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-explore%2Fv%2F1%26cellId%3D6&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fdavid-morcuende-c%2Fprofile_images%2F838c26273259477c91c825f1e213f085%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/58f0d515a3487aae7bd9f74bafca6259/href">https://medium.com/media/58f0d515a3487aae7bd9f74bafca6259/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-explore%2Fv%2F1%26cellId%3D7&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-explore%2Fv%2F1%26cellId%3D7&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fdavid-morcuende-c%2Fprofile_images%2F838c26273259477c91c825f1e213f085%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e77b7a89dc7d2f612966c3cf9eb2045/href">https://medium.com/media/5e77b7a89dc7d2f612966c3cf9eb2045/href</a></iframe><p>We can see that there are 50 different categories and that every category is balanced</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-explore%2Fv%2F1%26cellId%3D9&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-explore%2Fv%2F1%26cellId%3D9&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fdavid-morcuende-c%2Fprofile_images%2F838c26273259477c91c825f1e213f085%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/17443256ca097d03b70e07899aada2e4/href">https://medium.com/media/17443256ca097d03b70e07899aada2e4/href</a></iframe><h4>Transforming sound to image</h4><p>To transform sound to an image we are going to use the librosa library.</p><p>First, we are transforming the audio to a waveplot.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-explore%2Fv%2F1%26cellId%3D12&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-explore%2Fv%2F1%26cellId%3D12&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fdavid-morcuende-c%2Fprofile_images%2F838c26273259477c91c825f1e213f085%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/d50947dd3058f6432c46a8b41a269def/href">https://medium.com/media/d50947dd3058f6432c46a8b41a269def/href</a></iframe><p>This example is from a clock tick audio, we can listen to it with the Ipython Display utils library.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-explore%2Fv%2F1%26cellId%3D13&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-explore%2Fv%2F1%26cellId%3D13&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fdavid-morcuende-c%2Fprofile_images%2F838c26273259477c91c825f1e213f085%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f13ec88b9bd8d31d1e5885ed52f5731/href">https://medium.com/media/7f13ec88b9bd8d31d1e5885ed52f5731/href</a></iframe><p>Once having the waveplot, we are getting a spectrogram from it, again with librosa.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-explore%2Fv%2F1%26cellId%3D14&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-explore%2Fv%2F1%26cellId%3D14&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fdavid-morcuende-c%2Fprofile_images%2F838c26273259477c91c825f1e213f085%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/5038ee43374f9275a5dba7c70e40d66f/href">https://medium.com/media/5038ee43374f9275a5dba7c70e40d66f/href</a></iframe><p>And the normalized spectrogram</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-explore%2Fv%2F1%26cellId%3D15&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-explore%2Fv%2F1%26cellId%3D15&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fdavid-morcuende-c%2Fprofile_images%2F838c26273259477c91c825f1e213f085%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc645d2e7f035c45407b7bc5dde10c75/href">https://medium.com/media/dc645d2e7f035c45407b7bc5dde10c75/href</a></iframe><p>Now that we can transform audio to image we are making a function to process all the audios and transform it into images. We are going to save them using the same directory structure that then the PyTorch library ImageFolder will need.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/1*yjFTGllrGFYsVIJW9E8E2A.png" /></figure><p>For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*YcnGGAhkZanExc9K3MvQjQ.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-audio2img%2Fv%2F1%26cellId%3D0&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-audio2img%2Fv%2F1%26cellId%3D0&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fdavid-morcuende-c%2Fprofile_images%2F838c26273259477c91c825f1e213f085%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f408fce7ce7b918709d3c3c4fb36cb2/href">https://medium.com/media/3f408fce7ce7b918709d3c3c4fb36cb2/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-audio2img%2Fv%2F1%26cellId%3D1&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-audio2img%2Fv%2F1%26cellId%3D1&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fdavid-morcuende-c%2Fprofile_images%2F838c26273259477c91c825f1e213f085%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f8439ab2309d8654a1ebeeb263ca703/href">https://medium.com/media/0f8439ab2309d8654a1ebeeb263ca703/href</a></iframe><h4>Model</h4><p>We are using PyTorch to build and train the model, so we can use the ImageFolder function from torchvision to load all the image. But first, we are resizing it to a 32 x 32 image and converting them to tensors.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-model%2Fv%2F1%26cellId%3D1&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-model%2Fv%2F1%26cellId%3D1&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fdavid-morcuende-c%2Fprofile_images%2F838c26273259477c91c825f1e213f085%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/447a23a9fda4b05020662a9390d92837/href">https://medium.com/media/447a23a9fda4b05020662a9390d92837/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-model%2Fv%2F1%26cellId%3D2&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-model%2Fv%2F1%26cellId%3D2&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fdavid-morcuende-c%2Fprofile_images%2F838c26273259477c91c825f1e213f085%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6ad2a36e9561750d5931b53cd08e102/href">https://medium.com/media/b6ad2a36e9561750d5931b53cd08e102/href</a></iframe><p>One example of the tensor and the image could be:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-model%2Fv%2F1%26cellId%3D4&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-model%2Fv%2F1%26cellId%3D4&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fdavid-morcuende-c%2Fprofile_images%2F838c26273259477c91c825f1e213f085%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/911b516e567add765acc3985f4ef3a90/href">https://medium.com/media/911b516e567add765acc3985f4ef3a90/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-model%2Fv%2F1%26cellId%3D6&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-model%2Fv%2F1%26cellId%3D6&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fdavid-morcuende-c%2Fprofile_images%2F838c26273259477c91c825f1e213f085%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/f525c3f172e750bed83a0943c9faef3c/href">https://medium.com/media/f525c3f172e750bed83a0943c9faef3c/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-model%2Fv%2F1%26cellId%3D7&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-model%2Fv%2F1%26cellId%3D7&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fdavid-morcuende-c%2Fprofile_images%2F838c26273259477c91c825f1e213f085%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/f67eb8c00fe53e4578e3f12925d6458c/href">https://medium.com/media/f67eb8c00fe53e4578e3f12925d6458c/href</a></iframe><p>Then we split the dataset into 3: train, validation, and test, 75%, 20%, and 10% respectively.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-model%2Fv%2F1%26cellId%3D9&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-model%2Fv%2F1%26cellId%3D9&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fdavid-morcuende-c%2Fprofile_images%2F838c26273259477c91c825f1e213f085%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/03094f9bd19b0cf70e458f6f3b84f7b5/href">https://medium.com/media/03094f9bd19b0cf70e458f6f3b84f7b5/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-model%2Fv%2F1%26cellId%3D10&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-model%2Fv%2F1%26cellId%3D10&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fdavid-morcuende-c%2Fprofile_images%2F838c26273259477c91c825f1e213f085%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ba362c1bbb15f8b88a4d9250636e489/href">https://medium.com/media/2ba362c1bbb15f8b88a4d9250636e489/href</a></iframe><p>and finally, we get a dataloader from those datasets</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-model%2Fv%2F1%26cellId%3D12&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-model%2Fv%2F1%26cellId%3D12&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fdavid-morcuende-c%2Fprofile_images%2F838c26273259477c91c825f1e213f085%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b2dc5b767befd4741cf401aacc34710/href">https://medium.com/media/2b2dc5b767befd4741cf401aacc34710/href</a></iframe><p>We are using a batch size of 32. To see one batch from the dataloader we can use this function:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-model%2Fv%2F1%26cellId%3D13&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-model%2Fv%2F1%26cellId%3D13&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fdavid-morcuende-c%2Fprofile_images%2F838c26273259477c91c825f1e213f085%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/de962957f9e3545ac6a058ea4efb553d/href">https://medium.com/media/de962957f9e3545ac6a058ea4efb553d/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-model%2Fv%2F1%26cellId%3D14&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-model%2Fv%2F1%26cellId%3D14&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fdavid-morcuende-c%2Fprofile_images%2F838c26273259477c91c825f1e213f085%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/54efb6c8fc4fc4fdc6d87f0858f3bf5c/href">https://medium.com/media/54efb6c8fc4fc4fdc6d87f0858f3bf5c/href</a></iframe><p>Then we define some metrics and validations with the class <strong>ImageClassificationBase</strong> that has functions to calculate the training and validation losses.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-model%2Fv%2F1%26cellId%3D16&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-model%2Fv%2F1%26cellId%3D16&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fdavid-morcuende-c%2Fprofile_images%2F838c26273259477c91c825f1e213f085%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/78e9b1260bfa66754b6b9b92c23b96b8/href">https://medium.com/media/78e9b1260bfa66754b6b9b92c23b96b8/href</a></iframe><p>Finally, we build and train the model, in this case, it will be like cifar10 model.</p><p>The model:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-model%2Fv%2F1%26cellId%3D17&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-model%2Fv%2F1%26cellId%3D17&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fdavid-morcuende-c%2Fprofile_images%2F838c26273259477c91c825f1e213f085%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/46ba67af7ad82febb90f8006ab2682d0/href">https://medium.com/media/46ba67af7ad82febb90f8006ab2682d0/href</a></iframe><p>We define some auxiliar function for the dataloader and to use GPU accelerators</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-model%2Fv%2F1%26cellId%3D20&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-model%2Fv%2F1%26cellId%3D20&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fdavid-morcuende-c%2Fprofile_images%2F838c26273259477c91c825f1e213f085%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/3cd8eaa7d9c4512032c1f7fbfe96975d/href">https://medium.com/media/3cd8eaa7d9c4512032c1f7fbfe96975d/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-model%2Fv%2F1%26cellId%3D24&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-model%2Fv%2F1%26cellId%3D24&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fdavid-morcuende-c%2Fprofile_images%2F838c26273259477c91c825f1e213f085%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6392452721c1bc7935367957cc6cd8b/href">https://medium.com/media/a6392452721c1bc7935367957cc6cd8b/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-model%2Fv%2F1%26cellId%3D23&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-model%2Fv%2F1%26cellId%3D23&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fdavid-morcuende-c%2Fprofile_images%2F838c26273259477c91c825f1e213f085%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/66e85fddd1b0a774352c4b17357ac081/href">https://medium.com/media/66e85fddd1b0a774352c4b17357ac081/href</a></iframe><p>The training, in this case, we run for 104 epochs with a lr of 0.001and another 25 epochs with 0.0001.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-model%2Fv%2F1%26cellId%3D27&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-model%2Fv%2F1%26cellId%3D27&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fdavid-morcuende-c%2Fprofile_images%2F838c26273259477c91c825f1e213f085%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4575b84cfcb1a001b6f6b56aa412a3a/href">https://medium.com/media/d4575b84cfcb1a001b6f6b56aa412a3a/href</a></iframe><p>Both with the adam optimizer, the losses are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*_x-krt0zHapANN-aOYX08g.png" /></figure><p>And the accuracy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*4Ji1AAXcMUlwmN75-s9a1A.png" /></figure><p>There are clearly overfitting and there aren’t so good results, so we will have to try different models.</p><p>On the test results, it doesn’t perform good either</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-model%2Fv%2F1%26cellId%3D34&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fdavid-morcuende-c%2Fesc-50-audio-clasification-model%2Fv%2F1%26cellId%3D34&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fdavid-morcuende-c%2Fprofile_images%2F838c26273259477c91c825f1e213f085%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/a057618312231548e738f0972d620b8a/href">https://medium.com/media/a057618312231548e738f0972d620b8a/href</a></iframe><p>You can find all the code on <a href="https://github.com/Morcu/ESC-50-audio-clasification">https://github.com/Morcu/ESC-50-audio-clasification</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9500a2112234" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>