<?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 Thenjiwe kubheka on Medium]]></title>
        <description><![CDATA[Stories by Thenjiwe kubheka on Medium]]></description>
        <link>https://medium.com/@thenjiwekubheka2?source=rss-e668bb8b2f76------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xleclQkvHCW9eqnTVFROHg.jpeg</url>
            <title>Stories by Thenjiwe kubheka on Medium</title>
            <link>https://medium.com/@thenjiwekubheka2?source=rss-e668bb8b2f76------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 20:17:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thenjiwekubheka2/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[Set Theory]]></title>
            <link>https://levelup.gitconnected.com/set-theory-8ee4d66aacf5?source=rss-e668bb8b2f76------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ee4d66aacf5</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Thenjiwe kubheka]]></dc:creator>
            <pubDate>Thu, 19 Dec 2024 15:51:04 GMT</pubDate>
            <atom:updated>2025-01-17T18:28:16.034Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*KWpr6ueLofBGjGB-FurVtA.png" /></figure><p>Set theory is a branch of mathematics that has been embraced by Computer Scientists due to its practicality. Sets are a member of Data Structures and Algorithms as they can store and manipulate distinct elements. Set Operations such as union, intersection, difference, and symmetric difference are essential for most algorithms.</p><p><strong>Sets</strong></p><p>A set is an unordered collection of objects called elements. These elements are packaged into a theoretical ‘container’ according to comparable properties, such as numbers, programming languages, team players etc.</p><p>We indicate that an item is a set by using a capital letter as its name with curly braces {} that contain elements within a set. The elements are logged inside of the curly brackets separated by a comma. If we wanted to know the programming languages chosen for a specific technical team, we would represent the expression as follows;</p><pre>P= {Python, C++, JavaScript, Rust}.</pre><p>P is the set containing elements Python, C++, JavaScript and Rust, the elements are separated using a comma and are in no specific order. The symbol ∈ is used to indicate that an element is part of a set and ∉ is used to specify an element is not part of a set.</p><p>Example;</p><p>Python ∈ P and Java ∉ P.</p><p><strong>Cardinality | |</strong></p><p>The cardinality is the size of the set. The number of elements inside the set decides the cardinality of the set. We use the figure | | to signal cardinality and embed the name of the set in-between.</p><p>Example:</p><p>The cardinality of our set P is 4 as P contains four elements</p><p>|P| = 4</p><p><strong>Finite and Infinite sets</strong></p><p>Finite sets are sets that hold elements that have a conclusion. Perfect example would be the set containing the English Alphabets.</p><pre>B={A,B,C,....X,Y,Z} </pre><p>On the contrary, infinite sets accommodate elements that are continuous and boundless. Integers are limitless and are an exemplar of infinite sets.</p><pre>ℤ ={...,-2,-1,0,1,2,....} </pre><p><strong>Set Notation</strong></p><p>Customary conventional methods deployed to depict sets are:</p><ul><li>Listing</li><li>Set Builder Notation, and</li><li>Interval Notation.</li></ul><p><strong>Listing Method</strong></p><p>Lists elements of a set and sets them apart by employing a comma.This convention allows for listing of elements inside the curly braces separating the elements by commas. P= {C++, JavaScript, Python, Rust}. Applicable when dealing with finite sets.</p><pre>P= {C++, JavaScript, Python, Rust}</pre><p><strong>Set Builder Notation</strong></p><p>This technique addresses the limitation of the listing method by describing properties of the elements.</p><pre>A= {y|y∈ ℕ, 1&lt;=y&lt;=5} </pre><p>The above declaration can be expressed in natural language as;</p><p>Y is an element of set A such that it is a Natural number and is greater than and equal to 1 and less than and equal to 5.</p><p><strong>Interval Notation</strong></p><p>Chronicles values between two elements on a number line. Presume the variable y is between 0 and 5, y ∈ (0,5).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*y2Cs-2hLxbC_fYfoVuv2ZA.png" /></figure><p>Values 0 and 5 are represented on the number line accompanied by two circles known as open intervals. Open intervals indicate that 0 and 5-the endpoints are not included in the expression. This computation starts from 1 and ends at 4 as 0&lt;y&lt;5.</p><p>A numeric expression that includes 5 and not 0 would use a mix of open and closed intervals, y ∈ (0,5]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*0LV4qGkjmwoS__4RS4td8A.png" /></figure><p>The black point stipulates a closed interval with the square bracket specifying that 5 is included in the expression. Our computation is revised to 0&lt;y&lt;=5.</p><p><strong>Common Sets</strong></p><p><strong>Subsets ⊆</strong></p><p>The sign ⊆ is used to signify subsets. Suppose we have two sets A and B; A is a subset of B if all the elements in A are contained in B.</p><pre>A= {6,7,8} and B= {5,6,7,8,9} </pre><p>A is a subset of B as its elements 6,7,8 is in set B. We write it as follows; A ⊆ B, but B is not a subset of A as the elements 5 and 9 are not in A. If A and B had the same elements, then they would be equal.</p><pre>A= {6,7,8} and B= {6,7,8}</pre><p>This indicates that A is a subset of B and B is a subset of A, qualifying the two sets as equal.</p><pre>A ⊆ B and B ⊆ A, therefore A=B</pre><p>Also note that every set is a subset of itself.</p><pre>A ⊆ A = A, B ⊆ B =B, C ⊆ C =C </pre><p><strong>Empty Set</strong></p><p>An empty set contains no elements. The characters ⦰ and {} identify an empty set.</p><p>The empty set is a subset of all other sets including itself. An element cannot be a subset of another set if it does not contain the same elements. B is not a subset of A as it contains the extra value 9.</p><pre>A= {6,7,8} and B= {,6,7,8,9} </pre><p>There are no elements in the empty set to prove that it is not a subset of any set, consequently it is a subset of every set.</p><p><strong>Natural Numbers ℕ</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*PPc2XJlFNnaprbuK4ZAOZg.png" /></figure><p>The set of natural numbers is comprised of positive solid numbers from 1 to infinity. Represented as : N= {1,2, 3,…,∞}.</p><p><strong>Whole Numbers W</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*Wd91nkKMSCW5QFSd1kY-sg.png" /></figure><p>The set of whole numbers is like the set of natural numbers with the inclusion of 0. The set of whole numbers will be from 0 to positive infinity. W= {0,1,2, 3,…, ∞}.</p><p><strong>Integers ℤ</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*xXtvILnxC4yDeTyTf5GR6g.png" /></figure><p>The set carrying Integers is everything within the whole numbers set increased by the negative numbers. Integers are solid counting numbers from negative infinity to positive infinity. <strong>ℤ = </strong>{- ∞,….,-2,-1,0,1,2,…, ∞}.</p><p><strong>Rational Numbers </strong>ℚ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*On3fZCKdczk2f714EYDPYQ.png" /></figure><p>The set of Rational numbers is written in the form a/b, where b cannot be 0. Both the numerator and the denominator must be integers. Q= {- ∞ ,…,-1,-4/5,-3/5,-2/5,-1/5,0,1/5,2/5,3/5,4/5,1…, ∞}.</p><p><strong>Real Numbers </strong>ℝ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*ULRUPYNgARgP1htRr2FYWw.png" /></figure><p>Any number which can be plotted on the number line falls within the set of real numbers. These include Integers, Rational numbers, whole numbers, natural numbers, and irrational numbers.</p><p><strong>Powerset</strong></p><p>The powerset of a set is all subsets of a specific set. A capital letter P with the set name inside the brackets () stipulates a Powerset.</p><pre>Example: <br><br>B = {1,2,3} <br><br>P(B)= {⦰, {1}, {2}, {3}, {1,2}, {1,3}, {2,3}, {1,2,3}} </pre><p>P(B) encompasses every subset of set B including the empty set. The cardinality of a powerset is 2 ^n with n being the cardinality of the set. Set B has three elements, the cardinality of P(B) = 2³ =8. Powerset B should possess eight subsets.</p><p>|P(A)| =8</p><p><strong>Set Operations</strong></p><p>Used to combine two or more sets into a single set that retains elements from the original sets.</p><p><strong>Union U</strong></p><p>The union of set A and B is the set containing all elements in A OR B. Drafted as A ∪ B.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*KWpr6ueLofBGjGB-FurVtA.png" /></figure><pre>A= {1,2,5,7,12} B= {1,2,4,6,8,9,10,11) <br><br>A ∪ B = {1,2,3,4,5,6,7,8,9,10,11,12} </pre><p>A ∪ B integrates all the elements in A or in B. A union B in set builder notation is-X is an element of A union B if and only if x is an element of A or x is an element of B.</p><pre>A ∪ B = {x| x ∈ A OR x ∈ B}</pre><p><strong>Intersection ∩</strong></p><p>Utilized to combine elements common to both sets A<strong> AND </strong>B.</p><pre>A= {3,6} B= {5,8} <br><br>A ∩ B = {6,8} </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*xK5cjdkc9xY8vaof5MeRLg.png" /></figure><p>Elements 6 and 8 are common to both sets A and B.</p><p>A intersection B in set builder notation is-X is an element of A intersection B if and only if x is an element of A AND x is an element of B.</p><pre>A ∩ B = {x| x ∈ A AND x ∈ B}</pre><p><strong>Difference -</strong></p><p>The difference operator (-) simply subtracts elements. The difference of A-B would subtract elements from B to form the new set.</p><pre>A= {1,2,3,4,5,6,7,8,9} B= {1,2,3,4,5,6} <br><br>A-B = {7,8,9} </pre><p>All the elements of B and those common to both A AND B are withdrawn in set A-B. Only elements 7,8,9 which are not part of set B remain.</p><p>The difference of sets A and B in set builder notation is-X is an element of A minus B if and only if x is an element of A and x is not an element of B.</p><pre>A - B = {x| x ∈ A and x ∉ B}. </pre><p><strong>Symmetric Difference ⊕</strong></p><p>Fuses the elements of A OR B then subtracts elements common to both A AND B. The symmetric difference of A and B equals the union of A <strong>OR</strong> B minus (–) the intersection of A <strong>AND</strong> B.</p><pre>A ⊕ B = (A ∪ B) - (A ∩ B)</pre><p>The symmetric difference of sets A and B in set builder notation is-X is an element of A symmetric difference B if and only if x is an element of A OR x is an element of B but not an element of the intersection of A and B.</p><pre>A ⊕ B = {x| (x ∈ A OR x ∈ B) and x ∉ A ∩ B}</pre><p><strong>Universal Set and The Complement</strong></p><p>The complement functions within the universal set. The universal set is a special set that contains all the elements under consideration or observation. We could have a set containing Real numbers, numbers commencing from 1 up to 100, or even just a set of even numbers. The universal set is often referred to as the universe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*XvUf_UI1iZbRZ0rS3Xx_aQ.png" /></figure><p>The rectangle is a universal set also integrating elements within its subset A.</p><pre>U= {1,4,5} <br><br>A= {2,3} <br></pre><p><strong>The Complement</strong></p><p>Isolates elements of a particular subset from that of the universal set. Given set A, the complement of A’ will hold everything in the universal set except the elements inside A. The complement of A is equal to the universal set minus A (A’ = U-A).</p><pre>U = {1,2,3,4,5,6,7,8,9,10} <br><br>A= {7,8,9} <br><br>B= {3,4,5} <br><br>A&#39; = {1,2,3,4,5,6,10} </pre><p>All the elements in A are removed from the complement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*RRRmAHMboAaigibIlO6QKQ.png" /></figure><p>The complement of A is all the elements outside of A and in the blue shaded area.</p><p><strong>Membership Tables</strong></p><p>Akin to Truth tables, membership tables use 0 and 1 to manifest the impact of set operations. 1 indicates an element is a member of the set and 0 suggests it is not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*T6KfvNlzHH8rYOvO-F5Gng.png" /></figure><p><strong>Algebraic Laws of Sets</strong></p><p>Addition, subtraction, division, and multiplication govern arithmetic equations and expressions. Algebraic laws of sets govern relationships between subsets of sets.</p><p>Only one proof theorem per algebraic regulation will be covered.</p><p><strong>Commutative Laws</strong></p><p>Under commutative law the order of the sets does not matter.</p><pre>A ∪ B = B ∪ A <br><br>A ∩ B = B ∩ A </pre><p>Commutative Law 1: AUB = B U A.</p><p>Equality can be revealed by exhibiting that AUB ⊆ B U A and B U A ⊆ AUB.</p><p>Assumption: x is an element of AUB.</p><pre>X ∈ AUB</pre><p>X is an element of AUB if and only if x is an element of A OR x is an element of B.</p><pre>X ∈ A OR X ∈ B</pre><p>Interpreted as X belong to B OR x belongs to A</p><pre>X ∈ B OR X ∈ A</pre><p>Simplification of the above expression.</p><pre>X ∈ BUA</pre><p>If x is an element of A union B as per above assumption, then x is also an element of B union A as per above proof.</p><pre>If X ∈ AUB then X ∈ BUA</pre><p><strong>Associative Laws</strong></p><p>Explores the grouping of the sets we are working on and how it does not affect the outcome.</p><pre>(A ∪ B) ∪ C = A ∪ (B ∪ C)  <br><br>(A ∩ B) ∩ C = A ∩ (B ∩ C)  </pre><p>Associative Law 1: (A ∪ B) ∪ C = A ∪ (B ∪C).</p><p>Assumption: x is an element of (A ∪ B) ∪ C.</p><pre>X ∈ (A ∪ B) ∪ C</pre><p>X is an element of (A ∪ B) ∪ C if and only if x is an element of AUB OR x is an element of C.</p><pre>X ∈ A ∪ B OR X ∈ C</pre><p>Simplification.</p><pre>X ∈ A Or X ∈ B OR X ∈ C</pre><p>∴</p><pre>X ∈ A OR X ∈ BUC</pre><p>Which is:</p><pre>X ∈ A U (BUC)</pre><p>If x is an element of (A ∪ B) ∪ C as per above assumption, then x is also an element of A ∪ (B ∪C) as per above proof.</p><p><strong>Distributive Laws</strong></p><pre>A ∪ (B ∩ C) = (A ∪ B) ∩ (AUC) <br><br>A ∩ (B U C) = (A ∩ B) U (A ∩ C) </pre><p>Distributive Law 1: A ∪ (B ∩ C) = (A ∪ B) ∩ (AUC).</p><p>Assumption: x is an element of A ∪ (B ∩ C). Xis an element of A ∪ (B ∩ C) if and only if x is in A OR x is in B ∩ C.</p><pre>X ∈ A OR X ∈ B ∩ C</pre><p>Rewrite as:</p><pre>X ∈ A OR (X ∈ B AND X ∈ C)</pre><p>Simplification:</p><pre>(X ∈ A OR X ∈ C) AND (X ∈ A OR X ∈ C) </pre><p>Written as sets:</p><pre>X ∈ (AUB) AND X ∈(AUC)<br>X ∈(AUB) ∩ (AUC)</pre><p>If x is an element of A ∪ (B ∩ C) as per above assumption, then x is also an element of (AUB) ∩ (AUC) as per above proof.</p><p><strong>Complement Laws</strong></p><pre>A U A&#39; = U <br><br>A ∩ A&#39; = ⦰ <br><br>U&#39;= ⦰ <br><br>⦰ = U </pre><p>Complement Law 1: A U A’ = U</p><p>A union the complement of A is a subset of the universal set as every set is a subset of the universal set.</p><pre>A U A&#39; ⊆ U</pre><p>Now we need to prove that U is a subset of A union complement A.</p><pre>U ⊆ A U A&#39; </pre><p>Assumption: x is an element of U.</p><pre>X ∈ U </pre><p>X can be in the set A or x can be in the complement of A.</p><pre>X∈ A OR X ∈ A&#39; </pre><p>Thus, x is an element of A U A’. Hence the same element that belongs to the universal set also belongs to the set of A U A’.</p><pre>U ⊆ A U A&#39;</pre><p>A U A’ = U as per above proof.</p><p><strong>Idempotent Laws</strong></p><pre>AUA =A <br>A ∩ A =A</pre><p>Idempotent Law 1: AUA =A.X is an element of AUA if and only if x is an element of A OR x is an element of A.</p><pre>X∈ A OR X∈ A</pre><p>The above statement is a repetition and can be rewritten as:</p><pre>X∈ A </pre><p>Suggesting x is in set A.</p><p><strong>Identity Laws</strong></p><pre>AU ⦰ =A <br><br>A ∩ ⦰ = ⦰ <br><br>AU U =U <br><br>A ∩ U =A </pre><p>Identity Law 1: A U A’ = U. Xis an element of A union the empty set if and only if x is an element of A or x is an element of the empty set.</p><pre>X∈ A OR X∈⦰</pre><p>The empty set cannot contain any elements as a result we can rewrite our statement as:</p><pre>X∈ A </pre><p>Consequently, X is in set A.</p><p><strong>De Morgan’s Laws</strong></p><pre>(A U B)&#39; = A&#39; ∩ B&#39; <br><br>(A n B)&#39; = A&#39; U B&#39; </pre><p>De Morgans Law 1: (A U B)’ = A’ ∩ B’.</p><p>Assumption: x is in the set (A U B)’. X is an element of (A U B)’if and only if x is not an element of A U B .</p><pre>X∉ AUB</pre><p>X is not in A AND x is not in B. Note that the ∉ symbol flips the union OR to the intersection AND.</p><pre>X∉ A AND X∉ B</pre><p>If x does not belong to A then it is an element of A complement. Equivalently, if x is not in B then it is an element of B complement.</p><pre>X∈ A&#39; AND X∈ B&#39;</pre><p>Therefore:</p><pre>X∈ A&#39; ∩ B&#39; </pre><p>In conclusion, sets are a fundamental data structure and proficiency is essential. A good programmer is also a good mathematician. Always aware of the fundamental elements of Computer Science and Mathematics. The article covers the essential components of set theory.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ee4d66aacf5" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/set-theory-8ee4d66aacf5">Set Theory</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Counting Objects In Python]]></title>
            <link>https://faun.pub/counting-objects-in-python-ed5a3c4321f2?source=rss-e668bb8b2f76------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed5a3c4321f2</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Thenjiwe kubheka]]></dc:creator>
            <pubDate>Mon, 02 May 2022 15:20:03 GMT</pubDate>
            <atom:updated>2022-05-02T15:20:03.040Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Serial problem solving is what we do right as programmers, “solve it one problem at a time”. Object tracking solves multiple problems such as keeping track of cars passing by the highway, objects on a conveyer belt the list goes on. In this article we are going to go through how its done.</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FT-H3k0A2Sp8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DT-H3k0A2Sp8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FT-H3k0A2Sp8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/269dbbca0b759387c064b6e589a55b95/href">https://medium.com/media/269dbbca0b759387c064b6e589a55b95/href</a></iframe><h3>Setting Up Our Environment</h3><p>In my previous article I discussed setting up virtual <a href="https://medium.com/geekculture/an-a-z-guide-on-managing-anaconda-environments-simplified-d8681b4f2161">environments in Conda</a>, and for this particular project I wanted to set up my development environment using my command prompt .</p><p>lets fire up Windows command prompt terminal. And create a folder track_it.</p><pre>mkdir track_it</pre><p>We then need to cd into our track it folder;</p><pre>cd C:\Users\gp2ca\track_it</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*X3q2Wp5Jipj9sew47iQG4w.png" /></figure><p>Now we need to create our virtual environment inside our track_it folder; The command is <strong>python</strong> then <strong>m</strong> for the module, <strong>venv</strong> is the specific module followed by the name of our environment, ours is simply <strong>tcount</strong>. The name <strong>tcount</strong> is short for traffic count and I feel like working on Python 3.8, hence we have specified our Python version.</p><pre>python -m venv tcount python=3.8</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/469/1*nExqjEEyFWoU0MPYnTe1Sw.png" /></figure><p>Lets check has the environment been created inside of our track_it folder;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*HfJLQ_bekfg13g0vkmvtKQ.png" /></figure><p>Now we need to activate it, it is more complex than just ‘conda activate and then the name of the environment. With this method we activate as follows;</p><pre>.\tcount\scripts\activate</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*ARD7jlg7Qm-vWd8kndZShA.png" /></figure><p>We can go ahead and run our Jupyter Notebook with the command</p><pre>jupyter notebook</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S_UkrInQ72zbgnYBXr9uhQ.png" /></figure><p>This will open Jupyter Notebook and we can see our virtual environment tcount inside there, but we are still using the global Python kernel. Starting Jupyter Notebook and Jupyter Lab inside of an in environment is quite futile as we must still associate our environment with Jupyter.</p><p>So we need to stop our Jupyter Notebook in the terminal and install ipykernel.</p><pre>pip install ipykernel</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*7Ax_oozJTo68QjeCZO0ipw.png" /></figure><p>Ipykernel allows us to attach a virtual environment to the jupyter notebook or lab, however you prefer it.</p><p>Now we want to use ipykernel and we will do this as follows;</p><pre>python -m ipykernel install --name = tcount</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*yjyamEJm-NhujSBVUPznCA.png" /></figure><p>We see that they are now linked. Lets also check all the different kernels we have running inside our Jupyter.</p><pre>jupyter kernelspec list</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*s0HxERIY00ecLIsXaiuuSg.png" /></figure><p>Lets run jupyter notebook and select our new environment which is tcount.</p><pre>jupyter notebook</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m8DdzH6saNYAVM9qHPH-yw.png" /></figure><p>After selecting the tcount environment we will see it as the selected virtual environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9pPGCffNYEQgEFGYqS0ocw.png" /></figure><h3>Object Detection</h3><p>We are doing two things for this task namely object detection followed by object tracking.</p><p>Object detection is detecting objects on individual frames, what do I mean by this.</p><p>Lets say we have a video or image the detection algorithm check everything frame by frame. We further extend this with object tracking that keeps a counter and furthermore labels the objects counted.</p><h3>Installing Dependencies</h3><p>We will start by installing open CV which is a Python framework used for computer vision projects. The command is as follows;</p><pre>!pip install opencv-python </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SRDpxfn1_1wnkjJ3kV_8xw.png" /></figure><p>Then we need to import open cv with the command;</p><pre>import cv2</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*c3AzX0AsQCFEfB6qSNCE0A.png" /></figure><p>Now we need to create a capture object to read from our video. I will be using a video supplied by <a href="https://pysource.com/blog/">Sergio Canu</a>.</p><pre>cap = cv2.VideoCapture(&#39;highway.mp4)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*qR14wa9AjLPXyj34U1akzw.png" /></figure><p>Now we need to loop through the frames one after the other, we will do this using a while loop.</p><pre>while True:<br>    ret, frame = cap.read()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*kL32LYY6eoEVYXsvu9MgMA.png" /></figure><p>Now we need to show our video frames in real-time;</p><pre>cv2.imshow(&#39;frame&#39;, frame)</pre><p>Finally we need an escape to the loop, we will use an await key event</p><pre>    key = cv2.waitKey(30)<br>    if key == 27:<br>        break<br>cap.release()<br>cap.destroyAllwindows()</pre><p>So we want to show the frame in realtime, open CV will loop continuously and we cannot close the window by simply pressing x. We need to press the key which is 27.</p><p>Now lets run our code;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*xMk0A3pgF5h3GYrDm2e6xQ.png" /></figure><p>Now our goal is to detect cars and we will be using object detection method for a stable camera. Stable camera means background is always the same only the objects change over time.</p><pre>object_detector = cv2.createBackgroundSubtractorMOG2()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*NdMGQweI7XShYPYTqCozMw.png" /></figure><p>Our variable object_detector will extract the moving objects from a stable camera.</p><p>We will extract these creating a mask where we will apply the detection on the frame;</p><pre>mask = object_detector.apply(frame)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*Mi0sLXwFuvjmC8qLYJlC4w.png" /></figure><p>Then we can apply the mask and run our code;</p><pre>cv2.imshow(&#39;mask&#39;,mask)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*qnxjWB_XrOvxoB0wuT7QJA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VNSRzhovJHFYGMiN8r2K_A.png" /></figure><p>The goal of a mask is to make everything black and exempt the object we want to detect and make them white.</p><p>All the vehicles and motorbikes must be white and everything else needs to be black.</p><p>Now we want to get the coordinates of all the white elements and remove the small elements we don’t need such as traffic signs, the speed meter on the bike and some of the trees.</p><p>So from the mask we need to extract the co-ordinates of the objects. We will do that cv2.findContours() function. We want to detect the boundaries of the white objects on the mask and we will also extract the information using the cv2.RETR_TREE and cv2.CHAIN_APPROX_SIMPLE function.</p><pre>cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*Msz_jPNatw1IVlNEAhxIkw.png" /></figure><p>Will then assign this to contours and _(the _ symbol) represents the hierarchy).</p><pre>contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE</pre><p>Now we want to loop through the contours and draw them on the frame we will use a blue color and our thickness is 2;</p><pre>for cnt in contours:<br>    cv2.drawContours(frame,[cnt],-1, (255,0,0),2)</pre><p>Lets run our code;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*wFWXZNQXTqaab7G7-Z3Lpg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Y-Ru2kGEQjWamdgVuy_8Q.png" /></figure><p>As you can see everything that was white is surrounded with blue, but we have a lot of things we do not need that have been drawn, we only want the cars and motor bikes.</p><p>We want to remove all of the small elements by first calculating the area then remove these elements.</p><pre>area = cv2.contourArea(cnt)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*6UzFKa_KjBIJsiSvKo1CPQ.png" /></figure><p>Then we add a condition to the area statement, saying if our area is greater than 100px then we draw our contours. Remember the cars and bikes have larger pixels.</p><pre>if area &gt;100:<br>    </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/144/1*lZ4CQV75X6KdyRAGinzQFg.png" /></figure><p>We still have a lot of things we do not need and to just simplify things we will select a region of interest and focus on it and the vehicles on the road.</p><p>To get the roi we need to say from which region of the image do we want to extract. So to check which position is to show the entire frame we have, we check the height, width and some channels</p><pre>height,width, _ = frame.shape<br>print(height, width)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*6i8DQ5W61tUnf_f6lLduZw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/186/1*caLWvWsVCw93BqDb-Kf6yQ.png" /></figure><p>Our height is 720 and width is 1280, of course it has printed it multiple times due to the while loop.</p><p>So if we want the region which is the middle of the screen then our x position will be around 400 and we can make our y 600.</p><pre>roi = frame[340,600,400:600]</pre><p>Now we want to show the roi;</p><pre>cv2.imshow(&#39;roi&#39;,roi)</pre><p>Very small we can tweak it a bit play around with our numbers our height starts from 500 to 720 and width from 500 to 800.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*n7AOBpEWPYu9JjmQPRXmkQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*eRHlP7LVOPj_EC9EcPdTHQ.png" /></figure><p>Now we can get rid of our print statement(indicated as a comment) as we have already determined our width and height.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*TMat0rfqfCvdc9y8BqE_1g.png" /></figure><p>Now we want to apply our mask to the specific area, the roi area, we will replace frame with roi.</p><p>First we will replace frame and roi with for the mask;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*BjZCTzqq6-FRRalkW4DX3Q.png" /></figure><p>Then replace it on the contours;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*6-V4MuJnZaht4OfSVWCKXg.png" /></figure><p>Now lets run our code;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*-Ep_VkkqDYo6zRqbdBp1GA.png" /></figure><p>Well the detection is still not 100% it can still be improved by applying history as this increases our precision.</p><p>As we have a stable camera and one that does not move we can assign our history to 100 and our varThreshold to 40. History is how many frames are used to build the background model, in our case a 100 frames. Both the history and threshold are done to reduce false positives.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*CA2vntdBywSOPRHsgih0Ng.png" /></figure><p>Now we can construct a rectangle to formalize our detection.</p><pre>x,y,w,h = cv2.boundingRect(cnt)<br>cv2.rectangle(roi, (x,y), (x + w,y + h), (255,0,0),3)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*hPUfVG7S8yLB72Ma3yKzpg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*Ooa0yHY1mEHD8IhcX-Kn8g.png" /></figure><p>One last thing we need to clean up is the grey shadows by cleaning up the mask;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*nDANlP4bCRq9Jtft8VU4_g.png" /></figure><p>We will use the threshold function to remove the grey pixels.</p><pre>_,mask = cv2.threshold(mask,254,255,cv2.THRESH_BINARY)</pre><p>Inside the threshold function we pass mask,254,255,cv2.THRESH_BINARY. Why these values, well pixels range from 0 to 255. The value 255 is completely white and below that we have different variants of grey. Closer to 0 is darker grey shades and closer to 255 is lighter grey shades.</p><p>Lets run our code;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*TmSp4oPeMMLAoy3QiA2dDA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/1*UV3fG4zNnrCqIhm70JyCcw.png" /></figure><p>As we can see the detection has improved drastically by just removing the grey pixels.</p><p>We are done with the object detection part and now we want to do some object tracking.</p><h3>Object Tracking</h3><p>For this section we are going to import the tracker.py file but before we import it, we want to drag and drop it into our track_it directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*EftJ4VDzsxJbKcKvVKRaxg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a2-5yAimVrDg_CgVD7e_0Q.png" /></figure><p>Now we can import everything from tracker;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*wNcEeJ1ei7xbYSq8o5ufig.png" /></figure><p>Then we want to create a tracker object, which will take the bounding boxes of the object and we need to save these into one array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*PvnMZpbnuTcMNG3f178OHA.png" /></figure><p>Now we will save all those bounding boxes into one array, first lets print out our bounding box values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*hfyuIAjmLzo2BvXBBROeAg.png" /></figure><p>As a car or motorbike passes it is attached to a bounding box which is attached to a set of values.</p><p>So we want these values in one array, we will create a variable detections which is assigned to an empty array,;</p><pre>detections = []</pre><p>So each time our model finds boxes it will put them inside an empty array and we want to append the x, y, width and height and print detections.</p><pre>detections.append([x,y,w,h])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*y3UWRQ_T2qGbaiMLV6t18g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*enzuf68Kewn_K-b2-2YTZQ.png" /></figure><p>As there are no cars an bikes passing by our array is empty, when cars start passing by the values are captured into the array.</p><p>We need to give the detections array to the tracker, which will in turn give us the history that has a unique id that is associated to each.</p><pre>boxes_ids = tracker.update(detections)</pre><p>We have a variable boxes_ids and assign it to the function tracker.update and pass in detections as our argument.</p><p>Next we want to loop through box_ids;</p><pre>for box_id in boxes_ids</pre><p>And what are we looking for while looping x,y, width, height, id and we assign those to box_id;</p><pre>x,y,w,h,id = box_id</pre><p>Then we want to put text to the boxes as they pass. We have our function cv2.putText and we only want to put text where there is the roi, str(id), the x value and the y value(we want to distance the objects a bit as they pass, need to avoid cluster. Then we apply the font and color</p><pre>cv2.putText(roi, str(id), (x,y -15),cv2.FONT_HERSHEY_PLAIN,1,(0,255,0),2)</pre><p>Lets run our code;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*3zlutSfawy-TxD0x6k9KdA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*G0b7uAu3A0lfOesHCi9RZw.png" /></figure><h3>Additional Material</h3><ul><li><a href="https://colab.research.google.com/drive/1oLz60-hUiDFqx2OfXZ_srInZqVi7_IJ_?usp=sharing">Google Colaboratory</a></li><li><a href="https://pysource.com/blog/">Blog - Pysource</a></li><li><a href="https://colab.research.google.com/drive/1Jt7TIShruo-AD8QY2esjvEmpT1l-hVOc?usp=sharing">Google Colaboratory</a></li></ul><figure><a href="https://faun.to/bP1m5"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BCiLLad3dvZLwBa-B5cAVQ.png" /></a></figure><p>Join FAUN: <a href="https://faun.to/i9Pt9"><strong>Website</strong></a><strong> </strong>💻<strong>|</strong><a href="https://faun.dev/podcast"><strong>Podcast</strong></a><strong> </strong>🎙️<strong>|</strong><a href="https://twitter.com/joinfaun"><strong>Twitter</strong></a><strong> </strong>🐦<strong>|</strong><a href="https://www.facebook.com/faun.dev/"><strong>Facebook</strong></a><strong> </strong>👥<strong>|</strong><a href="https://instagram.com/fauncommunity/"><strong>Instagram</strong></a><strong> </strong>📷|<a href="https://www.facebook.com/groups/364904580892967/"><strong>Facebook Group</strong></a><strong> </strong>🗣️<strong>|</strong><a href="https://www.linkedin.com/company/faundev"><strong>Linkedin Group</strong></a><strong> </strong>💬<strong>|</strong> <a href="https://faun.dev/chat"><strong>Slack</strong></a> 📱<strong>|</strong><a href="https://thechief.io/"><strong>Cloud Native</strong> <strong>News</strong></a><strong> </strong>📰<strong>|</strong><a href="https://linktr.ee/faun.dev/"><strong>More</strong></a><strong>.</strong></p><p><strong>If this post was helpful, please click the clap 👏 button below a few times to show your support for the author 👇</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed5a3c4321f2" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/counting-objects-in-python-ed5a3c4321f2">Counting Objects In Python</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An A — Z Guide On Managing Anaconda Environments Simplified!]]></title>
            <link>https://medium.com/geekculture/an-a-z-guide-on-managing-anaconda-environments-simplified-d8681b4f2161?source=rss-e668bb8b2f76------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8681b4f2161</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Thenjiwe kubheka]]></dc:creator>
            <pubDate>Sun, 17 Apr 2022 19:02:36 GMT</pubDate>
            <atom:updated>2022-04-17T19:02:36.404Z</atom:updated>
            <content:encoded><![CDATA[<h3>An A — Z Guide On Managing Anaconda Environments Simplified!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_jKvS7xTF4UCmIIGHOAbsw.png" /></figure><p>Often times Python newbies do not understand the need for these environments. In this article we will be covering the basics of virtual environments in Python.</p><h3>Why Are Virtual Environments Important In Python?</h3><p>Simplest to answer that is with an example;</p><p>Say you have developed a web application using libraries and frameworks from Python 3,6. Then months later you see there is a new version of Python which is 3.7.</p><p>You go ahead and upgrade from 3.6 to 3.7 and your application stops working, once you launch an investigation you notice that by upgrading to 3.7 your application which was build using 3.6 is no longer supported.</p><p>By upgrading the to Python 3.7 you also upgraded to 3.7 libraries and you used 3.6 libraries to build your application. Now the question comes up, do you downgrade or upgrade, maybe just downgrade certain libraries and modules to also be 3.6 compatible, but it will be difficult to determine which versions of these libraries and frameworks you used.</p><p>Hence virtual environments are important to help isolate projects.</p><h3>So What Are Virtual Environments?</h3><p>This of it as a room, whatever you do inside the room does not directly affect anyone outside the room. We can paint the room blue, it does not affect anything that is outside the room. Now lets get started with virtual environments.</p><h3>Conda Virtual Environments</h3><p>I prefer creating virtual environments using Conda, I will be showing you how to manage them in Anaconda and using the terminal.</p><h4>Conda Terminal</h4><p>Also referred to as Conda Command prompt, to access it navigate to the search bar and type in Anaconda Prompt, click on it and a Conda terminal will appear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZI_t4Lx1OFg0ijhPlbiqKg.png" /></figure><p>As you can see on the screen the default virtual environment is base. I have created a few virtual environments for illustration purposes.</p><p>To view all our virtual environments we type;</p><pre>conda env list</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*JGsVLl5wGt55e9hwimOsiA.png" /></figure><p>From the picture above we have 4virtual environments. The asterisks indicates the virtual environment we are working on currently. Now lets start by creating a virtual environment.</p><h4>Creating A Virtual Environment</h4><pre>conda create -name pydemo1<br>conda create -n pydemo1</pre><p>Both commands do the same thing, the other one name is typed fully and the other we just used (n) to indicate name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*taIJxZAzlxYUOsiXzArWKw.png" /></figure><h4>Activating An Environment</h4><p>Then we simply have to activate our environment using;</p><pre>conda activate pydemo1</pre><p>Notice we do not only tell conda to activate but also indicate which virtual environment to activate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*6HLBDG5Jr6PJLLbcX6YkSg.png" /></figure><p>To check if pydemo1 was added to the list of environments and if it is the main environment we use the list command again.</p><pre>conda env list</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*9FyYWKaCJsAlkaHUBqu5Nw.png" /></figure><p>And we can notice that pydemo1 is our current virtual environment by the asterisks.</p><p>Also notice the locations of the virtual environments are listed. What happens if we want to specify the location for our virtual environment.</p><h4>Specifying A Location Of An Environment</h4><p>The location is where our environment lives, so we can determine this by giving conda a the target path.</p><pre>conda create --prefix ./venv</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*1YaCXK6-A-c75kAxkD_UPg.png" /></figure><p>We have created a new virtual environment and added prefix so we can specify our directory/location.</p><p>We can simply activate it and list our environments to check.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*_202BEWaedZjtZEcyoUueA.png" /></figure><h4>Update A Conda Environment</h4><p>We want to update Python for a particular virtual environment. We are currently sitting at a Python 3.9 version, lets check and make sure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*Gdsd5aDbv0B-Z1lSJlHfaw.png" /></figure><p>Yes we are on 3.9.7 and we will type the command quit() to exist out of the additional prompt;</p><pre>quit()</pre><p>So lets update to Python 3.10 using the command;</p><pre>conda create -n pydemo2 python=3.10</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*GtVAI1DJrxslf9h9v4VO_A.png" /></figure><p>From the picture above we can see conda proceeded to install Python 3.10 and its default packages. We just need to proceed and check.</p><p>First we have to deactivate the current environment which entails our path specification, the perform another deactivation command which involves the pydemo1 environment. The next virtual environment we will meet is base, which is our default virtual environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*2AsTzDuccA2oD_rzFo-UBw.png" /></figure><p>The we can go ahead and activate our virtual environment that is running python 3.10, known as pydemo2</p><pre>conda activate pydemo2</pre><p>Then check our python version using the command;</p><pre>python</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*eQZHzEOpWvJJwe6M5BsrIg.png" /></figure><h4>Listing Packages In Your Environment</h4><p>Lets say we want to check which packages/ libraries I have inside my environment I simply run;</p><pre>conda list</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*hcY2WCpomezwSMYnRA-L9A.png" /></figure><p>This covers the basics of virtual environments and I will attach links with in-depth information about virtual environments.</p><p>If you do prefer to work around virtual environments using the Graphical user interface you can simply open Anaconda Navigator and click on existing environments or create new environments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EeJtkcpWe2UXU7LYoSzDOQ.png" /></figure><h3>Additional Reading</h3><p><a href="https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html#viewing-a-list-of-the-packages-in-an-environment">Managing environments - conda 4.12.0.post32+6558801f documentation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8681b4f2161" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/an-a-z-guide-on-managing-anaconda-environments-simplified-d8681b4f2161">An A — Z Guide On Managing Anaconda Environments Simplified!</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bringing Old Images Back To Life With AI]]></title>
            <link>https://levelup.gitconnected.com/bringing-old-images-back-to-life-with-ai-4f33d11bd151?source=rss-e668bb8b2f76------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f33d11bd151</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Thenjiwe kubheka]]></dc:creator>
            <pubDate>Tue, 15 Mar 2022 13:21:13 GMT</pubDate>
            <atom:updated>2022-03-15T13:21:13.782Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*NmA1jVnmz094FVwRhjpU0A.png" /></figure><p>They say a picture tells a thousand words, this should include old pictures. So we need to bring these back to life and we have our AI friend to help with this.</p><p>In this article, we will bring back an old image of my stepdad, my uncle, my grandma and a family friend back to life using an AI model called DEOLDIFY.</p><h3>How Does The Model Work?</h3><p>First step in this entire process is taking a black and white image(as our input). We then take this black and white image and pass it to the DEOLDIFY model which will recolor the image and our output will be a color image.</p><p>The model was trained using NOGAN training, which is still a GAN training. Most GANS have two parts of them which is a generator(which is the bit that goes and creates the image) and a discriminator(which pics out fake from real images. So fake recolored images from real recolored images. So Gen and discriminator are trained in isolation and refers to this as NOGAN.</p><p>So we pass a black and which image to the generator and we are able to generate the color equivalent of our image. So we will train again to finetune and find a fine tuned color equivalent.</p><p>So the discriminator has a fake color image and a generated color image, the discriminator will learn to predict weather it is a fake or a real color image. So with most GANS we train side by side but with NOGAN we train in isolation.</p><p>Now after training in NOGAN(in isolation) they are brought together for fine tuning.</p><p>Now lets get started;</p><p>We will clone the model from <a href="https://github.com/jantic/DeOldify">https://github.com/jantic/DeOldify</a>, also bunch of resources from the author, explaining the inner working of the model in detail.</p><h3>Setup Up Our Development Environment</h3><p>First we open our terminal and create our folder, then clone our repository</p><pre>get clone <a href="https://github.com/jantic/DeOldify">https://github.com/jantic/DeOldify</a></pre><p>We can cd into the DEOLDIFY repository and dir, to check;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*N73tMChIRv5cSk1GoeLbwg.png" /></figure><p>We will now install open CV with the following command</p><pre>pip install opencv-python==4.4.0.42</pre><p>Once that is complete we need to install our requirements using the command;</p><pre>pip install -r requirements.txt<br></pre><p>Then we can check our environment by running the command</p><pre>pip list</pre><p>Now we want to download the pretrained deep learning model. I have attached the link;<a href="https://www.youtube.com/redirect?event=video_description&amp;redir_token=QUFFLUhqbHVIUHJQckZNR25VTXZlT3JUZW9qT2hjTWhJZ3xBQ3Jtc0tsR0hhNFN0cnoyc0pSY3Y1cXFZTXdwZVVVRkFTQXRRTWkxbnpuNWFJWGJXWmJkaGJGWkxWTXNaall2Y3BaRFJvTG5XSzc0dXN2alFBcjYyb0pid3VGNDBnaVJ5ZXNEZW1PbXlJcHlUTWkzNk9GZW9XYw&amp;q=https%3A%2F%2Fdata.deepai.org%2Fdeoldify%2FColorizeArtistic_gen.pth">https%3A%2F%2Fdata.deepai.org%2Fdeoldify%2FColorizeArtistic_gen.pth</a></p><p>Once the model is done downloading we need to put it inside a folder called models.</p><p>So within our folder we will create a new folder models and place our model inside there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*5BBQOivsTq3KgpfiGCQG_A.png" /></figure><p>Then we can drag and drop our downloaded model inside there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*_EATidByxANwPD23PeB77A.png" /></figure><p>Then its tie to fire up our Jupyter Notebook and open up the notebook image colorizer.ipnb</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0yFeTrUr7E4LWOpsCeNjPA.png" /></figure><p>When we open the notebook we will execute the cells. The first cell registers our GPU.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*8-Z2fUqpDnI4-fBi9iw5UA.png" /></figure><p>The second cell imports some of the DEOLDIFY libraries or modules and set our torch backend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8KkDKRt7yIxfoN9co6pk6A.png" /></figure><p>The third cell gets the model we downloaded and placed in the models folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bq7LhzSjf2Vxczge7-gEQw.png" /></figure><p>I will be moving to Google Colab, to guide those that do not have powerful GPU’s.</p><p>We will then supply a source black and white image for it to change to color. Assign a render factor, and perform our magic on the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*OBhXTR_w3fg8t-3rlKUz8Q.png" /></figure><p>It is important to not that I tried multiple images on both Jupyter notebook and Google Colab and ran into multiple errors. The image must be clear and good resolution.</p><p>Finally we want to compare the render factor on the image, we will take the start and finish for comparison purposes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*VhiMhiEGEuKRdwC-fYwlGw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*0Yph8y4c4CuKQtN4IU6GuA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*Xu4f9fdrhyQwaQ3WTgBSbg.png" /></figure><p>The image with render factor 10 is colored blue and the image with render factor 38 is evenly colored and looks better.</p><h3>Additional Resources</h3><ul><li><a href="https://github.com/jantic/DeOldify">GitHub - jantic/DeOldify: A Deep Learning based project for colorizing and restoring old images (and video!)</a></li><li><a href="https://colab.research.google.com/github/jantic/DeOldify/blob/master/ImageColorizerColab.ipynb#scrollTo=GcsQPXrj6q4k">Google Colaboratory</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f33d11bd151" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/bringing-old-images-back-to-life-with-ai-4f33d11bd151">Bringing Old Images Back To Life With AI</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build an AI Model to Play Super Mario]]></title>
            <link>https://python.plainenglish.io/build-an-ai-model-to-play-super-mario-7607b1ec1e17?source=rss-e668bb8b2f76------2</link>
            <guid isPermaLink="false">https://medium.com/p/7607b1ec1e17</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Thenjiwe kubheka]]></dc:creator>
            <pubDate>Mon, 10 Jan 2022 16:18:55 GMT</pubDate>
            <atom:updated>2022-01-12T09:13:46.341Z</atom:updated>
            <content:encoded><![CDATA[<h4>A guide on how to build an AI model for playing Super Mario.</h4><p><em>Every Millennial grew up playing the iconic game of Super Mario, I included. But there was always that level that would give me a tough time. So I collaborated with </em><a href="https://medium.com/u/483d2ec29b96"><em>Gugu Sibanyoni</em></a><em> once again to build an AI to play Super Mario.</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FGVypF8-dsZg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DGVypF8-dsZg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FGVypF8-dsZg%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef454b38205b2034d5945ebe37299534/href">https://medium.com/media/ef454b38205b2034d5945ebe37299534/href</a></iframe><h3>Setting Up The Environment</h3><p>We will start by creating a folder and calling it super_mario, opening our Anaconda terminal. Then cd to the Super Mario folder and open Jupyter Notebook using the command Jupyter Notebook.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eE9m6Wzh34f37vIK0aG6Wg.png" /></figure><p>Now we need to bring in our environments by bringing in gym-super-mario-bros, nes-py, open AI gym.</p><p>But before we do that we need to install a C++ compiler as one of the dependencies was not built for windows.</p><p>Once we have our C++ compiler everything should be running smoothly.</p><p>And we can install our dependencies using a simple pip install.</p><pre>!pip install gym_super_mario_bros nes_py</pre><p>Then we want to import the dependencies we just exported.</p><pre>import gym_super_mario_bros<br>from nes_py.wrappers import JoypadSpace<br>from gym_super_mario_bros.actions import SIMPLE_MOVEMENT</pre><p>The next step is to simplify the environment for our AI, as we want it to learn to play the game with very little hassle. We are going to do this by simplifying the number of actions that Mario can do. We do this by using the following command:</p><pre>SIMPLE_MOVEMENT</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2OCygxeWxLZ2Su0Uc_l6xQ.png" /></figure><p>The SIMPLE_MOVEMENT simplifies what Mario can do and hence what the AI model can do. We are limiting them to only 7 different types of actions NOOP which means no action/no key, right, right plus A, right+ B, right +A and B, A and left.</p><p>Now we want to set up our game, turning our game on.</p><pre>env = gym_super_mario_bros.make(&#39;SuperMarioBros2-v0&#39;)<br>env = JoypadSpace(env, SIMPLE_MOVEMENT)</pre><p>We have different versions of Super Mario, we have picked the ‘SuperMarioBros2-v0’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*jYMAojdgW_XzHAQgCe269A.png" /></figure><p>So now we want to go ahead and play the game:</p><pre>done = True<br>for frame in range(100000): <br>    if done: <br>        env.reset()<br>    state, reward, done, info = env.step(env.action_space.sample())<br>    env.render()<br>env.close()</pre><p>First-line which is done = True, is creating the flag which tells us whether to start the game or not. True means the game has been started by the environment we have just set up.</p><p>To specifically start the program we will use env.reset(), take this as our on and off button.</p><p>The for loop is used to loop through every frame in the game, we have 100 000 frames. If the above commands are done, we start the game using env.reset().</p><p>Then we want to pass through actions in our game using the env.step method, these are certain actions to our game such as jump, left/right, a joystick exchange. This allows us to perform random actions.</p><p>The env.render() allows us to show the game on the screen and the env.close() allows us to close the game. Let&#39;s run our cell and see if we have successfully initiated Python to play Super Mario.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fkGlD0LivDbM_aQUlVC-AQ.png" /></figure><p>At this stage we just have a Mario jumping, with no intelligence as yet, he hasn&#39;t even jumped over the first pole. It is timed and when it gets to zero it will restart over.</p><p>Time to put Mario out of his misery and stop the game with the stop button and the env.close() method.</p><p>Now we move on to Preprocessing the environment, let&#39;s call it data preprocessing.</p><h3>Pre Process The Environment</h3><p>We will be applying two preprocessing steps, namely;</p><ul><li>Grey Scaling and</li><li>Frame Stacking</li></ul><p>Our AI model takes in images of the Mario to learn, the color image has 3 times as many pixels to process, which convert it to greyscale cuts down the data which our model has to learn from.</p><p>Frame stacking helps our AI have context, by stacking consecutive frames we are effectively giving our AI model memory.</p><p>We will start by importing our frame stacking, gray scaling wrapper, and vectorization wrapper, not forgetting our useful framework Matplotlib for plotting our frame stack.</p><p>First, we need to install our baseline framework as it presents errors when we just try to import it. A stable baseline is a reinforcement learning library we use for training the model.</p><pre>!pip install stable-baselines3[extra]</pre><pre>from gym.wrappers import GrayScaleObservation<br>from stable_baselines3.common.vec_env import VecFrameStack, DummyVecEnv<br>from matplotlib import pyplot as plt</pre><p>We want to go ahead and install Pytorch and select the Pytorch version you need to be installed for your hardware. The installation varies with device specs, whether you have a GPU or not, and which GPU you have installed.</p><pre>!pip install torch torchvision torchaudio</pre><p>Our dependencies for the preprocessing stage are done, we need to wrap these into our environment.</p><p>We have 5 preprocessing steps namely:</p><ul><li>Creating a base environment, for this, we use the gym_super_mario_bros.make() method and pass in the version of our Super Mario game. We set it to the variable env.</li><li>Then we simplify the controls by using the JoypadSpace() method and we pass env and SIMPLE_MOVEMENT to it. If we did not apply the simple movement wrapper we would have been stuck with approximately 200 movements.</li><li>Now we want to greyscale our gaming data, what do I mean by this? We have a color Super Mario, we want to reduce our pixels and data by diming the game a bit, and making it easier for our model to learn.</li><li>The next step is to use the dummy wrapper to wrap everything together, using the DummyVecEnv() method and we pass the lambda env and set it to env.</li><li>And finally, we want to stack all our images together.</li></ul><h3>Train Model To Play Super Model</h3><p>We will be using reinforcement learning to train our AI model to play Super Mario. A quick brief on what Reinforcement Learning is:</p><ul><li>Agent</li><li>Reward</li><li>Environment</li><li>Action</li></ul><p>The Character Mario is our agent, his action is jumping, left, right and he can only do this inside of the game. We reward our character with rewards or penalties, this depends on his actions.</p><p>So the aim is to teach our AI to take actions inside of the environment, we will be using an algorithm named <a href="https://openai.com/blog/openai-baselines-ppo/">PPO</a>.</p><p>Now we want to import the dependencies to train our model:</p><pre>import os <br>from stable_baselines3 import PPO<br>from stable_baselines3.common.callbacks import BaseCallback</pre><p>We have brought in the OS function, the PPO algorithm from the baseline framework, and callbacks to save our model every 10,000 steps.</p><p>The callback looks as follows:</p><pre><strong>class</strong> TrainAndLoggingCallback(BaseCallback):<br><br>    <strong>def</strong> __init__(self, check_freq, save_path, verbose<strong>=</strong>1):<br>        super(TrainAndLoggingCallback, self)<strong>.</strong>__init__(verbose)<br>        self<strong>.</strong>check_freq <strong>=</strong> check_freq<br>        self<strong>.</strong>save_path <strong>=</strong> save_path<br><br>    <strong>def</strong> _init_callback(self):<br>        <strong>if</strong> self<strong>.</strong>save_path <strong>is</strong> <strong>not</strong> <strong>None</strong>:<br>            os<strong>.</strong>makedirs(self<strong>.</strong>save_path, exist_ok<strong>=True</strong>)<br><br>    <strong>def</strong> _on_step(self):<br>        <strong>if</strong> self<strong>.</strong>n_calls <strong>%</strong> self<strong>.</strong>check_freq <strong>==</strong> 0:<br>            model_path <strong>=</strong> os<strong>.</strong>path<strong>.</strong>join(self<strong>.</strong>save_path, &#39;best_model_{}&#39;<strong>.</strong>format(self<strong>.</strong>n_calls))<br>            self<strong>.</strong>model<strong>.</strong>save(model_path)<br><br>        <strong>return</strong> <strong>True</strong></pre><p>Now we want to set up our callback, we begin by setting up directories where we will be saving our stuff.</p><pre>CHECKPOINT_DIR <strong>=</strong> &#39;./train/&#39;<br>LOG_DIR <strong>=</strong> &#39;./logs/&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*o3Hkv2QOBNAHTvXS1FRwEw.png" /></figure><p>We want to set up the callback, to ensure our model is saved every 10000 steps, every 10000 steps we will have a new model saved.</p><pre>callback <strong>=</strong> TrainAndLoggingCallback(check_freq<strong>=</strong>10000, save_path<strong>=</strong>CHECKPOINT_DIR)</pre><p>Now we want to set up our PPO / AI model, we simply have 1 line that creates the AI model that is just waiting for training.</p><pre>model <strong>=</strong> PPO(&#39;CnnPolicy&#39;, env, verbose<strong>=</strong>1, tensorboard_log<strong>=</strong>LOG_DIR, learning_rate<strong>=</strong>0.000001, <br>            n_steps<strong>=</strong>512)</pre><p>So we have our model and we set it to PPO and we pass in CNN policy(which is a computer-based brain, the CNN neural network is really fast at processing images. We also pass in our environment which is our preprocessed data, tensorflow_log that is sort of like a scoreboard as we are running and training our model, also pass in our learning rate. Mine will not be training super fast or super slow, just fair enough. Lastly, we have specified the number of steps to run for each environment.</p><p>Finally, we can move on to training the model:</p><pre>model<strong>.</strong>learn(total_timesteps<strong>=</strong>100000, callback<strong>=</strong>callback)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*__n-kLETu8bsjYQBOROMDQ.png" /></figure><p>We get back the frames per second (FPS), iterations, time_elapsed, total_timesteps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*f4Iao5Au7ZeUQOJuHtNLUQ.png" /></figure><p>We also get our training matrix, we mainly pay attention to our loss matrices, we want to see the loss going down as we go through and the explain variants going up, these are two good signs that the model is converging.</p><p>Once we hit 10000 steps the callback we created and saved should be in our train directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*ZSHa0jBXOIJOtutI22-K8w.png" /></figure><p>We also have our TensorFlow logs saved inside our logs folder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*idEOC4lnDaIBHzl0KdbK9w.png" /></figure><p>Our model has finished training and now time to test it out, so excited.</p><h3>Play Super Mario With Our Model</h3><p>First, we need to load our model, we will take the best model 100000.</p><pre>model = PPO.load(&#39;./train/best_model_100000&#39;)</pre><p>We will try and play Super Mario with this PPO model.</p><p>First, we reset the game;</p><pre>state <strong>=</strong> env<strong>.</strong>reset()</pre><p>Then time to play:</p><pre>state = env.reset()<br>while True: <br>    <br>    action, _ = model.predict(state)<br>    state, reward, done, info = env.step(action)<br>    env.render()</pre><p>Well, our model seems to be underperforming at 100000 steps, we need to increase it to 1000000. We just adjust the training command to 1000000.</p><pre>model.learn(total_timesteps=1000000, callback=callback)</pre><h3>Additional Reading</h3><ul><li><a href="https://colab.research.google.com/drive/1Wpht1CkorRMtbNUoEbm9JDSeuTtF8Jxg?usp=sharing">Google Colaboratory</a></li><li><a href="https://openai.com/blog/openai-baselines-ppo/">Proximal Policy Optimization</a></li><li><a href="https://pypi.org/project/gym-super-mario-bros/">gym-super-mario-bros</a></li></ul><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Get exclusive access to writing opportunities and advice in our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7607b1ec1e17" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/build-an-ai-model-to-play-super-mario-7607b1ec1e17">Build an AI Model to Play Super Mario</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Artificial Intelligence Project: Pose Detection]]></title>
            <link>https://levelup.gitconnected.com/artificial-intelligence-project-pose-detection-564dead6f10c?source=rss-e668bb8b2f76------2</link>
            <guid isPermaLink="false">https://medium.com/p/564dead6f10c</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Thenjiwe kubheka]]></dc:creator>
            <pubDate>Tue, 04 Jan 2022 15:17:13 GMT</pubDate>
            <atom:updated>2022-01-04T15:17:13.038Z</atom:updated>
            <content:encoded><![CDATA[<p>I get asked a lot, how to use AI to detect certain posepostures and is it possible to get emotions out of these.</p><p>Well, my collogue(<a href="https://medium.com/u/483d2ec29b96">Gugu Sibanyoni</a>) and I decided to play around with AI tracking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*uQfcLAM1HwXrS_v6p6BovQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*0OaZ-pRyETLDnSHG0-Mleg.png" /></figure><p>The picture above is the end goal, using AI for recognizing posture and eventually emotions.</p><h3>Setting Up Our Environment</h3><p>We will be using open CV for the image recognition and media pipe for our posture recognition models.</p><pre>!pip install mediapipe opencv-python</pre><p>We will only be using two dependencies and time to move on to setting up our real-time feed in opencv.</p><p>To set up our real time feed, we need to import our dependencies;</p><pre>import mediapipe as mp<br>import cv2</pre><p>Lets begin by setting up media pipe</p><pre>mp_drawing = mp.solutions.drawing_utils<br>mp_holistic = mp.solutions.holistic</pre><p>So we have set up our drawing utilities that will draw our different detections from our holistic model to the screen via open cv.</p><p>Then holistic simply brings in our holistic model.</p><p>Inside media pipe we have a variety of models we can play around with, namely;</p><p>Face Mesh, Iris, Hands, Pose, Holistic, Selfie Segmentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VBMNqFmh3IGw-xN-733c7g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XK_qj3dk9KJ_sGjkknewKg.png" /></figure><p>Now we want to setup open cv for real time imaging;</p><pre>cap = cv2.VideoCapture(0)<br>while cap.isOpened():<br>    ret, frame = cap.read()<br>    cv2.imshow(&#39;Real Time Imaging&#39;, frame)<br>    <br>    if cv2.waitKey(10) &amp; 0xFF == ord(&#39;q&#39;):<br>        break</pre><pre>cap.release()<br>cv2.destroyAllWindows()</pre><p>The first line of code we are declaring cap as our variable and assigning cv2(alias of calling open cv) to VideoCapture and choosing 0 as the default camera port.</p><p>We begin our wile loop, by telling open cv that while cap, our variable is open, then return frame and read/ render cap to the screen.</p><p>Then we use the imshow function to render the image in frames and label the frame real-time imaging.</p><p>Our conditional if statement starts the break part of the statement, we saying to cv2 wait 10 milliseconds then when I press q, break the while loop that is running the frame.</p><p>Then release the program and break all windows.</p><p>Sometimes from the if statement, the break and q does not work, hence we can just have the following code alone. Just to make sure the code is broken.</p><pre>cap.release()<br>cv2.destroyAllWindows()</pre><p>Now we want to overlay our media pipe holistic components onto the opencv.</p><p>We start by copying the open cv code, to the next Jupyter cell, then we will add the holistic code to it.</p><pre>cap = cv2.VideoCapture(0)<br>with mp_holistic.Holistic(min_detection_confidence=0.5, min_tracking_confidence=0.5) as holistic:<br>    while cap.isOpened():<br>         ret, frame = cap.read()<br>         image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)<br>         results = holistic.process(image)<br>         print(results)<br>         cv2.imshow(&#39;Real Time Imaging&#39;, frame)<br>    <br>         if cv2.waitKey(10) &amp; 0xFF == ord(&#39;q&#39;):<br>             break</pre><pre>cap.release()<br>cv2.destroyAllWindows()</pre><p>The new additional code we have added, we are using the wit statement and using the mp_holistic we have imported earlier. Within the mp.holistic method we are adding the min_detection_confidence and min_tracking_confidence and assigning it to 0.5.</p><pre>with mp_holistic.Holistic(min_detection_confidence=0.5, min_tracking_confidence=0.5) as holistic:</pre><p>We will be setting the entire line to holistic as we do not want to be typing holistic every time.</p><p>For a model with high tracking confidence we would set min_detection confidence and min_tracking_confidence to higher values.</p><p>We have also added the following lines of code;</p><pre>image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)<br>         results = holistic.process(image)<br>         print(results)</pre><p>The first line of code we are recoloring our image and grabbing our frame we have above and recoloring what is returning within the frame using cv2.COLOR-BGR2RGB, we want the color of the model to be represented in RGB.</p><p>We take the image which is being recolored and we pass it to holistic model and assign a variable called results. Then we print out our results as we are not yet drawing anything to the screen.</p><p>When we run our code we will see a pop up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*KdCXo8lhUs9_tE3L71PuDQ.png" /></figure><p>Then a print out of what we needed, just to check if we are still on track with everything.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*QN8m2hHVXlhFTX3Cp0UuJw.png" /></figure><p>Now that we have checked that all is working ok, we can go ahead and draw, these to our screen, starting with the face landmarks, we can remove the print and add the draw.</p><pre>image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)<br>mp_drawing.draw_landmarks(image, results.face_landmarks, mp_holistic.FACEMESH_TESSELATION)<br>         cv2.imshow(&#39;Real Time Imaging&#39;, frame)</pre><p>The first line of code image = cv2.cvtColor(image, cv2.COLOR_RGB2RGB2) is converting back the rendering of the image from BGR(which we converted above) to RGB, as this is how open cv wants its images.</p><p>Then we go ahead and draw, using mp_drawing.draw_landmarks and we pass in the image variable from above, the results from our face_landmarks and the mp.holistic.FACEMESH_TESSELATION model.</p><p>So we want to change the image we are rendering, so we want to change our raw frame image to our image variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*abIfRvA1zIJauGz0a7qZ8g.png" /></figure><p>So we have all of our different face landmarks drawn to the screen, which is pretty cool and very creepy, I move my face in any direction it keeps tracking my face.</p><p>Now we want to draw the rest of our landmarks which is the pose, right hand and left hand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*bP1n9mzN5kZrRq91hMjo8Q.png" /></figure><pre>mp_drawing.draw_landmarks(image, results.face_landmarks, mp_holistic.FACEMESH_TESSELATION)<br>         mp_drawing.draw_landmarks(image, results.right_hand_landmarks, mp_holistic.HAND_CONNECTIONS)<br>         mp_drawing.draw_landmarks(image, results.left_hand_landmarks, mp_holistic.HAND_CONNECTIONS)<br>         mp_drawing.draw_landmarks(image, results.pose_landmarks, mp_holistic.POSE_CONNECTIONS)<br>         cv2.imshow(&#39;Real Time Imaging&#39;, image)</pre><p>As seen above the model is tracking my face, right and left hands including my pose, very accurately, very fast. We can also track the full body with the pose tracking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*eFFxSQJlQPreCgjGCgrRWA.png" /></figure><p>Well we have the white and red, and we want to color our landmarks a bit, we will do that by using the drawing spec model.</p><pre>mp_drawing<strong>.</strong>DrawingSpec(color<strong>=</strong>(0,0,255), thickness<strong>=</strong>2, circle_radius<strong>=</strong>2)</pre><p>We are able to pass the color, thickness and circle radius, we want to pass through the line and circle color.</p><pre>mp_drawing<strong>.</strong>DrawingSpec(color<strong>=</strong>(0,0,255), thickness<strong>=</strong>2, circle_radius<strong>=</strong>2)</pre><p>We will do this for face, pose and hands.</p><pre>cap = cv2.VideoCapture(0)<br># Initiate holistic model<br>with mp_holistic.Holistic(min_detection_confidence=0.5, min_tracking_confidence=0.5) as holistic:<br>    <br>    while cap.isOpened():<br>        ret, frame = cap.read()<br>        <br>        # Recolor Feed<br>        image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)<br>        # Make Detections<br>        results = holistic.process(image)<br>        # print(results.face_landmarks)<br>        <br>        # face_landmarks, pose_landmarks, left_hand_landmarks, right_hand_landmarks<br>        <br>        # Recolor image back to BGR for rendering<br>        image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)<br>        <br>        # 1. Draw face landmarks<br>        mp_drawing.draw_landmarks(image, results.face_landmarks, mp_holistic.FACEMESH_TESSELATION, <br>                                 mp_drawing.DrawingSpec(color=(80,110,10), thickness=1, circle_radius=1),<br>                                 mp_drawing.DrawingSpec(color=(80,256,121), thickness=1, circle_radius=1)<br>                                 )<br>        <br>        # 2. Right hand<br>        mp_drawing.draw_landmarks(image, results.right_hand_landmarks, mp_holistic.HAND_CONNECTIONS, <br>                                 mp_drawing.DrawingSpec(color=(80,22,10), thickness=2, circle_radius=4),<br>                                 mp_drawing.DrawingSpec(color=(80,44,121), thickness=2, circle_radius=2)<br>                                 )</pre><pre># 3. Left Hand<br>        mp_drawing.draw_landmarks(image, results.left_hand_landmarks, mp_holistic.HAND_CONNECTIONS, <br>                                 mp_drawing.DrawingSpec(color=(121,22,76), thickness=2, circle_radius=4),<br>                                 mp_drawing.DrawingSpec(color=(121,44,250), thickness=2, circle_radius=2)<br>                                 )<br> # 4. Pose Detections<br>        mp_drawing.draw_landmarks(image, results.pose_landmarks, mp_holistic.POSE_CONNECTIONS, <br>                                 mp_drawing.DrawingSpec(color=(245,117,66), thickness=2, circle_radius=4),<br>                                 mp_drawing.DrawingSpec(color=(245,66,230), thickness=2, circle_radius=2)<br>                                 )<br>                        <br>        cv2.imshow(&#39;Raw Webcam Feed&#39;, image)</pre><pre>if cv2.waitKey(10) &amp; 0xFF == ord(&#39;q&#39;):<br>            break</pre><pre>cap.release()<br>cv2.destroyAllWindows()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*BCP0j9Ryo8SY2O9st7AdoA.png" /></figure><p>It looks nicer in color and this forms the first stage of our tracking.</p><h3>Additional Reading</h3><ul><li><a href="https://google.github.io/mediapipe/">Home</a></li><li><a href="https://colab.research.google.com/drive/1LXvSRpg0hNMT9u00p3sJmUweaXGYmtVW?usp=sharing">Google Colaboratory</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=564dead6f10c" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/artificial-intelligence-project-pose-detection-564dead6f10c">Artificial Intelligence Project: Pose Detection</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stock Market Analysis Using Python Pandas]]></title>
            <link>https://levelup.gitconnected.com/stock-market-analysis-using-python-pandas-ec278f76e217?source=rss-e668bb8b2f76------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec278f76e217</guid>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Thenjiwe kubheka]]></dc:creator>
            <pubDate>Sun, 19 Dec 2021 20:10:42 GMT</pubDate>
            <atom:updated>2021-12-19T20:10:42.157Z</atom:updated>
            <content:encoded><![CDATA[<p>Python pandas is one of the most important tools to have in your toolbox as a Data Scientist.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8QpMpCoG48LOav6-o4MsTA.jpeg" /><figcaption>source: Nicholas Cappelo via Unsplash.com</figcaption></figure><p>We’re referring to the framework used for tabular analysis. The name is derived from “panel data” a term closely associated with multidimensional structured data sets.</p><p>I have thought of an interesting use case for Pandas and that is stock market analysis.</p><p>We want to analyze the stock prices of my 5 favorite car manufactures, and see all the interesting cool things we can do with Pandas.</p><h3>Setting Up Our Environment</h3><p>Before diving into any project it is important to have our toolbox ready, this is mainly setting up the environment.</p><p>We will create a folder and we will name ours ‘Analysing_Stock_Prices’, open our Anaconda prompt as an administrator and cd into the folder ‘Analysing_Stock_Prices’, and open the Jupyter Notebook.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*kyyOgEwyu35hpbgHUmz-Ng.jpeg" /></figure><p>Select New and Python 3 (Ipykernel) and get your Jupyter Notebook ready.</p><h3>Getting Live Data From Yahoo Finance</h3><p>We will be using <a href="https://pandas-datareader.readthedocs.io/en/latest/remote_data.html">Pandas data reader</a>, to get live data for us to work with and analyze.</p><p>We will start by importing the pandas data reader and the date-time module, we will use the data reader for remote data access and the datetime module for specifying the begin and end date times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*DHdAe9Lrf8QwXLrsolTXDQ.png" /></figure><p>Then we need to specify to the DataReader how we want our data, meaning the start and end dates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*SCYqGqc2SfTQgwJ2R7lgWQ.png" /></figure><p>We will use BMW as a litmus, to test out Pandas reader and the DateTime module.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*CaX6Z0V0irzdQRXLeYsgrQ.png" /></figure><p>Above we have our variable bmw, we set it to the Pandas data reader by calling web.DataReader and pass in “BMW.DE” as the stock name for BMW, our source is yahoo and we put in our start and end dates. Then we call bmw and check our data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*NjyTiPBgcUoO_5FWTRa2KA.jpeg" /></figure><p>Above we have a summary of the important data from 2015 to 2021. We want the first set of results we will use the .head() method and for the last bit of results, we can use the .tail() method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*dHqALqlAlBqrHmqmw968LA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/27/0*mGPlQgil3gKD0znO" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*RGIme5Y3iYPY-CXLeaETVg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*rzth9dyAQ_aMm_w9QeqvbQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*El97lgts_gsO2MzMrKXxng.jpeg" /></figure><p>Now we want the data of when the BMW stocks closed, which is data from 2015 to 2021, we also want to plot out this data. We will first import matplotlib as the alias plt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*un0sabkOsuypHC5x5YIluA.png" /></figure><p>Then we need to read the closing stocks and plot them using matplotlib.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*kHwrUIrEfrhzA9TjVYTTbQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/60/0*dLfisPVTJg03IcZM" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*DYcC0rJdtbuLXc6CQfB9Jg.jpeg" /></figure><p>Let’s make our data look more interesting, we know the finance guys want to see, colors, labels, bigger shapes and interactive data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*cPdJYnooCIH9GMaxlobHZA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*ZcWotzG-6e7nk9YWR4hApQ.jpeg" /></figure><p>We are sure our environments are fully set up, let’s dig in.</p><h3>Tesla Vs VW Vs BMW Vs Daimler Vs Ford Vs Toyota Vs Nissan</h3><p>German car manufacturers against their American counterparts Vs the Japanese carmakers.</p><p>Before we get started, we also need a Python library called NumPy which we use when working with arrays and matrices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*SOlHlBJwjAXxY6XAYA9Umg.png" /></figure><p>Then we need to tell the Data Reader to get us our different stock</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*SBAi_O3_9FPmGtLbhHbiQQ.png" /></figure><p>We can also save the stock in CSV files to complement our Jupyter Notebook.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*EBeGIyIsQPsXgVvEQ__oQg.png" /></figure><p>We name the variable as per above for the different car manufacturers, then we use the .to_csv() method and pass in the Title of the CSV file in the brackets. Then we can check our folder named Analysing_Stock_Prices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*uTTs77jfNa8yWx2234YSQQ.jpeg" /></figure><h3>Analyzing The Start Data</h3><p>To check starting data, we use the .head method, now let’s do it for all the car manufacturers we have brought in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*ItrwXqNMZnjPyUv0KLWNAA.png" /></figure><p>And the .tail() method for viewing the bottom sectioned data, which is the latest data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*grUOH-HojEDy1RXYIKFTow.png" /></figure><p>And we want to plot all the data of the car manufacturers at open and at close.</p><p>We will begin with ‘Close’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*NBk65dy7greIliaVeGkX2Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*q0P3mDtKse2G8nBJBGyWvA.jpeg" /></figure><p>Then move on to ‘open’ and plot the outcome.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*FSfJ4BSNoNEN1SqCLOOUnw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*PkNlfs7wjBg77KoPwyyb1w.jpeg" /></figure><p>As we can see for both the ‘Open’ and ‘Close’ from mid-2020, Tesla has been dominating the other car manufacturers, we can see this by the blue wave. Let’s continue playing with our data and see if Tesla really dominates.</p><p>I want to see the volume of all these stocks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*xnlivpljqOa9gM4Hw4pZOw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*d6xuPKNkMMrceJVTz9MKlw.jpeg" /></figure><p>Let’s analyze the above plot, we see that Tesla began to peak in mid-2020, what caused the spike in Tesla stock? We will use the iloc method for this. The iloc method is used when we want to index at a certain point using Pandas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*Bl_7f_zn9zg9KtHSUsNSBw.png" /></figure><p>So we want to see the Tesla ‘Open’ stock from mid-2020 and we are just enlarging our diagram, by specifying the figsize.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*JIvZnyjwU1RN-4JtIJDnbQ.jpeg" /></figure><p>But we want a clearer image of the year 2020 only.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*026yo_X4KE-NaARrnEbRNw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*4OSJzoFIEzjvCDzMk7VBCw.jpeg" /></figure><p>The volumes increased and the stock price decreased. Companies drop the stock and the volume increases.</p><h3>Analyzing The Market Cap</h3><p>We want to check which of the car manufacturers is more valuable than the other. We do not want to rely simply on the time series data.</p><p>Our current data can not help us analyze this, that however won’t stop us from using tricks within mathematics to get that data. We will use some basic math to get the total units of the stock present.</p><p>We will use the open price and the Volume, our end goal is to get the total money traded.</p><p>So we want to add a column for the total traded, for each car manufacturer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*nv7BNF7ZF2RkDDjzgqvn6w.png" /></figure><p>Let’s check with Nissan, Tesla and VW if we have the column added.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*NZ6pLYDBWBlpPql8THd8Zw.jpeg" /></figure><p>Now let’s plot our ‘Total Traded’ for all car manufacturers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*vOKyT-poWF2PEEloOmymdQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*nTZlpt3h1pDAB-2AMBJ4FQ.jpeg" /></figure><p>The time series graph shows us that there was a huge amount of Total Traded for Tesla in 2021. So we want the position of that spike.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*xay3gn5U_y_xLnG2xnBOww.png" /></figure><p>We get position 1502 and we want the iloc on 1502.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*KKhYgA8sbvQDdRFJ7MLpSg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*edB-l0KVh7QoguaRSH9YwA.jpeg" /></figure><p>Well as I said before we cannot rely on the time series representation as it is sometimes misleading. The peak happened on December the <a href="https://www.reuters.com/business/autos-transportation/tesla-shares-jump-record-high-ahead-sp-500-debut-2020-12-18/#:~:text=Dec%2018%20(Reuters)%20%2D%20Shares,SPX).&amp;text=Tesla&#39;s%20shares%20ended%20up%206%25%20at%20a%20record%20%24695.">18th 2020</a>, quite interesting stuff.</p><h3>Moving Average</h3><p>We want to read each manufacturer separately as it seems at this moment Tesla is winning, but we need need to analyze everything in order to make informed decisions. We will just work with the Close for now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*Dj5MICy4M0-UbaIt0khNrA.png" /></figure><p>Now that we have plotted each individually, we want to get rid of the noise, smoothen out our diagrams a little bit.</p><p>We will begin by creating another new column and we will call it moving average 60. The 60 represents the samples we will be analyzing, 60 dates, a two-month analysis is quite fair enough. We can use VW as our sample for this, but in the Notebook, I have done all the car manufacturers for you guys.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*qwEpCBygBoXs6Fd3eqTI8Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*Tn8oTs0OSv93HGxgQQxHkg.jpeg" /></figure><p>The noise has been smoothened out a bit, and we can increase our moving average to maybe 300.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*UKr_qvgytkkog0uyX0LYTA.png" /></figure><p>When the window size is too high we miss out on trends, it’s always better to consume big data in small chunks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*hq-_zcWp6aEg6moB-4O6VA.jpeg" /></figure><h3>Correlation And Scatter Matrix</h3><p>There is a framework in pandas that allows us to work easily with scatter matrices. So we will import it and import pandas as our alias pd.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*7zgYJkD6uNPGwL_F6a64eA.png" /></figure><p>And we want to combine the closing prices of all the car manufacturers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*MRIR6EeR_HtBLazjCNcQyA.png" /></figure><p>Now we want to name our columns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*jjTtiv7hB3HrUu9uQ3N5DQ.png" /></figure><p>We need to plot our scatter matrix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*ikIk_kG-Bhta-j-p4ki1aA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*efnLJWkuQwTTX7cigu_Zdw.jpeg" /></figure><p>Stock prices can be viewed as random variables, now scatter matrices can determine if there is a linear correlation with one or more variables. So it simply shows us the correlation and relation between different types of data.</p><p>At some point, BMW and Nissan are related, also Ford and Nissan. Linear, histograms, curves etc we looking for similar diagrams at a certain point.</p><p>When a plot looks like a line we say that there is probably some correlation going on, the more the points are clustered on a straight line, we say have a perfect correlation.</p><p>And when we have strange curves and less straight lines, we say we have less correlation between the variables(in our case car manufacturers).</p><h3>Candle Stick Charts</h3><p>We now want to get a bit fancy and plot candlestick charts, with these glamourous charts we can see the open, close, high and low all in one chart.</p><p>We will start by bringing in the mpl_finance library and bring in the candlestick library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*qFJyit4h1mOU6dXhReJscQ.png" /></figure><p>There will be a warning, just ignore it and run the import again, then all will be normal.</p><p>And from matplotlib we will need the following modules;</p><p>DateFormatter, date2num, WeekdayLocator, DayLocator and lastly Monday.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*kSvc7eAd_2AnDHQdUxmJNg.png" /></figure><p>We will now use Toyota as our sample, you can do the rest on the Notebook I have supplied.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*ymQiOA9-1V8k3E3jbcD-Cw.png" /></figure><p>We are only interested in the December information, from the 1st of December 2021 to currently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*I1bIN_PvwXlFf2esY6CTmw.png" /></figure><p>Then we will create a new column and call it date accessed(date_acc) and we will apply a lambda function that converts a date to a number. We will also take the values of the opening values;</p><p>‘Date accessed’, ‘Opening Values’, ‘High Prices’, ‘Low Prices’, ‘Close Values’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*zwAwTGuPZhI1G3zZn4gWNA.png" /></figure><p>Green means gain and red means loss.</p><h3>Daily Percentage Change</h3><p>The daily percentage change can be represented by the following formulae:</p><p>rt =Pt/Pt-1 -1</p><p>rt is the return at sub t</p><p>Pt is the Price at time T</p><p>Pt-1 is the price at time T-1</p><p>What the rt value report is a percentage gain or loss. Say you bought the stock on day t-1 and you sold it at day t. If you gained then Pt should be grater than Pt-1. So the ratio should be greater than 1 and hence rt would be positive.</p><p>The larger the value of rt the better the price of t. But if you bought a stock at day t-1 and you sold it for a lower price, then our ratio would be less than 1 and rt would be negative. The smaller the value of rt, the more loss we have experienced.</p><p>This is used mainly to analyze the volatility of the stock, if the daily returns have a wide distribution, the stock is more volatile. We will be calculating the percentage return and plot them on a histogram.</p><p>These histograms will help us see which is the more stable and which is the more volatile. Most investors fear volatility, they want stability.</p><p>We will represent our formula as code, using;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*EEk1miFuPWSgfiDuEoyJAw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*hGHCI7Xk3WVmzA1DxpDadA.jpeg" /></figure><p>The first term has NAN as there is nothing before it, hence it is not divisible by anything. Let’s do the same for the others and plot everything on a histogram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*Qu4PMrQWbG6rn-QmZb0zPw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*OZvn7J00bEt979uAeRYv3g.jpeg" /></figure><p>So we plot out the histogram using the .hist method and we specify the number of bins we want. The thicker our histogram is the more volatile the stock is.</p><p>The width of the histogram shape is related to the standard deviation of the distribution. The higher it is the more variants we have, the variants of a certain distribution are directly related to the standard deviation. It’s actually the square value of the standard deviation, the higher the standard deviation is, the higher the variance is. The more volatility we have in terms of stock analysis.</p><p>Let’s do the same for the other car manufacturers and even better yet, analyze them on the same graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*gTN1Q_it4Zqz7BQj1yWYfg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*cH0sq4EDYS29l2CgrGBm3Q.jpeg" /></figure><p>One histogram is covering the other, so we can set transparency called alpha and enlarge the figure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*DkbqA5yUMkOD4g2ZHrtuMA.jpeg" /></figure><p>The enlarged diagram shows Tesla, Ford and VW with a wider curve, hence we can see that these stocks are more volatile than that of the others. To smoothen this down we will use the KDE(Kernel Density Estimate).</p><p>The KDE takes in a histogram and tries to fit a certain kernel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*Cpe1sslzmPOZisY4SmlWqQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*8m4hD5zeleBj_Ozn9XMjFg.jpeg" /></figure><p>I the graph some companies are shorter such as Tesla, it is taller on the histogram but shorter on the KDE. Well, we are using a kernel, which tells us a certain probability function.</p><p>The histogram is not normalized, whilst the KDE is, the areas of each density are constant, hence the two methods can be used for comparison. We still see that Tesla, Ford and VW are still fatter, this definitely confirms that the stock is volatile.</p><h3>Box Plots</h3><p>Also another useful tool you can use for information representation. We will call the pandas box method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*N-hdx-yWN-2AAdLshLs8kQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*A6-pwZm03U_LUY2miQAlIQ.jpeg" /></figure><p>The daily percentage change of Tesla, Toyota and Mercedes is taller than the others, this means those stocks are more volatile.</p><h3>Cumulative Return</h3><p>The formulae for this goes as follows; it = (1 + rt)it-1, this is a recursive formula, hence we have the name cumulative return.</p><p>We multiply ‘it-1’ with the factor of ‘1+rt’, rt was used earlier on and it is called the daily percentage change. Cumulative returns are the answer to the question all investors ask.</p><p>You invest $100 in a car manufacturer at the beginning of your time series. The most important question here is how much would it be worth today. So in 2015, I invested $100 in BMW, how much did the dollar make me from then till now?</p><p>Our formula only calculated daily return and will not consider a stock that has dividends. Cumulative return is computed the day investment was made, if the cumulative return is above 1, then you are making profit. We can compute this, using the following;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*qVR8vNq1QW_KfeHUpXa0gw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*qMBCln5x4YQwPt1XeAJ4gA.jpeg" /></figure><p>The first entry is always $1 as you can see on the tables the values are close to 1, so the cumulative return is always compared to 1 dollar. So which stock showed the highest return for $1 invested? Clearly, the graphs show for some companies $1 dollar in 2015 is now worth $25 in 2021.</p><h3>Additional Reading</h3><p><a href="https://colab.research.google.com/drive/1gSih6aUzJLG39tHh6EZRvDg7FqfJnUc5?usp=sharing">Google Colaboratory</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec278f76e217" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/stock-market-analysis-using-python-pandas-ec278f76e217">Stock Market Analysis Using Python Pandas</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Huffman Encoding]]></title>
            <link>https://levelup.gitconnected.com/huffman-encoding-424d40d92f70?source=rss-e668bb8b2f76------2</link>
            <guid isPermaLink="false">https://medium.com/p/424d40d92f70</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Thenjiwe kubheka]]></dc:creator>
            <pubDate>Mon, 06 Dec 2021 03:51:13 GMT</pubDate>
            <atom:updated>2021-12-06T03:51:13.068Z</atom:updated>
            <content:encoded><![CDATA[<p>This is one of the greedy algorithms, and it was one of our first attempts as the computer science community to compress text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U_L892Cq1HUD84EHYYy8tQ.jpeg" /><figcaption>Source: Sandy Miller via <a href="https://unsplash.com/photos/Kl4LNdg6on4">Unsplash.com</a></figcaption></figure><p>Greedy Algorithms are algorithms that choose the best for themselves at every stage.</p><p>Common problems that are solved using Greedy algorithms are Huffman Encoding, the Knapsack problem, and the coin change problem. Let&#39;s explore Huffman Encoding</p><h3>Huffman Encoding</h3><p>Ever wondered how text is sent?</p><p>Well, this is a very complex problem, we are only concerned with sending text<br>as efficiently as possible. We want smaller bits, for faster transfers. This means<br>we need to compress our text, but how do we archive this?</p><p>Videos and Images use lossy compression, we can lose a bit of detail here not a<br>train smash. Unfortunately, this is not the case for text, we cannot afford to lose anything as the context of the text will be changed completely.</p><p>Our compression is limited to lossless compression.</p><p>Over the years better algorithms have been devised for text compression, but<br>all are based on Huffman encoding.</p><p>Formulated by mathematician David Huffman, huffman encoding is based on<br>inequality of data usage.</p><p>By data I mean characters, some characters are used more than others.</p><p>We use vowels more often than consonants such as ‘X’ or ‘Q’, hence this algorithm chooses “what is best at every stage”.</p><p>Lets compress and decompress the word Huffman, using the Huffman encoding algorithm;</p><p>We have our tree and table that illustrates Huffman.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*UniKg1QrONzRmw9bNXXFxw.png" /></figure><p>H- appears once</p><p>U- appears Once</p><p>F -appears twice</p><p>M-appears once</p><p>A-appears once</p><p>N-appears once</p><p>We then proceed to draw the tree with data from the table, by following these simple 5 steps.</p><p>Step 1: Create a node in our tree for each character, then label it with a frequency.</p><p>Step 2: Arrange these nodes in ascending frequency from low to high.</p><p>Step 3: We then take the first two nodes, join them and assign a parent node. The label of the parent node is the sum of the two frequency.</p><p>Step 4: The parent node that was just formed is then reinserted into the list with the child nodes.</p><p>Step 5: Repeat step(s) 3 and 4 until we have 1 parent node</p><p>See below image;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*D9fdC0c9lXKVLzk9PC_cAg.png" /></figure><p>This translates to;</p><p>h: 000,</p><p>u: 001,</p><p>m: 010,</p><p>a: 011,</p><p>n:10,</p><p>f: 11,</p><p>Encoded output: 00000111110100111011</p><p>Lets code out the solution for this.</p><p>We start by creating our tree node, which takes in the right and left node, which we initialize to zero, also symbol and probability.</p><pre># A Huffman Tree Node</pre><pre>class Node:</pre><pre>def __init__(self, prob, symbol, left=None, right=None):</pre><pre>self.prob = prob</pre><pre>self.symbol = symbol</pre><pre>self.left = left</pre><pre>self.right = right</pre><pre>self.code = &#39;&#39;</pre><p>We then pass a helper function to print the codes of symbols when traversing the tree.</p><pre># A helper function to print the codes of symbols by traveling Huffman Tree</pre><pre>codes = dict()<br>def Calculate_Codes(node, value=&#39;&#39;):</pre><pre>newValue = value + str(node.code)</pre><pre>if (node.left):</pre><pre>Calculate_Codes(node.left, newValue)</pre><pre>if (node.right):</pre><pre>Calculate_Codes(node.right, newValue)</pre><pre>if (not node.left and not node.right):</pre><pre>codes[node.symbol] = newValue</pre><pre>return codes</pre><p>We then create a helper function that will calculate the probabilities of symbols in our data</p><pre># A helper function to calculate the probabilities of symbols in given data</pre><pre>def Calculate_Probability(data):</pre><pre>symbols = dict()</pre><pre>for element in data:</pre><pre>if symbols.get(element) == None:</pre><pre>symbols[element] = 1</pre><pre>else:</pre><pre>symbols[element] += 1</pre><pre>return symbols</pre><p>Then we have the function to calculate the space difference between compressed and non compressed data.</p><pre># A helper function to calculate the space difference between compressed and non compressed data</pre><pre>def Total_Gain(data, coding):</pre><pre>before_compression = len(data) * 8</pre><pre>after_compression = 0</pre><pre>symbols = coding.keys()</pre><pre>for symbol in symbols:</pre><pre>count = data.count(symbol)</pre><pre>after_compression += count * len(coding[symbol])</pre><pre>print(&quot;Space usage before compression (in bits):&quot;, before_compression)</pre><pre>print(&quot;Space usage after compression (in bits):&quot;, after_compression)</pre><pre>def Huffman_Encoding(data):</pre><pre>symbol_with_probs = Calculate_Probability(data)</pre><pre>symbols = symbol_with_probs.keys()</pre><pre>probabilities = symbol_with_probs.values()</pre><pre>print(&quot;symbols: &quot;, symbols)</pre><pre>print(&quot;probabilities: &quot;, probabilities)</pre><pre>nodes = []</pre><p>We then convert symbols into probabilities into huffman tree.</p><pre># converting symbols and probabilities into huffman tree nodes</pre><pre>for symbol in symbols:</pre><pre>nodes.append(Node(symbol_with_probs.get(symbol), symbol))</pre><pre>while len(nodes) &gt; 1:</pre><pre>nodes = sorted(nodes, key=lambda x: x.prob)</pre><pre>right = nodes[0]</pre><pre>left = nodes[1]</pre><pre>left.code = 0</pre><pre>right.code = 1</pre><pre>newNode = Node(left.prob + right.prob, left.symbol + right.symbol, left, right)</pre><pre>nodes.remove(left)</pre><pre>nodes.remove(right)</pre><pre>nodes.append(newNode)</pre><pre>huffman_encoding = Calculate_Codes(nodes[0])</pre><pre>print(&quot;symbols with codes&quot;, huffman_encoding)</pre><pre>Total_Gain(data, huffman_encoding)</pre><pre>encoded_output = Output_Encoded(data, huffman_encoding)</pre><pre>return encoded_output, nodes[0]</pre><pre>def Huffman_Decoding(encoded_data, huffman_tree):</pre><pre>tree_head = huffman_tree</pre><pre>decoded_output = []</pre><pre>for x in encoded_data:</pre><pre>if x == &#39;1&#39;:</pre><pre>huffman_tree = huffman_tree.right</pre><pre>elif x == &#39;0&#39;:</pre><pre>huffman_tree = huffman_tree.left</pre><pre>try:</pre><pre>if huffman_tree.left.symbol == None and huffman_tree.right.symbol == None:</pre><pre>pass</pre><pre>except AttributeError:</pre><pre>decoded_output.append(huffman_tree.symbol)</pre><pre>huffman_tree = tree_head</pre><pre>string = &#39;&#39;.join([str(item) for item in decoded_output])</pre><pre>return string</pre><pre>data = &quot;huffman&quot;</pre><pre>print(data)</pre><pre>encoding, tree = Huffman_Encoding(data)</pre><pre>print(&quot;Encoded output&quot;, encoding)</pre><pre>print(&quot;Decoded Output&quot;, Huffman_Decoding(encoding, tree))</pre><p><a href="https://colab.research.google.com/drive/1zA5dXY9g40FfOeGrLGd49ZPq9M6xf8Ik?usp=sharing">Google Colaboratory</a></p><p>Code contributed by <a href="https://medium.com/u/483d2ec29b96">Gugu Sibanyoni</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=424d40d92f70" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/huffman-encoding-424d40d92f70">Huffman Encoding</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[String Manipulation in Python: A Comprehensive Guide]]></title>
            <link>https://python.plainenglish.io/string-manipulation-in-python-a-comprehensive-guide-99c10be6b911?source=rss-e668bb8b2f76------2</link>
            <guid isPermaLink="false">https://medium.com/p/99c10be6b911</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Thenjiwe kubheka]]></dc:creator>
            <pubDate>Wed, 13 Oct 2021 07:58:05 GMT</pubDate>
            <atom:updated>2021-10-13T07:58:05.717Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dwVL-apx5IpEtuHyz9vLCw.jpeg" /><figcaption>Source: Brett Jordan via<a href="https://unsplash.com/photos/POMpXtcVYHo"> Unsplash.com</a></figcaption></figure><p>As a software developer, you will be dealing with strings quite regularly. It is important you master all the tricks you can apply to them. This is why string manipulation is tested in coding interviews.</p><p>We will evaluate Python functions and methods that allow you to manipulate strings.</p><h3>Escape Characters</h3><h4>1. Escape Characters</h4><p>These are characters in Python represented with backslash (\).<br>Backslash n also expressed as (\n) represents a new line.</p><p>Backslash t also represented as (\t) represents tab, backslash backslash (\\) is the actual backslash character in strings.</p><p>Example:</p><p>We have the variable “words” and it contains the string, “Let us master Python strings”. We want stings to fall into a new line and we will use (\n) to tell the interpreter to take strings to a line of its own.</p><pre>words = “Let us master Python \n strings”</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*UfWHhvTWOzYJFlTMpDIjSw.png" /></figure><p>Let us test the tab escape character;</p><pre>words = &quot;Let \t us master strings</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*ZIqzrs_3EHuAwokR2Hf4pA.png" /></figure><h3>Raw Strings</h3><p>Our next useful function for strings is the raw string function, that allows us to include nested characters such as “” and \.</p><p>If we want to ignore the escape characters (\) and “” we can use the regex method, the r will convert our entire string to a normal string</p><p>r = represents regex characters, which is a method that converts our entire sentence into normal characters, so let’s say we put it in the sentence we put the r in the sentence of (/n) then the escape character will be ignored.</p><p>Example:</p><pre>words = “Let \t us master strings”</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/0*19-74UOuqjofhklm" /></figure><pre>words = r”Let \t us master strings”</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/0*uo1Imoh-RXZTAXkE" /></figure><p>As you can notice above the \t does not play the role of escape character, it is a normal character in the string.</p><h3>In and Not in</h3><p>in and not in operation in strings, if we have a string “Facebook was down” and we want to check if a specific word exists in the sentence.</p><p>Example:</p><pre>words = “Facebook was down”</pre><p>“Facebook” in words this would return True<br>“Twitter” in words we will get false</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/0*8kaFWqHfdO4hXSHM" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/0*D7-04TQFmSTSFKkT" /></figure><p>We can also use a not in function to check if it does not exist, i.e. “Facebook” not in words, we will get False as it does exist.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/0*qDDpFMpHgN2rU8oQ" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/0*p49sDoRAbky99EtN" /></figure><p>So, in and not in are two functions you can use to see if some specific string or word exists in a bunch of texts.</p><h3>Upper, Lower, isUpper, isLower</h3><p>Example:</p><p>We have the string “I love blue coding”</p><pre>words = “I love blue coding”</pre><p>We want to convert this sentence to all uppercase, so we can use the Python function words.upper() to convert our entire text to all caps lock and words.lower() to convert it all to lower case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/0*C_JNbGPCq1E49ffz" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/0*bvx5WWe8QqupkRLe" /></figure><p>To check if the text is upper case or lower case, we can use the isupper() or islower().</p><pre>words = “I love coding” </pre><p>words.isupper()</p><p>or</p><p>words.islower()</p><p>So upper and lower are two functions you can use to uppercase or lowercase your strings simultaneously.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/0*jhen0xv7t-mKriOK" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/0*-9ziHzeLWHNrcjPZ" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/0*PBkElmI-IsKIm6XR" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/0*SqB_Rfwlr0vhxs26" /></figure><h3>Is Function</h3><p>The is function is used to see if statements are True or False, so the function returns True or False<br><br><strong>isnumeric()</strong></p><pre>words = ‘zero’</pre><p>We want to know if words.isnumeric() is true or false.</p><pre>words = ‘0’</pre><p>We also want to know if words.isnumeric() is true or false</p><p>Interestingly we can also use the .isdigit() in this case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/0*c8UNgZXP2nGMnIbW" /></figure><p><strong>isdecimal()</strong></p><pre>number = “\u001” #unicode for 1</pre><p>We want to know if words.isdecimal() is true or false.</p><pre>words = “1.5”</pre><p>We also want to know if words.isdecimal() is true or false.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/0*LWuSaDOXz6mdnQEd" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/0*7wKMPFyqfKUpeXae" /></figure><h3>Starts With and End With</h3><p>Starts with function is something we can apply to strings to check if a string starts with or ends with a certain word.</p><pre>words = “We will proceed to the next task”</pre><p>We want to check if “We” is the first letter of the sentence.</p><pre>words.startswith(“We”)</pre><p>When we want to check if the sentence ends with “task”.</p><pre>words.endswith(“task”)</pre><p>These are very fun functions we can use to check the beginning and the ending of your sentences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/0*98hwmzhs9YJ4wHky" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/0*jxY59FJaVudUB8i9" /></figure><h3>Split Function</h3><p>Whenever we have a sentence, let’s say it is one giant sentence, and we want every individual word and we want to apply some other function to that individual word and we want to split that sentence by something.</p><pre>sent = “ Ruby is walking the dog” </pre><p>We want to split this and perform functions on each character in the string. Using the split function, we can go ahead and split by space, the split function takes in the delimiter by which you want to split up every single word or every single item inside of your string. So by splitting it by space every single time the Python interpreter encounters a space, it will go ahead and remove it and store it as an array.</p><pre>sent.split(“”) </pre><p>We get every single character in the string</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/0*vVPl1l2EUGP_NPaj" /></figure><h3>Split and Join function</h3><p>Similarly, for when we want to join our sentence. The split function has split up our entire sentence into five different words.</p><p>Let’s store it</p><pre>splitUpSentence = sent.split()</pre><pre>mySeparator = space</pre><p>Then we want to join our sentence splitUpSentence.join but we have to join with a specific keyword</p><pre>“ ”.join(splitUpSentence) </pre><p>What the join did was add a space in the split sentence.</p><p>The split function is used to split up the string based on a specific delimiter and the join function is used to append something to every single item in your list.</p><p>The split function is very useful when dealing with CSV files.</p><p>Example:</p><pre>data = “apple, orange, cherry”<br>data.split(“, “)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/0*6iIDlsEkWizF9N1y" /></figure><h3>Strip Function</h3><p>The strip function removes all of the excess space that we do not want.<br>We can also specify where we want to strip that extra text from, we can strip left or right.</p><pre>sent = “This is a sentence”</pre><p>We can use sent.lstrip() to strip left, .lstrip strips all the extra whitespace on the left.</p><p>We can use sent.rstrip() to strip right, rstrip strips all the extra whitespace on the right.</p><p>And lastly, .strip can be used to strip extra whitespace on both sides. So essentially, the strip function is used to remove all the extra whitespace we might have.</p><p>Example:</p><p>All the access space is removed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/0*TmYu12c_r9LTsNf2" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/0*IDynOTmmCKS1Wf__" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/0*dWC7Q7QAUuORgLv9" /></figure><p>Let’s day we accidentally split the data</p><pre>data.strip(“cherry”) </pre><p>And there are whitespaces before the cherry, then we can use the strip function to get rid of the whitespaces.</p><pre>data.rstrip(“cherry”)</pre><h3>Additional Reading:</h3><p><a href="https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str">Built-in Types - Python 3.10.0 documentation</a></p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99c10be6b911" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/string-manipulation-in-python-a-comprehensive-guide-99c10be6b911">String Manipulation in Python: A Comprehensive Guide</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Algorithmic Analysis]]></title>
            <link>https://levelup.gitconnected.com/algorithmic-analysis-92b8b78ba83d?source=rss-e668bb8b2f76------2</link>
            <guid isPermaLink="false">https://medium.com/p/92b8b78ba83d</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Thenjiwe kubheka]]></dc:creator>
            <pubDate>Mon, 11 Oct 2021 11:22:53 GMT</pubDate>
            <atom:updated>2021-10-12T14:52:37.648Z</atom:updated>
            <content:encoded><![CDATA[<p><em>In the previous article on our introduction to </em><a href="https://levelup.gitconnected.com/algorithms-3bd92fa4155f"><em>algorithms</em></a><em>, we spoke about algorithmic analysis. And in this article we will go in depth.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oAgFgTZcGRhcxDT-74m9hQ.jpeg" /><figcaption>Source: Micheal Dziedzic via <a href="https://unsplash.com/photos/aQYgUYwnCsM">Unsplash.com</a></figcaption></figure><h3>Writing An Algorithm</h3><p>Before we can analyze an algorithm, we need to write it first. So how do we write it?</p><pre>Algorithm Swap(a,b):<br>    temp = a<br>    a = b<br>    b = temp<br>return</pre><p>Above is a simple algorithm, I have borrowed some Python syntax. I said in the previous articles algorithms are syntax independent, which I still stand by.</p><p>I just borrowed the Python syntax so we can see where the name of the algorithm starts. The commands within the algorithm and where the algorithm ends.</p><p>We do not have variable declarations as they are not needed, syntax to start a function, etc.</p><h3>Analyzing An Algorithm</h3><p>Now that we now how to write an algorithm, we can move on to analyzing an algorithm.</p><p>We need to consider the following for algorithms;</p><ul><li>Time</li><li>Memory</li><li>Data Consumption(How much data your algorithm consumes)</li><li>Power Consumption</li></ul><p>We will only be focusing on time and space analysis for our algorithmic article series. These two are measured in Big O notation</p><h3>Time Taken By An Algorithm</h3><p>How long will an algorithm take to complete a specific task.</p><p>Say we want an algorithm to find the shortest path between A.B.C.D and return the answer to the user.</p><p>We will write this algorithm and after that check how much time it takes to complete this task. We do not want algorithms that take long to complete a task.</p><p>Let us start with statements;</p><p>A simple direct statement in an algorithm takes one unit of time.</p><p>Example:</p><p>temp = a, this is one unit of time.</p><p>a = b, this is also another unit of time.</p><p>The above statements are very direct, straight to the point and not calling any other algorithm, hence they are not nested statements.</p><p>Let’s analyze the time analyses of our above function:</p><pre>Algorithm swap(a,b):<br>    temp = a<br>    a = b<br>    b = temp<br>return</pre><p>We count all of our statements, temp = a, a = b and b = temp. Each of these statements take 1 unit of time.</p><p>temp = a (1)</p><p>a = b (1)</p><p>b = temp (1)</p><p>So our f(n) is 3, which is a constant value. Any integer number is considered as a constant value.</p><p>We can already see the pattern that all assignment statements take one unit of time.</p><p>We can represent constant values with O(1), all the integer numbers are O(1).</p><p>Lets analyze the space complexity of this algorithm:</p><p>To analyze space complexity we look at the variables, in our case we have a,b, and temp.</p><p>All in all we have used three variables. Our space complexity is O(3).</p><p>We can calculate time complexity in two ways, first one being frequency count and the other asymptotic notations.</p><h3>Frequency Count</h3><p>Frequency count specifies the number of times a statement is to be executed, so how many times the statement within our algorithm is executed.</p><p>I generally follow this four rules basis:</p><ul><li>For comments and declarations the step count is 0, as comments are not executed, and declarations are not needed while writing the algorithm.</li><li>For the return and assignment statement the step count is 1, assignment statement is simply assigning a left hand value to a right hand value. While the return statement is just returning a value.</li><li>Only consider higher order exponents. E.g.; 3n² +4n. We will only consider 3n² as it has the higher order exponent.</li><li>Ignore the constant value multipliers. We are left with 3n², our constant multiplier is 3, we ignore it and are left with n². Our time complexity is O(n²).</li></ul><p>Lets get our feet wet with some examples;</p><pre>Algorithm Sum(A,n):<br>    s = 0<br>    for i in A:<br>        s = s + A[i]<br>        return s</pre><p>The algorithm above is an array of a certain size, let us say the array has 4 elements within it. The elements within the array are 9,6,10,5,6</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*5LP8uNahYB_zkLPMiwormw.png" /></figure><p>A is our array and n is the number of elements. The algorithm above is finding the sum of all the elements in the array. We want to find the time taken by the algorithm, we will do this by finding the frequency count method, and our four rules.</p><p>Breaking down the algorithm;</p><p>Initially i is 0, as we have a for loop we know our algorithm is repeating a certain number of times, and this number of times is n.</p><p>Lets count with it;</p><p>i = 0</p><p>i = 1</p><p>i = 2</p><p>i = 3</p><p>i = 4</p><p>i = 5</p><p>The loop stops and returns the value at s, this is when the algorithm is done looping. The logic of this goes as follows; i = 0 and 0 &lt; n, i = 1 and 1&lt;n, i = 2 and 2 &lt; n, i = 3 and 3 &lt; n, i = 4 and 4 &lt; n, i = 5 and 5 &gt; n. The loop will stop at i = 5 as 5 is greater than n.</p><p>The condition is checked 5 times all in all. Four times the condition was true i &lt; n and the fifth time false, i &gt; n. Our loop is executing for n + 1 times. How would we count the For loop, as it executes n + 1 times then we count it as n+1 steps.</p><p>Summarizing;</p><pre>Algorithm Sum(A,n):     0<br>    s = 0 -1<br>    for i in range(A):  n+1<br>        s = s + A  n(1) <br>        return s    1</pre><p>The first line of our algorithm;</p><p>Algorithm Sum(A,n): this does not count for anything as it is a declaration and the step count is 0.</p><p>The second line of our algorithm;</p><p>s = 0; this is given a value of 1 in the step count frequency method as it is an assignment statement.</p><p>The third line in our algorithm;</p><p>for i in range A: the statement will tell our interpreter that loop inside the array until you complete the range of the array. This means we will loop n + 1 times.</p><p>The fourth line in our algorithm;</p><p>s = s + A[i]; this an assignment statement as we are assigning s to s + A[i], and because this statement is within a loop, we will assign n as its value.</p><p>The 5th line in our algorithm;</p><p>return s; as it is a return statement then the step count is 1</p><p>Tally up our values;</p><p>1+n+1+n+1 = 2n + 3</p><p>2n + 3</p><p>We only consider the higher order exponents, this means we will only be left with 2n.</p><p>Then we will ignore will constant multiplier, and we will be left with n, hence we be left with O(n).</p><p>Moving on to space complexity of the algorithm. We only count the variables in our algorithm.</p><p>We have s, A ,n, i;</p><p>A = n ( A is our array which has n elements, hence it is n)</p><p>s = 1 ( s only occupies one element)</p><p>n =1 ( n only occupies one element)</p><p>i = 1 ( i only occupies one element)</p><p>Tally count;</p><p>n+1+1+1+1 = n + 4, we only consider the higher order exponents and are left with n.</p><p>O(n).</p><p>Example 2:</p><pre>Algorithm Add(A,B,n):<br>    for i in range(A):<br>        for j in range(A):<br>            C = A + B<br>    return</pre><p>With our example two we have two nested loops, the outer For loop and the inner for loop. Additionally we have a metrices or what is known as a two dimensional array.</p><p>Which are size 3 * 3, also expressed as n * n, hence we can say our above algorithm finds the sum of two metrices.</p><pre>Algorithm ADD(A,B,n):   0<br>    for i in range(A):     n+1<br>        for j in range(A): n(n+1)<br>            c = A + B      n(n)<br>   return       1</pre><p>Starting from the first statement, we ignore Algorithm ADD(A,B,n):</p><p>Second line we have our outer for loop and our step count is n+1.</p><p>Third line we have our inner for loop, which has n as it is within a loop, in this case the outer loop. As it is a loop itself we also assign n+1 to it. The second loop will have n as it is within a loop and n+1 as it is a loop itself(it loops n+1 times even thou it is within a loop).</p><p>The fourth line we have c = A + B, it is within two for loops, for the first loop we will assign n and the second loop another n.</p><p>The last line we have&lt; return 1, it returns after the For loop.</p><p>Tally: n + 1 +n² +1 + n² + 1</p><p>2n² n +3</p><p>Only consider higher order exponents, we will be left with 2n².</p><p>2n², we ignore the multiplier constant.</p><p>We are left with n², hence we will have O(n²).</p><h3>Additional Reading:</h3><p><a href="https://www.geeksforgeeks.org/basic/frequency-counting/">Frequency-counting - Basic Articles</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92b8b78ba83d" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/algorithmic-analysis-92b8b78ba83d">Algorithmic Analysis</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>