<?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 Python Script on Medium]]></title>
        <description><![CDATA[Stories by Python Script on Medium]]></description>
        <link>https://medium.com/@pythonscript?source=rss-c978bd1f14c8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7jNRRreBWaKvmEHbRcoBsQ.jpeg</url>
            <title>Stories by Python Script on Medium</title>
            <link>https://medium.com/@pythonscript?source=rss-c978bd1f14c8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 07:33:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pythonscript/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[Psychology in Machine Learning]]></title>
            <link>https://faun.pub/psychology-in-machine-learning-33812c1fa428?source=rss-c978bd1f14c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/33812c1fa428</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[psychology-behind]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[psychology]]></category>
            <category><![CDATA[machine-intelligence]]></category>
            <dc:creator><![CDATA[Python Script]]></dc:creator>
            <pubDate>Tue, 22 Mar 2022 14:32:23 GMT</pubDate>
            <atom:updated>2022-06-02T14:02:53.659Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article I would try my best to explain the relation between psychology and machine Learning.</p><p>Learning is the process of converting experience into expertise or knowledge. The input to a learning algorithm is training data representing experience and the output is expertise which usually takes the form of another computer program that can perform some task</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MW92ba-3VBUwNlqb" /><figcaption>Photo by <a href="https://unsplash.com/@nickmorrison?utm_source=medium&amp;utm_medium=referral">Nick Morrison</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>lets consider a couple of examples from naturally occuring animal learning —</p><p><strong><em>Bait Shyness </em></strong>— <em>Rats Learning to avoid Baits</em> : When rats encounter food items with novel look or smell, they willl first eat very small portions and subsequent feeding will depend on the flavor of the food and physiological effect. If the food produces an ill effect, the noval food will often be associated with the illness, and subsequently, the rats will not eat. Clearly, there is a learning mechanisn in play here — animal used past experience with some food to aquire expertise in detecting the safety of this food. If the past experience with the food was negatively labeled, the animal predicts that it will also have a negative effect when encountered in the future.</p><p>Inspired by the preceding example of successful learning, let us demonstrate a typical machine learning task. Suppose we would like to program a machine that learns how to filter spam emails. Native solution would be seemingly similar to the way rats lean how to avoid poisonous baits. The machine will simply memorise all previous emails that had been labeled as spam emails by the human user. When a new email arrives, the machine will search for it in the set of previous emails. If it matches one of them, it will be trashed. Otherwise it will be moved to the user’s inbox.</p><p>While the preceeding “<strong><em>Learning by memorization</em></strong>” approach is sometimes useful, it lacks an important aspect of learning systems — the ability to label unseen email. A successful learner should be able to progress from individual examples to broader generalization. This is also refered to as <em>inductive reasoning</em> or <em>inductive inference.</em> To achieve generalization in the spam filtering task, the learner can scan the previously seen emails and extract a set of words whose apperance in an email is indicative of spam. Then, when a new email arrives, the machine can check whether one of the suspicious words appears in it, and predict its label accordingly. Such a system would potentially be able correctly to predict the label of unseen emails</p><p>However, inductive reasoning might lead us to false conclusions. To illustrate this, let us consider again an example from animal learning.</p><p><strong><em>Pigeon Superstition</em></strong>: In an experiment performed by phychologist B.F Skinner, he placed a bunch of hungry pigeons in a cage. An Automatic Mechanism had been attached to the cage, delivering food to the pigeons at regular intervals with no reference whatsoever to the birds’ behaviour. The hungary pigeons went around the cage, and when food was first delivered, it found each pigeon engaged in some activity such as pecking, turning the head, etc. The arrival of food reinforced each bird’s specific action, and consequnetly, each bird tended to spend some more time doing that very same action. That in turn, increased the chance that the next random food delivery would find each bird engaged in that activity again. What results is a chan of events that reinforces the pigeons’ association of the delivey of the food with whatever chance actins they had been performing when it was first delivered. They subseqently continue to perform these same actions diligently.</p><p>While human learners can rely on common sense to filter out random meaningless learning conclusions, once we export the task of learning to a machine, we must provide well defined crisp principles that will protect the program from reaching senseless or useless conclusions. The development of such principal is a central goal of the theory of machine learning.</p><p>Now, let us have a closer look at the bait shyness phenomenon in rats.</p><p><strong><em>Bait Shyness revisited — </em></strong><em>rats fail to acquire conditioning between food and electric shock or between sound and nausea</em>: The bait shyness mechanism in rats turns out to be more complex than what one may expect. In experiments carried out by Garcia, it was demonstrated that if the unpleasant stimulus that follows food consumption is replaced by electrical shock rather than nausea, then no conditioning occurs. Even after repeated trials in which the consumption of some food is followed by the administration of unpleasant electrical shock, the rists do not tend to avoid that food. Similar failure of conditioning occurs when the characteristic of the food that implies nausea (such as taste or smell) is replaced by a vocal signal. The rats seem to have some “built in” prior knowledge telling them that, while temporal correlation between food and nausea can be causal, it is unlikely that there would be a causal relationship between food consumption and electrical shocks or between sounds and nausea.</p><p>We conclude that one distinguishing feature between the bait shyness learn ing and the pigeon superstition is the incorporation of prior knowledge that biases the learning mechanism. This is also referred to as inductive bias. The pigeons in the experiment are willing to adopt any explanation for the occurrence of food. However, the rats “know” that food cannot cause an electric shock and that the co-occurrence of noise with some food is not likely to affect the nutritional value of that food. The rats’ learning process is biased toward detecting some kind of patterns while ignoring other temporal correlations between events.</p><p>It turns out that the incorporation of prior knowledge, biasing the learning process, is inevitable for the success of learning algorithms which is formally stated and proved as the “<strong><em>No-Free-Lunch theorem</em></strong>” . The development of tools for expressing domain expertise, translating it into a learning bias, and quantifying the effect of such a bias on the success of learning is a central theme of the theory of machine learning. Roughly speaking, the stronger the prior knowledge or prior assumptions that one starts the learning process with, the easier it is to learn from further examples. However, the stronger these prior assumptions are, the less flexible the learning is — it is bound, a priori, by the commitment to these assumptions.</p><p>……………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………….</p><p>Please support this article by simply following me here on Medium.</p><p>For video content you can check out my YT channel — <a href="https://www.youtube.com/c/PythonScript">https://www.youtube.com/c/PythonScript</a></p><p>Ciao !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*A_7a_LLNPpUfaEHi.png" /></figure><h4>If this post was helpful, please click the clap 👏 button below a few times to show your support for the author 👇</h4><h4>🚀Developers: Learn and grow by keeping up with what matters, <a href="https://faun.to/8zxxd">JOIN FAUN.</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33812c1fa428" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/psychology-in-machine-learning-33812c1fa428">Psychology in Machine Learning</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[Secure Workloads in Google Kubernetes Engine: Challenge Lab (GSP335)]]></title>
            <link>https://pythonscript.medium.com/secure-workloads-in-google-kubernetes-engine-challenge-lab-gsp335-4c324684e142?source=rss-c978bd1f14c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c324684e142</guid>
            <category><![CDATA[google]]></category>
            <category><![CDATA[workload]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[challenge]]></category>
            <dc:creator><![CDATA[Python Script]]></dc:creator>
            <pubDate>Thu, 27 Jan 2022 06:39:55 GMT</pubDate>
            <atom:updated>2022-01-27T06:39:55.442Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w-w1ReD3Lf6LTQXTcvcrIw.png" /><figcaption>Step by Step Tutorial</figcaption></figure><p>In this tutorial blog, I am gonna show you how you can complete the lab — Secure Workloads in Google Kubernetes Engine which is the challenge lab on qwiklab platform. So, without wasting any other time lets start -</p><h4>Task 0— Is to download required file for the lab</h4><pre>gsutil cp gs://spls/gsp335/gsp335.zip .<br>unzip gsp335.zip</pre><h4>Task 1— Is to setup cluster for the lab</h4><pre>gcloud container clusters create &lt;Cluster Name&gt;\<br> — zone us-central1-c \<br> — machine-type n1-standard-4 \<br> — num-nodes 2 \<br> — enable-network-policy</pre><pre>gcloud container clusters get-credentials &lt;Cluster Name&gt; --zone us-central1-c</pre><h4>Task 2 — Is to setup WordPress</h4><pre>gcloud sql instances create &lt;Cloud SQL Instance&gt; --region us-central1</pre><pre>gcloud sql databases create wordpress --instance &lt;Cloud SQL Instance&gt; --charset utf8 --collation utf8_general_ci</pre><pre>gcloud sql users create wordpress --host % --instance &lt;Cloud SQL Instance&gt; --password Passw0rd</pre><p>Create a service account for access to your WordPress database from your WordPress instances</p><pre>gcloud iam service-accounts create &lt;Service Account&gt;</pre><pre>gcloud projects add-iam-policy-binding $DEVSHELL_PROJECT_ID \<br>   --member=&quot;serviceAccount:&lt;&lt;Service Account&gt;&gt;@$DEVSHELL_PROJECT_ID.iam.gserviceaccount.com&quot; \<br>   --role=&quot;roles/cloudsql.client&quot;</pre><pre>gcloud iam service-accounts keys create key.json --iam-account=&lt;&lt;Service Account&gt;&gt;@$DEVSHELL_PROJECT_ID.iam.gserviceaccount.com</pre><pre>kubectl create secret generic cloudsql-instance-credentials --from-file key.json</pre><pre>kubectl create secret generic cloudsql-db-credentials \<br>   --from-literal username=wordpress \<br>   --from-literal password=&#39;Passw0rd&#39;</pre><p>Create the WordPress deployment and service</p><pre>kubectl create -f volume.yaml</pre><p>Open wordpress.yaml and replace INSTANCE_CONNECTION_NAME with the instance name of your Cloud SQL database (the format is <em>project:region:databasename</em>)</p><pre>kubectl apply -f wordpress.yaml</pre><h4>Task 3 — Setup Ingress with TLS</h4><pre>helm version</pre><pre>helm repo add stable <a href="https://charts.helm.sh/stable">https://charts.helm.sh/stable</a><br>helm repo update</pre><pre>curl -fsSL -o get_helm.sh <a href="https://raw.githubusercontent.com/helm/helm/master/scripts/get-helm-3">https://raw.githubusercontent.com/helm/helm/master/scripts/get-helm-3</a><br>chmod 700 get_helm.sh<br>./get_helm.sh</pre><pre>helm install nginx-ingress stable/nginx-ingress --set rbac.create=true</pre><pre>kubectl get service nginx-ingress-controller -w</pre><pre>. add_ip.sh</pre><pre>kubectl apply -f <a href="https://github.com/jetstack/cert-manager/releases/download/v1.2.0/cert-manager.yaml">https://github.com/jetstack/cert-manager/releases/download/v1.2.0/cert-manager.yaml</a></pre><pre>kubectl create clusterrolebinding cluster-admin-binding \<br>   --clusterrole=cluster-admin \<br>   --user=$(gcloud config get-value core/account)</pre><blockquote><strong><em>. add_ip.sh </em></strong>command will return something like <strong><em>student0300fdd647df7f.labdns.xyz</em></strong> save it somewhere because it will be use latter.</blockquote><p>Edit issuer.yaml and set the email address to the email address of your wordpress service account.</p><pre>kubectl apply -f issuer.yaml</pre><p>Edit ingress.yaml and set the dns and domain name to your YOUR_LAB_USERNAME.labdns.xyz. Don&#39;t forget to remove any _ characters from your username when using it as the dns</p><pre>kubectl apply -f ingress.yaml</pre><h4>Task 4 - set up Network Policy</h4><p>Now go to editor and in network-policy.yaml add to end</p><pre>---<br>apiVersion: networking.k8s.io/v1<br>kind: NetworkPolicy<br>metadata:<br>  name: allow-world-to-nginx-ingress<br>  namespace: default<br>spec:<br>  podSelector:<br>    matchLabels:<br>      app: nginx-ingress<br>  policyTypes:<br>  - Ingress<br>  ingress:<br>  - {}</pre><p>Save the file and then run the following command</p><pre>kubectl apply -f network-policy.yaml</pre><p>Task 5 — Setup Binary Authorization</p><p>Configure Binary Authorization Policy<br>1) In the Cloud Console, navigate to Security &gt; Binary Authorization.<br>2) Enable the Binary Authorization API.<br>3) On the Binary Authorization page, click on CONFIGURE POLICY.<br>4) Select Disallow all images for the Default rule.<br>5) Scroll down to Images exempt from this policy, click ADD IMAGE PATH.<br>6) Paste docker.io/library/wordpress:latest to the textbox, and click DONE.<br>7) Repeat the above two steps to add the following image paths:<br> — us.gcr.io/k8s-artifacts-prod/ingress-nginx/*<br> — gcr.io/cloudsql-docker/*<br> — quay.io/jetstack/*<br>8) Click SAVE POLICY.</p><p>Enable Binary Authorization in Google Kubernetes Engine<br>1) Navigate to Kubernetes Engine &gt; Clusters.<br>2) Click your cluster name to view its detail page.<br>3) Click on the pencil icon for Binary authorization under the Security section.<br>4) Check Enable Binary Authorization in the dialog<br>5) Click SAVE CHANGES</p><p>Task 6 — Setup Pod Security Policy</p><pre>kubectl apply -f psp-restrictive.yaml<br>kubectl apply -f psp-role.yaml<br>kubectl apply -f psp-use.yaml</pre><p>Hope it helped :))<br>If you find it little bit useful subscribe “PythonScript” on youtube (It means a lot)</p><p>Link of the channel — <a href="https://www.youtube.com/channel/UCXhIDPF_kw_KDTqyVZtyxbw">PythonScript — YouTube</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c324684e142" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create a static HTML web app by using Azure Cloud Shell]]></title>
            <link>https://pythonscript.medium.com/how-to-create-a-static-html-web-app-by-using-azure-cloud-shell-ce1eb2af4e1c?source=rss-c978bd1f14c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce1eb2af4e1c</guid>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[web-app-development]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[Python Script]]></dc:creator>
            <pubDate>Sat, 15 Jan 2022 09:08:31 GMT</pubDate>
            <atom:updated>2022-01-15T09:08:31.888Z</atom:updated>
            <content:encoded><![CDATA[<p>In this tutorial we’ll deploy a basic HTML+CSS site to Azure App Service by using the Azure CLI <strong><em>az webapp up</em></strong> command. we will also update the code and redeploy it by using the same command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o15M7-AcKE-jI8WFgFAT6A.png" /><figcaption>Get this image on: <a href="https://commons.wikimedia.org/wiki/File:Microsoft_Azure_Logo.svg">Wikimedia Commons</a> | <a href="https://creativecommons.org/licenses/by-sa/4.0">License details</a></figcaption></figure><p>The <strong><em>az webapp up</em></strong> command makes it easy to create and update web apps. When executed it performs the following actions:</p><ol><li>Create a default resource group.</li><li>Create a default app service plan.</li><li>Create an app with the specified name.</li><li>Zip deploy files from the current working directory to the web app.</li></ol><blockquote>Before you begin make sure you have the following requirements in place:</blockquote><blockquote>An Azure account with an active subscription. If you don’t already have one, you can sign up for a free trial at <a href="https://azure.com/free">https://azure.com/free</a> .</blockquote><h4># Step 1 — Login to Azure and download the sample app</h4><ul><li>Login to the Azure portal and open the Cloud Shell</li><li>After the shell opens be sure to select the Bash environment.</li><li>In the Cloud Shell, create a directory and then navigate to it</li></ul><pre>mkdir htmlapp <br>cd htmlapp</pre><ul><li>Run the following git command to clone the sample app repository to your htmlapp directory.</li></ul><pre>git clone <a href="https://github.com/Azure-Samples/html-docs-hello-world.git">https://github.com/Azure-Samples/html-docs-hello-world.git</a></pre><h4># Step 2 — Create the web app</h4><ul><li>Change to the directory that contains the sample code and run the az webapp up command. In the following example, replace with a unique app name, and with a region near you.</li></ul><pre>cd html-docs-hello-world <br>az webapp up --location &lt;myLocation&gt; --name &lt;myAppName&gt; --html</pre><p>This command may take a few minutes to run. While running, it displays information similar to the example below. Make a note of the resourceGroup value. You need it for the Clean up resources section later.</p><pre>{ <br>&quot;app_url&quot;: &quot;https://.azurewebsites.net&quot;, <br>&quot;location&quot;: &quot;westeurope&quot;, <br>&quot;name&quot;: &quot;&lt;app_name&gt;&quot;,<br>&quot;os&quot;: &quot;Windows&quot;, <br>&quot;resourcegroup&quot;: &quot;&lt;resource_group_name&gt;&quot;, <br>&quot;serverfarm&quot;: &quot;appsvc_asp_Windows_westeurope&quot;, <br>&quot;sku&quot;: &quot;FREE&quot;, <br>&quot;src_path&quot;: &quot;/home//demoHTML/html-docs-hello-world &quot;,  <br>}</pre><ul><li>Open a browser and navigate to the app URL i.<em>e http://&lt;myAppName&gt;.azurewebsites.net</em> and verify the app is running — take note of the title at the top of the page. Leave the browser open on the app for the next section.</li></ul><h4># Step 3 — Update and redeploy the app</h4><ul><li>In the Cloud Shell, type code index.html to open the editor. In the &lt;h1&gt; heading tag, change Azure App Service — Sample Static HTML Site to Azure App Service Updated — or to anything else that you’d like.</li><li>Use the commands <strong><em>ctrl-s</em></strong> to save and <strong><em>ctrl-q</em></strong> to exit</li><li>Redeploy the app with the same az webapp up command. Be sure to use the same values for &lt;myLocation&gt; and &lt;myAppName&gt; as you used earlier.</li></ul><pre>az webapp up --location &lt;myLocation&gt; --name &lt;myAppName&gt; --html</pre><ul><li>Once deployment is completed switch back to the browser from step 2 in the “Create the web app” section above and refresh the page.</li></ul><h4># Step 4— Clean up resources</h4><p>If you no longer need the resources you created in this exercise you can delete the resource group using the az group delete command below. Replace &lt;resource_group&gt; with resource group name you noted in step 1 of the “Create the web app” section above</p><pre>az group delete --name &lt;resource_group&gt;  --no-wait</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce1eb2af4e1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Azure App Service]]></title>
            <link>https://pythonscript.medium.com/introduction-to-azure-app-service-60afa820f83?source=rss-c978bd1f14c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/60afa820f83</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[web-app-development]]></category>
            <category><![CDATA[apps]]></category>
            <category><![CDATA[azure-devops]]></category>
            <dc:creator><![CDATA[Python Script]]></dc:creator>
            <pubDate>Fri, 14 Jan 2022 12:09:23 GMT</pubDate>
            <atom:updated>2022-01-14T12:09:23.145Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/282/0*uxQWJofPVNEi1bRs.png" /><figcaption><a href="https://commons.wikimedia.org/wiki/File:Azure.png">Wikimedia Commons</a> | <a href="https://creativecommons.org/licenses/by-sa/4.0">License details</a></figcaption></figure><p>Azure App Service is an HTTP-based service for hosting web applications, REST APIs, and mobile back ends. You can develop in your favorite language, be it .NET, .NET Core, Java, Ruby, Node.js, PHP, or Python. Applications run and scale with ease on both Windows and Linuxbased environments.</p><p>Baked into Azure App Service is the ability to scale up/down or scale out/in. Depending on the usage of the web app, you can scale your app up/down the resources of the underlying machine that is hosting your web app. Resources include the number of cores or the amount of RAM available. Scaling out/in is the ability to increase, or decrease, the number of machine instances that are running your web app.</p><p>The Azure portal also provides out-of-the-box continuous integration and deployment with Azure DevOps, GitHub, Bitbucket, FTP, or a local Git repository on your development machine. Connect your web app with any of the above sources and App Service will do the rest for you by auto-syncing code and any future changes on the code into the web app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*asJB7HGkA_hpF9h8" /><figcaption>Get this image on: <a href="https://pxhere.com/en/photo/1635932">PxHere</a> | <a href="https://creativecommons.org/licenses/publicdomain/">License details</a></figcaption></figure><p>Using the Azure portal, or command-line tools, you can easily add deployment slots to an App Service web app. For instance, you can create a staging deployment slot where you can push your code to test on Azure. Once you are happy with your code, you can easily swap the staging deployment slot with the production slot. You do all this with a few simple mouse clicks in the Azure portal.</p><p>App Service can also host web apps natively on Linux for supported application stacks. It can also run custom Linux containers (also known as Web App for Containers). App Service on Linux supports a number of language specific built-in images. Just deploy your code. Supported languages include: Node.js, Java (JRE 8 &amp; JRE 11), PHP, Python, .NET Core, and Ruby. If the runtime your application requires is not supported in the built-in images, you can deploy it with a custom container. The languages, and their supported versions, are updated on a regular basis. You can retrieve the current list by using the following command in the Cloud Shell.</p><pre>az webapp list-runtimes --linux</pre><p><strong><em>Limitations</em></strong></p><p>App Service on Linux does have some limitations:</p><ol><li>App Service on Linux is not supported on Shared pricing tier.</li><li>You can’t mix Windows and Linux apps in the same App Service plan.</li><li>Historically, you could not mix Windows and Linux apps in the same resource group. However, all resource groups created on or after January 21, 2021 do support this scenario. Support for resource groups created before January 21, 2021 will be rolled out across Azure regions (including National cloud regions) soon.</li><li>The Azure portal shows only features that currently work for Linux apps. As features are enabled, they’re activated on the portal.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60afa820f83" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beginner guide to Ethereum]]></title>
            <link>https://pythonscript.medium.com/beginner-guide-to-ethereum-6765c1cddd0b?source=rss-c978bd1f14c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/6765c1cddd0b</guid>
            <category><![CDATA[ethereum-blockchain]]></category>
            <category><![CDATA[remix]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Python Script]]></dc:creator>
            <pubDate>Sat, 13 Nov 2021 07:33:33 GMT</pubDate>
            <atom:updated>2021-11-13T07:33:33.030Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/888/0*IeKS6psC5bkRsMk9.jpg" /><figcaption>Phtoto by — <a href="https://orionx.net/author/shahin/">Shahin Khan</a></figcaption></figure><p>Before we explore the world of Ethereum, let’s understand how the Internet functions. The reason we are doing this is because many experts in the field compare the emergence of blockchain technology to be very similar to how the internet disrupted almost every industry known to us. Our personal data, passwords and financial transaction details are all stored in centralized databases that are hosted and owned by large companies like Google, Amazon, Facebook, etc. Although this setup provides a number of conveniences to its users, the primary advantage being the presence of a team of specialists to monitor and maintain these databases.</p><p>However, there is also exists a major vulnerability. Once a hacker manages to get access into one of these centralized databases, all the information contained in it is compromised. What’s worse is that the data breach will not be apparent until all the damage is done. Bitcoin penetrated into the online banking sector and has left a huge dent. Similarly, Ethereum has been designed with the goal of using blockchain to replace internet third parties that are prevalent today. These include services like messaging applications and online document editing platforms from Evernote to Google docs.</p><p>So who stores the massive amounts of data being generated? People like you and me can volunteer to become a part of the peer-to-peer network, and thereby become a “node”. Thus, all serves and clouds are replaced by a thousands of “nodes” from all over the world. Our individual computers all unite to act a single “World Computer”. This is why Ethereum and the block chain technology it works on is so powerful. Although no individual or company is the owner of Ethereum, any computational process happening on the network cannot take place for free of cost.</p><p>The currency used within the Ethereum network to pay for computationally intensive processes is called Ether. Today, the value of 1 ether is approximately $215.84. This may vary depending on when you’re reading this post. Do check out what the current value of the currency is. What is an ether made of? It is just a unique piece of computer code which is run to pay for the usage of your computational resources. Like physical cash, you don’t require a third party to process the transaction.</p><p>Ethereum introduces us to a term called “Smart Contracts”. This term was introduced way back in 1997 by Nick Szabo. He was a computer scientist, cryptographer and law scholar. Smart contracts are just like contracts in the real world, the only difference being that they are completely digital. A smart contract is a computer program stored inside a block chain. A typical example to explain this is by referring to Kickstarter, an online crowd sourcing platform.</p><p>Product teams will set a funding goal and source money from people who believe in the idea. Kickstarter is a third party which handles these transactions which both the product teams and the public need to trust to handle their money correctly. With smart contracts, we don’t have to rely on a third party like Kickstarter. A smart contract is created to do the work that Kickstarter did. Transactions made by the public for a certain product is stored in the smart contract until the funding goal is reached. If the goal is reached, it sends the money across to the product team for further development of their product. If the funding goal is not reached, it automatically refunds the money to the public who supported the project. Since the smart contract is stored within a blockchain, it is completely distributed and no one is in control of the money. They are immutable and distributed. This means once a smart contract is created, it can never be changed again. The output of the contract is validated by everyone on the network. A single person cannot tamper with the contract and force it to release the funds before the funding goal is reached. Everyone on the network can verify that this attempt was malicious and stop the transaction from taking place.</p><p>This has several applications. For example, banks can issue loans using this technique, insurance companies can process claims, etc. Smart contracts can be specifically programmed using a programming language called “Solidity”, which has a syntax similar to JavaScript. We will now explore this programming language and write our first smart contract.</p><h3>Getting Started With Solidity</h3><p>Solidity is an object-oriented, high-level language for deploying smart contracts. Solidity was developed using C++, Python and JavaScript and is designed to target the Ethereum Virtual Machine (EVM). The main features of Solidity are that it is statically typed, supports inheritance, libraries and complex user-defined types. There are several ways of implementing Solidity code. The method that we will be using is using the in-browser IDE called <a href="https://remix.ethereum.org/">Remix</a>. Let’s write our first “Hello world” program using Solidity to get started. Create a new program by clicking on the plus button on the left side. Call the program helloworld.sol. All solidity programs will have the extension of .sol. Copy the following program.</p><pre>pragma solidity ^0.4.0; //Sets the version of Solidity you&#39;re using<br><br>contract Hello {<br>string name; //Creating a string type variable called name<br>function Hello(){ //Hello constructor<br>name = &quot;Steve&quot;; //Setting the name to a default<br>}<br>function sayHello() constant returns(string,string){<br>return(&quot;Hello&quot;, name);<br>}<br><br>function setName(string custom_name){ //To set a customized name<br>name = custom_name;<br>}<br>}</pre><p>In the case of Java, we write classes. Analogous to classes, in Solidity, which is also an object oriented programming language, we use the term “contracts”. So, contracts are basically classes. There’s a main class which uses other classes and inherits from various other classes. During the beginning of instantiation of a class in Solidity, we call a function called a constructor, and is given the same name as the contract. In our case, it’s the function called Hello. The constructor is called when you first deploy your smart contract into the blockchain, and is never called after that is done. The second function returns the words Hello and name Steve. The third function allows you to manually enter a name within with double quotes (e.g., “Elon Musk”), which will be assigned to the variable called name.</p><p>To deploy your smart contract, click on the tab called “Run” in the top right hand corner and hit “deploy”. On clicking sayHello function underneath in the “deployed contracts” section, your output should be as follows.</p><ul><li>0: string: Hello</li><li>1: string: Steve</li></ul><p>You can change the name under the setName contract, which will give you an output as below.</p><ul><li>0: string: Hello</li><li>1: string: Elon Musk</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6765c1cddd0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Blockchain]]></title>
            <link>https://pythonscript.medium.com/introduction-to-blockchain-fe6e57dca77e?source=rss-c978bd1f14c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe6e57dca77e</guid>
            <category><![CDATA[hash]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Python Script]]></dc:creator>
            <pubDate>Mon, 01 Nov 2021 04:59:03 GMT</pubDate>
            <atom:updated>2021-11-01T04:59:03.653Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3155v_R7C-p0vZND.jpg" /><figcaption><a href="https://creativecommons.org/licenses/by-nd/4.0/">License details</a> — Creator: Advantus Media Inc. and QuoteInspector.com | Credit: QuoteInspector.com</figcaption></figure><p>There are certain fundamental flaws in the way that financial transactions and services take place in the present world. If person X wanted to send some money to person Y, then person X usually does it through a centralised authority, i.e., his bank, which ensures that person Y receives the money from person X. In the process the bank charges person X a certain transaction fee for carrying out the transaction successfully, and updates the corresponding databases (i.e., a digital ledger), by deducting a certain amount from the buyer and adding it to the seller’s account.</p><p>Similarly, consider the several online shopping platforms that bring together the buyer and seller. The buyer needs to buy the product on the website from the seller for the transaction to take place. The shopping website again is acting like a centralized entity for the transaction to occur. However, do we really need these centralized entities or “middle-men” to carry out these transactions for us? What if there was a more efficient technology that eliminated all the middle-men from the equation? Welcome to the world of Blockchain, which does exactly this.</p><p>I’m sure you’ve heard of the word “Bitcoin”, a term which has become quite viral in recent times. Bitcoin is a digital cryptocurrency which doesn’t require a centralized entity like a bank for transactions to take place. This means that transactions can occur from person to person without any transaction fee.</p><p>Unlike conventional currency, it can be used in any country and we won’t need any prerequisites or have problems like the bank freezing your account. The cryptocurrency works fundamentally on the backbone of blockchain technology. Let’s dive deeper and understand how this works.</p><h3>Principle of working of Blockchain</h3><p>As the name suggests, the word “blockchain” means a chain of blocks that contain some information. This concept was suggested way back in 1991 to timestamp digital documents, so as to ensure that these time stamps can’t be tampered with. However, this went by unused until the Bitcoin revolution came along. When we talk about blockchain, we essentially focus on the following terminology —</p><p>A blockchain is a distributed ledger which is open to anyone. Once some data has been recorded inside a blockchain it becomes very difficult to change it.</p><p>A block will hold some data, the “hash” of a block and the “hash” of the previous block. The data stored depends on the type of blockchain. For example, in a Bitcoin blockchain, the data stored will be the transaction details such as the sender, receiver and the amount of coins transferred. The “hash” of a blockchain is analogous to the fingerprint of humans. It is unique to a block and gives identity to a block in the chain. It identifies a block and the content that it stores. You may be wondering how the hash of the block is determined. Once a block is created, it’s hash is automatically calculated based on its contents.</p><p>A hash function is a mathematical function which converts a given input message into an alphanumeric unique output. If the data inside the block is changed, the associated hash will also change. Therefore, hashes are very useful in detecting changes made to the block. Once the hash changes, the identity of the block changes. Since each block also stores the hash of the previous block, each block will point to the previous block. If data in a block is tampered with, and the hash of the block is changed, the successive block will have no other block to point to. As a result, the chain of blocks is broken and the transaction will not be carried out. In other words, it makes all the successive blocks invalid.</p><p>In this way, blockchain technology adds a layer of security against any form data manipulation from taking place. However, this is not enough to ensure complete security of data. With more and more powerful computer being built, it is possible to tamper with the data and recalculate all the hashes of the blocks to make the blockchain active once again. Computers are capable of calculating thousands of hashes per second. To counter this, blockchain has a concept called “Proof of Work”. It is a mechanism that slows down the creation of new blocks. The way we do this is by introducing a 32 bit (4 byte) number called a “nonce”.</p><p>The nonce of the block makes it more difficult to calculate the hash of a number because it prefixes a certain number of zeros to each alpha-numeric hash value of a block. The more the number of zeros that prefixes a hash, the higher the difficulty of the calculating a hash. The number of zeros is decided based on how long it takes to calculate the hash. In bitcoins, it requires approximately 10 minutes to calculate the required nonce and thereby the proof of work to add a new block to the chain. If number of zeros so chosen requires more than 10 minutes to calculate the proof of work, then the number of zeros is reduced and vice versa.</p><p>The process of creating new blocks is called “mining”, and with regard to bitcoin, creating new blocks will award the miner a certain number of bitcoins. Initially, 50 bitcoins were offered as reward for mining a new block. This number halves every 4 years. Currently, one can get 12.5 bitcoins for each new block created. So, if you tamper with one block, you need to re-calculate the proof of work of all the remaining blocks. The security features don’t end here. In addition to this, blockchain is completely distributed.</p><p>Blockchains use a “Peer-to-peer” network, which means there is no centralised authority that has dominant control. Each member of the network is called a node. Every time a member join this network, he gets a full copy of the blockchain. For example, if a node adds a new block, every node will get a copy of the block. If the block hasn’t been tampered with, the creator and all the nodes will get the same block identity. All nodes verify and agree with each other that the block hasn’t been corrupted and then add it to the chain. Any blocks that have been tampered with will be rejected by other nodes.</p><p>To summarize, to really tamper with the data, you will need to recalculate all the hashes of the blocks in the chain, recalculate the proof of work of all the blocks in the chain and finally take control of over 50% of the P2P network. This is nearly impossible to do with current computational ability. This is why Blockchain is so powerful in today’s world. The security against data theft is vital in an era which is dominated by massive amounts of data. Blockchain is now used in a variety of applications like digital cryptocurrency, voting systems, collecting taxes, hospital databases, etc. to name a few.</p><blockquote>Click <a href="https://youtu.be/_160oMzblY8">here</a> to watch a visual demonstration of the concepts explained above.</blockquote><p>To summarize, the major benefits of this technology are:</p><ul><li><strong><em>Saves time</em></strong> — The transaction time is reduced from days to near instantaneous due to peer to peer communication rather than through a centralised entity.</li><li><strong><em>Removes cost</em></strong> — Overhead and cost intermediaries are ruled out due to elimination of middle-men</li><li><strong><em>Reduces risk</em></strong> — Tampering , fraud and cyber crime risks are eliminated.</li><li><strong><em>Increases trust</em></strong> — The whole concept of a blockchain is built on mutual trust among all the its users and this is induced via shared processes and record keeping.</li></ul><p>As with any new technology, Blockchain also has its set of limitations.</p><ol><li><strong><em>Complexity</em></strong>: To achieve the high level of high security, Blockchain had to be made very complex by nature. It also involves an entirely new vocabulary which most people aren’t very familiar with. Thankfully, several online glossaries and indices makes this slightly easier to work with.</li><li><strong><em>Size of the Network</em></strong>: As mentioned earlier, one key aspect of good security in a blockchain system is its decentralized P2P network of nodes. To get good security, you need a large number of users. Therefore, if a blockchain is not large and robust enough, it becomes more difficult to extract its full benefit. In many applications, this factor is crucial in determining if blockchain is a suitable technology to be used or not.</li><li><strong><em>Energy consumption</em></strong>: The process of creating new blocks is an energy intensive process as it requires a lot of computational power. As a result, a new study showed that bitcoin mining consumed 2.6GW of power, almost just as much as Ireland consumes, and is estimated to increase to 7.7GW by the end of 2018. This is believed to reduce by 2020 when the number of bitcoins per new block will halve again. However, this is not certain because the value of one bitcoin could also increase to counteract this.</li><li><strong><em>Unavoidable security flaw</em></strong>:Earlier, I had mentioned that to manipulate data in a blockchain, changes have to be made to more than half of the nodes involved in the chain. In other words, if a lie is told by more than half the nodes in the network, the lie becomes the truth. This is called a ‘51% attack’ and was highlighted by Satoshi Nakamoto in the original whitepaper when he launched bitcoin. For this reason, bitcoin mining pools are monitored closely by the community, ensuring no one unknowingly gains such network influence.</li></ol><blockquote>These concepts are further elaborated in the original Bitcoin whitepaper. Click <a href="https://bitcoin.org/bitcoin.pdf">here</a> to view the whitepaper.</blockquote><h4>Certain common terminology regarding blockchain :-</h4><ol><li><strong>Ledger</strong>: The system for keeping records in an organisation. Eg: account books, file etc.</li><li><strong>Asset</strong>: Anything that can be owned or controlled to produce value. Eg: house, mortgage etc</li><li><strong>Transaction</strong>: Transfer of an asset onto or off the ledger. Eg: selling of the house.</li><li><strong>Contract</strong>: A set of fixed rules that all the participants involved in the transaction have to follow.</li><li><strong>Smart contract</strong>: A contract that is embedded on the blockchain using a coding language.</li></ol><blockquote><strong><em>Subscribe to email notification to get new article in your inbox everytime I publish new article</em></strong></blockquote><blockquote><strong><em>If Like this article please follow python script… By the way its free!</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe6e57dca77e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Tensorflow and Keras — Fashion MNIST database]]></title>
            <link>https://faun.pub/introduction-to-tensorflow-and-keras-fashion-mnist-database-6954c6593d58?source=rss-c978bd1f14c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/6954c6593d58</guid>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[keras]]></category>
            <dc:creator><![CDATA[Python Script]]></dc:creator>
            <pubDate>Fri, 08 Oct 2021 16:58:16 GMT</pubDate>
            <atom:updated>2021-10-11T12:39:21.335Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction to Tensorflow and Keras — Fashion MNIST database</h3><p>In this article, we will learn the following things —</p><ul><li>Build a neural network using Tensorflow and Keras</li><li>Train the neural network to see the difference between different types of fashion items</li><li>Test the accuracy of your neural network on test images.</li></ul><h3>Requirements</h3><p>Things that are required for smooth processes in this walkthrough —</p><ol><li>Spyder on Anaconda Python</li><li>Numpy</li><li>Tensorflow</li><li>Keras</li></ol><p>Before we start building our neural network, we will need to install Tensorflow and Keras on Anaconda.</p><ul><li>Make sure all instances of Anaconda are closed (including Anaconda Navigator, Spyder, and Jupyter).</li><li>Open Anaconda Prompt on your PC.</li><li>Type the following command in the command line:</li></ul><pre>conda install -c conda-forge tensorflow keras</pre><ul><li>When prompted for “yes” or “no” (y/N), type “y” and hit Enter.</li><li>Once it finishes installing, you can test if it has been installed properly. type python3 in your command line. You will be able to type Python code now. This will be indicated by the “&gt;&gt;&gt;” symbol on your command line.</li><li>Type import tensorflow as tf and hit Enter.</li><li>If you do not get any error, then tensorflow has been installed correctly.</li><li>Type from tensorflow import keras and hit Enter.</li><li>If you do not get any error, then keras has been installed correctly.</li></ul><h3>Neural Networks</h3><p>A neural network is a mathematical model to implement machine learning. It is an extremely effective optimization algorithm that is compatible with a large amount of data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/0*nuZlQXfjDnI5PrXT.png" /><figcaption><em>General Neural Network</em></figcaption></figure><h4>Neuron</h4><p>A neuron is a basic building block of a neural network. It is a simple computational block that takes inputs and gives proportional outputs. The output of the neuron is called its <em>excitation.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/0*wg_Fd7DYZE89vGXZ.png" /><figcaption><em>Neuron as computational block</em></figcaption></figure><h4>Multi-Layer Perceptron</h4><p>When many neurons are arranged as layers, and all neurons of one layer are connected to all neurons of another layer, you get the most popularly used form of a <em>neural network,</em> also called a <em>Multi-Layer Perceptron (MLP)</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*elbElPt8WRSpGgai.png" /><figcaption><em>Multi-Layer Perceptron</em></figcaption></figure><p>The additional layers of computations help in the following ways:</p><ul><li>Add non-linearity to a mathematical problem by combining neurons that perform only linear computations.</li><li>Extract features from the input, helping it to better learn the problem. The feature extraction is done by the middle layers, usually called <em>Hidden Layers.</em></li></ul><h4>Weights</h4><p>The most important part of any neural network is its <em>weight. </em>Weights can be thought of as the <em>knowledge storing element</em> of a neural network.</p><p>Weights tell you the strength of a connection between two neurons. If the weight between neuron A and neuron B is a large number, the connection is strong. It means that neuron B depends heavily on the output of neuron A. A small change in the output of neuron A can drastically change the output of neuron B.</p><p>Weights are of two types:</p><ul><li>Excitatory — neuron A pushes the output of neuron B to the positive side — also called positive weight.</li><li>Inhibitory — neuron A pushes the output of neuron B to the negative side — also called negative weight.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d3FZ4_QGuU7CC-yr.png" /><figcaption><em>Weights of connections in Neural Network</em></figcaption></figure><p>Whenever we say a neural network is <em>trained</em>, we mean that the weights of all connections in a network have been adjusted to give the best possible output.</p><h3>Training</h3><p>A neural network is a <em>supervised machine learning</em> algorithm. This means that we need to give the network a large number of example sets, having pairs of input and the corresponding target output.</p><p>The network initially starts off with random weights — meaning the network does not know anything. When we give it an example, called a <em>training sample,</em> it tries to calculate an output using the random weights it has. Obviously, on the first try, it will give a wrong output.</p><p>It will compare this output with the target output in that training sample and finds out how wrong its calculated output was. This is called the <em>error.</em> It uses this error to change its weights so that it will give better output in the next try, also called <em>iteration </em>or <em>epoch.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2cz6zxek9rqQTqoq.png" /><figcaption><em>Training of a Neural Network</em></figcaption></figure><p>It repeats this process for all training samples taken from a <em>training set.</em> Now the network is said to be trained. It will give a correct output for most of the training samples.</p><p>A good neural network should also be able to give correct output for examples that it has never seen before. This means the neural network has learnt a pattern and not particular training examples. Another way to say this is that the neural network has learnt the concept, it has not simply learnt all the answers by heart. This scenario can be tested by checking the output of the neural network on a separate set of examples called a <em>test set.</em> It gives a good measure of how much the neural network has learnt.</p><h3>Database</h3><p>We will be trying a Tensorflow example problem here. The <a href="https://www.tensorflow.org/tutorials/keras/classification">example</a> we are considering is the one on the Fashion MNIST database. This database contains 70,000 images of articles of clothing. The classes available are ‘T-shirt/top‘, ‘Trouser‘, ‘Pullover‘, ‘Dress‘, ‘Coat’, ‘Sandal‘, ‘Shirt‘, ‘Sneaker‘, ‘Bag‘, ‘Ankle boot‘.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*w_BR_l3Z7g2Fa4uX.png" /><figcaption><a href="https://github.com/zalandoresearch/fashion-mnist">Fashion-MNIST samples</a> (by Zalando, MIT License)</figcaption></figure><p>This database can be downloaded directly using a keras command. So we can begin directly.</p><p>We will be splitting the database into 60,000 training images and 10,000 test images.</p><h3>Code —</h3><pre># MIT License<br># Copyright (c) 2017 François Chollet    <br># Permission is hereby granted, free of charge, to any person <br># obtaining a copy of this software and associated documentation <br># files (the &quot;Software&quot;), to deal in the Software without <br># restriction, including without limitation the rights to use, <br># copy, modify, merge, publish, distribute, sublicense, and/or sell<br># copies of the Software, and to permit persons to whom the<br># Software is furnished to do so, subject to the following conditions: <br>#      <br># The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. <br>#      <br># THE SOFTWARE IS PROVIDED &quot;AS IS&quot;, WITHOUT WARRANTY OF ANY KIND,  <br># EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF <br># MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND <br># NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT <br># HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,<br># WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING    <br># FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR<br># OTHER DEALINGS IN THE SOFTWARE.<br>    <br>import tensorflow as tf    <br>from tensorflow import keras    <br>import numpy as np    <br>import matplotlib.pyplot as plt <br>       <br>fashion_mnist = keras.datasets.fashion_mnist</pre><pre>(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data() <br>   <br>class_names = [&#39;T-shirt/top&#39;, &#39;Trouser&#39;, &#39;Pullover&#39;, &#39;Dress&#39;, &#39;Coat&#39;, &#39;Sandal&#39;, &#39;Shirt&#39;, &#39;Sneaker&#39;, &#39;Bag&#39;, &#39;Ankle boot&#39;] </pre><pre>train_images = train_images / 255.0    <br>test_images = test_images / 255.0<br>        <br>model = keras.Sequential([keras.layers.Flatten(input_shape=(28, 28)),keras.layers.Dense(128, activation=tf.nn.relu),   keras.layers.Dense(10, activation=tf.nn.softmax)])</pre><pre>model.compile(optimizer=tf.train.AdamOptimizer(),    loss=&#39;sparse_categorical_crossentropy&#39;,metrics=[&#39;accuracy&#39;])        </pre><pre>print(&quot;\n\n[STATUS] TRAINING&quot;)<br>    <br>model.fit(train_images, train_labels, epochs=20)        </pre><pre>print(&quot;\n\n[STATUS] TESTING&quot;)    </pre><pre>test_loss, test_acc = model.evaluate(test_images, test_labels)    </pre><pre>print(&#39;Test accuracy:&#39;, test_acc)</pre><p>When you run the code, the neural network you built will be trained for 5 epochs. The trained network will then be tested on the 10,000 testing images and the testing accuracy will then be shown. The <a href="https://www.tensorflow.org/tutorials/keras/classification">original tutorial</a> also shows you how to plot your predictions for the images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/0*jMD2K5OPY9yuIHyG.png" /></figure><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=6954c6593d58" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/introduction-to-tensorflow-and-keras-fashion-mnist-database-6954c6593d58">Introduction to Tensorflow and Keras — Fashion MNIST database</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[Classification between Apple and Oranges— Machine Learning example with Images for beginners]]></title>
            <link>https://pythonscript.medium.com/classification-between-apple-and-oranges-machine-learning-example-with-images-for-beginners-487b3173f50?source=rss-c978bd1f14c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/487b3173f50</guid>
            <category><![CDATA[decision-tree]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[opencv]]></category>
            <dc:creator><![CDATA[Python Script]]></dc:creator>
            <pubDate>Sun, 03 Oct 2021 16:02:59 GMT</pubDate>
            <atom:updated>2021-12-22T05:08:16.313Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article we will learn the following things —</p><ul><li>Learn about texture and color features in an image</li><li>Learn about Decision Trees and train a decision tree on texture and color features.</li><li>Train a decision tree to differentiate between apples and oranges</li></ul><h3>Requirements</h3><p>Thnings which are required for smooth processes in this walkthrough —</p><ol><li><a href="https://drive.google.com/file/d/1WrCRsn46SckAL43GssZizqkQ_IbxCVgM/view?usp=sharing">Data set containing apple and orange image</a></li><li>Anaconda Python</li><li>OpenCV library</li><li>Sklearn library (it is built-in if you are using Anaconda)</li></ol><h4>Introduction</h4><p>A decision tree is a supervised machine learning algorithm which learns to classify data into two or more classes. Let’s take some images of apples and oranges and use a decision tree to classify them. First, we will have to extract a few features from the images using image processing. Then, these features will be used to train a decision tree that we build. Finally, we can test the working of the decision tree on images it has never seen before.</p><h4>About Database</h4><p>A supervised learning algorithm always needs labeled data. This means that we need to tell the decision tree which images are apples and which images are oranges. In order to do this, we separate our data into folders, and the folder name is taken as our label.</p><p>In Machine Learning, it is common practice to split the dataset into two (or sometimes more) parts. This is to combat a problem called ‘overfitting’. Overfitting occurs when an ML algorithm is trained extensively on a dataset without care for data which may have been ignored in the dataset.</p><p>For example, the images we are using aren’t the only possible images of oranges and apples. There are several species of these fruits, and each fruit is different. Overfitting would mean that the machine would claim that only the images it has learnt are correct and nothing else can be correct.</p><p>To combat this problem, the data is split into two parts: training data and testing data. The ML algorithm is trained on the training data. The testing data is then used to test the real-world accuracy of the ML algorithm, since it hasn’t been trained for the testing data. So the results obtained on the testing data can, ideally, be used as a measure of the real-world accuracy of the ML algorithm.</p><p>You can navigate to the “Baby Machine Data\ap-or-database\train” folder. Here you will find two folders — “apple” and “orange”. Each of these folders has been loaded with images downloaded from Google Images. You can explore these images and see the variety that they have.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MFFH3UpZ1MOScd7L.png" /><figcaption><em>Apple and Orange database for training</em></figcaption></figure><h3>About Decision Tree Algorithm</h3><p>Decision tree algorithm basically consists of a tree of nodes, where each node asks a question and sees if a feature fits a condition. Based on the answer to that question, it will decide what question to ask next. This process continues until it is able to separate the data into classes.</p><p>In our case, the questions that it will be asking at every node are “what is the dominant color in this image?” and “what is the texture of this image”. When we train, every node will learn what values determine if a fruit is an orange or an apple.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mFTALv4gbyYhBBTm.png" /><figcaption><em>Working of a Decision Tree</em></figcaption></figure><h3>Step 1 : Feature Extraction</h3><p>In order to train our decision tree, we have to extract the features from our training images. We have observation that color and texture are the most prominent features discriminating apples and oranges. So, let’s extract these features.</p><p>In first step, we’ll extract the texture feature. There is an algorithm known as the Haralick algorithm which is meant to extract numbers from an image which give us an idea about the texture of the image. It takes each pixel of the image and seeks out pixels in its neighborhood. It then calculates a number based on how different the surrounding pixels are from the pixel it is considering. It does this for all pixels and gives a set of numbers which summarise the texture features of the image as a whole. We will use these numbers as they are for our purpose.</p><p>In order to extract the Haralick features, we will be using a command from the mahotas library. We will need to first install this library:</p><pre>conda install -c conda-forge mahotas</pre><blockquote>Note : Make sure all instances of Anaconda are closed (including Anaconda Navigator, Spyder, and Jupyter) while installing the mahotas library.</blockquote><p><em>Once it finishes installing, you can test if it has installed properly. type python3 in your command line. You will be able to type python code now. This will be indicated by the “&gt;&gt;&gt;” symbol on your command line.And then type import mahotas as mt. If you do not get any error, then mahotas has been installed correctly.</em></p><p>We will also be extracting the most dominant color from the image. This will give us an idea if the image is largely red, or largely orange, which our decision tree can use to make its decisions. To do this, we will have to use OpenCV to analyze the pixels of the image. First, we will install OpenCV.</p><pre>conda install -c conda-forge opencv</pre><blockquote>Note : Make sure all instances of Anaconda are closed (including Anaconda Navigator, Spyder, and Jupyter) while installing the OpenCV library.</blockquote><p><em>Once it finishes installing, you can test if it has installed properly. type python3 in your command line. You will be able to type python code now. This will be indicated by the “&gt;&gt;&gt;” symbol on your command line.And then type import cv2. If you do not get any error, then OpenCV has been installed correctly.</em></p><ul><li>First, download <a href="https://thingqbator.s3.ap-south-1.amazonaws.com/tqb/2018/09/Baby-Machine-Data.zip">this data set</a> onto your PC. Unzip it to a folder.</li><li>Open Spyder. On the top right corner, there will be an icon of a folder. Click on it and navigate to the extracted database folder. Make sure you are inside the Data set folder. If you select any other folder, including the “ap-or-database” folder, the code will not work, since it is looking for a particular folder.</li><li>Copy the code below to your editor window and save the code. You will also find this code as “fruit-feature.py” in your downloaded folder.</li></ul><pre>import numpy as np<br>import cv2<br>from scipy.stats import itemfreq<br>import mahotas as mt</pre><pre>def extract_features(image):<br>   # calculate haralick texture features for 4 types of adjacency<br>   gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)<br>   textures = mt.features.haralick(gray)<br>   # take the mean of it and return it<br>   ht_mean  = textures.mean(axis=0)<br>   arr = np.float32(image)<br>   pixels = arr.reshape((-1, 3))<br>   n_colors = 3<br>   criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 200, .1)<br>   flags = cv2.KMEANS_RANDOM_CENTERS<br>   _, labels, centroids = cv2.kmeans(pixels, n_colors, None, criteria, 10, flags)<br>   palette = np.uint8(centroids)<br>   quantized = palette[labels.flatten()]<br>   quantized = quantized.reshape(image.shape)<br>   dominant_color = palette[np.argmax(itemfreq(labels)[:, -1])]<br>   feat = np.concatenate((ht_mean,dominant_color))<br>   return feat</pre><h3>Step 2 : Training the Decision Tree</h3><p>You can now start training the decision tree. You can do this by using built-in functions in sklearn which comes pre-installed in Anaconda.</p><ul><li>Copy the code below to your editor window and run the code. You will also find this code as “baby-machine.py” in your downloaded folder.</li></ul><pre>import cv2<br>import numpy as np<br>import os<br>import glob<br>from sklearn import tree<br>from fruit_feature import extract_features</pre><pre># load the training dataset<br>train_path  = &quot;ap-or-database/train&quot;<br>train_names = os.listdir(train_path)</pre><pre># empty list to hold feature vectors and train labels<br>train_features = []<br>train_labels   = []</pre><pre># loop over the training dataset<br>for train_name in train_names:<br>   cur_path = train_path + &quot;/&quot; + train_name<br>   cur_label = train_name<br>   i = 1</pre><pre>for file in glob.glob(cur_path + &quot;/*.jpg&quot;):<br>   print (&quot;Processing Image - {} in {}&quot;.format(i, cur_label))<br>   # read the training image<br>   image = cv2.imread(file)<br>   # extract texture and color from the image<br>   features = extract_features(image)<br>   # append the feature vector and label<br>   train_features.append(features)<br>   train_labels.append(cur_label)<br>   # show loop update<br>   i += 1</pre><pre># create the classifier<br>clf=tree.DecisionTreeClassifier()</pre><pre># train the classifier<br>print (&quot;Training model..&quot;)<br>clf.fit(train_features, train_labels)</pre><pre># loop over the test images<br>test_path = (&quot;ap-or-database/test&quot;)<br>for file in glob.glob(test_path + &quot;/*.jpg&quot;):<br>   # read the input image<br>   image = cv2.imread(file)<br>   # extract texture and color from the image<br>   features = extract_features(image)<br>   # evaluate the model and predict label<br>   prediction = clf.predict(features.reshape(1, -1))[0]<br>   # show the label<br>   cv2.putText(image, prediction, (20,30), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (235,188,0), 3)<br>   print (&quot;Prediction - {}&quot;.format(prediction))<br>   # display the output image<br>   cv2.imshow(&quot;Test_Image&quot;, image)<br>   cv2.waitKey(0)<br>cv2.destroyAllWindows()</pre><p>You will now train your decision tree. The code will then take images from the “test” folder and show you what the decision tree is predicting for the image. You can add more images to this folder to see what output you get. You can also add more images to the training data to improve results.</p><h4>Output</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/0*4o8D6aWTc1hKJQwi.png" /><figcaption>Predicted Image</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/0*ttjfihzR91gupBDl.png" /><figcaption>Predicted Image</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=487b3173f50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Find the face in a picture — OpenCV example for beginners]]></title>
            <link>https://pythonscript.medium.com/find-the-face-in-a-picture-opencv-example-for-beginners-bb76f454a89c?source=rss-c978bd1f14c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb76f454a89c</guid>
            <category><![CDATA[facedetection]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[beginner-coding]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Python Script]]></dc:creator>
            <pubDate>Fri, 01 Oct 2021 07:21:11 GMT</pubDate>
            <atom:updated>2021-10-01T07:21:11.736Z</atom:updated>
            <content:encoded><![CDATA[<h3>Find the face in a picture — OpenCV example for beginners</h3><p>To begin, we need to download the Haar cascade files from the following github link — <a href="https://github.com/Itseez/opencv/blob/master/data/haarcascades/haarcascade_frontalface_default.xml">https://github.com/Itseez/opencv/blob/master/data/haarcascades/haarcascade_frontalface_default.xml</a></p><blockquote>NOTE — Make sure that the downloaded XML file (haarcascade_frontalface_default.xml) and the input image is present in the directory from which the code is running.</blockquote><h4>About haarcascade_frontalface_default.xml file</h4><p>This is basically a XML (extensible markup language) file containing generic information about features of a face. The following code uses this information to draw a rectangle around the detected face.</p><p>Let’s use this image to check the working of our code. <a href="https://media.istockphoto.com/photos/group-portrait-of-a-creative-business-team-standing-outdoors-three-picture-id1146473249?k=20&amp;m=1146473249&amp;s=612x612&amp;w=0&amp;h=9Ki3nKs4Su-_YRMc6__iuWnHLhpp58ULOsz4l9PT6tw=">Download it here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/0*jeIEaO6FbiXTdKpj" /><figcaption><em>Trial Image</em></figcaption></figure><h3>THE CODE</h3><p>First we will import all the required modules</p><pre>import cv2<br>import numpy as np<br>import math</pre><p>In next step, the image is extracted from its location and stored in ‘img’ variable</p><pre>img=cv2.imread(&quot;pic1.jpg&quot;)</pre><p>and then the cascade file is also loaded into ‘face_cascade’ variable</p><pre>face_cascade = cv2.CascadeClassifier(&#39;haarcascade_frontalface_default.xml&#39;)</pre><p>Now come very important two lines of code-</p><pre>gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)<br>faces = face_cascade.detectMultiScale(gray, 1.3, 5)</pre><p>The first line converts the image from one color space to another i.e from BGR to grayscale in this case.</p><p>The second line uses the CascadeClassifier::detectMultiScale() function which detects objects of different sizes in the input image and the detected objects are returned as a list of rectangles. More information on this module can be found <a href="https://docs.opencv.org/2.4/modules/objdetect/doc/cascade_classification.html#cascadeclassifier-detectmultiscale">here</a> .</p><p>In the next 4 lines, we’re finding faces, their sizes, drawing rectangles, and noting the region of interest(ROI).</p><pre>for (x,y,w,h) in faces:<br>   cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)<br>   roi_gray = gray[y:y+h, x:x+w]<br>   roi_color = img[y:y+h, x:x+w]</pre><p>In above code, (x,y) are the starting indices of the rectangle and (w,h) are the width and height that when added to (x,y) form the rectangle. The second line draws rectangles on the input image.</p><p>Following code is used to display the image with the detected faces -</p><pre>cv2.imshow(&quot;Image&quot;,img)<br>k = cv2.waitKey(30) &amp; 0xff<br>if k == 27:<br>   break</pre><p>The first line displays the image in a new window named “Image”.</p><p>As seen, the last 8 lines of code are written inside an infinite loop (while 1:).</p><pre>k = cv2.waitKey(30) &amp; 0xff<br>if k == 27:<br>   break</pre><p>Above code displays the image until you press the “Esc” key (breaks the infinite loop).</p><h4>Final Code</h4><pre>import cv2<br>import numpy as np<br>import math<br>img=cv2.imread(&quot;name_of_image.extension&quot;)<br>face_cascade = cv2.CascadeClassifier(&#39;haarcascade_frontalface_default.xml&#39;)<br>gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)<br>faces = face_cascade.detectMultiScale(gray, 1.3, 5)<br>while 1:<br>   for (x,y,w,h) in faces:<br>      cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)<br>      roi_gray = gray[y:y+h, x:x+w]<br>      roi_color = img[y:y+h, x:x+w]<br>   cv2.imshow(&quot;Image&quot;,img)<br>   k = cv2.waitKey(30) &amp; 0xff<br>   if k == 27:<br>      break<br>cv2.destroyAllWindows()</pre><h4>Output of the program</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*WhKqll2q_kR40UU8pzb3RA.jpeg" /><figcaption>Output for Trail Image</figcaption></figure><p>As we can clearly see from the above output, it does not give perfect result.It left the guy in dark blue shirt and triange on guy which at back is not perfect.</p><p>So lets try our code with one more image.</p><p><a href="https://thingqbator.s3.ap-south-1.amazonaws.com/tqb/2018/08/pic.jpg">Download this image</a> -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OumTCCYzu1kOBoI1.jpg" /><figcaption>Second Trail Image</figcaption></figure><p>Now run the code with this image. Make sure XML file, image and code are in same working directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FsP7dBrSk8y3P8FccHTfmg.png" /><figcaption>Output for second trail Image</figcaption></figure><p>After running the program we find that it again left the girl at right bottom of the picture.</p><p>In my personal opinian it is because of XML file we downloaded from github in the beginning. For more accurate results we have to modify that XML file so that it can capture face more accurately.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p>Please give your valuable feedback at pythoncript007@gmail.com</p><p>Please subcribe to Python Script — For more high quality article about Data Science/Machine Learning</p><p>New article will be published on Friday, Sunday and Tuesday.</p><blockquote>Thank You</blockquote><blockquote>Python Script</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb76f454a89c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Play with Images — Open CV example for beginners]]></title>
            <link>https://pythonscript.medium.com/play-with-images-open-cv-example-for-beginners-f4283a245b7b?source=rss-c978bd1f14c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4283a245b7b</guid>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[opencv-python]]></category>
            <category><![CDATA[beginner]]></category>
            <dc:creator><![CDATA[Python Script]]></dc:creator>
            <pubDate>Tue, 14 Sep 2021 15:30:50 GMT</pubDate>
            <atom:updated>2022-01-08T05:58:42.342Z</atom:updated>
            <content:encoded><![CDATA[<h3>Play with Images — Open CV example for beginners</h3><p>In this article, we will understand how to perform certain operations to change the pixel properties of the images that we have. We will look at turning a color image into various forms like gray scale and binary using different techniques. We also understand how to visualize these changes effectively and all this will be done using a very powerful image processing tool called OpenCV.</p><p>Pip command to install the library —</p><pre>pip install opencv-python</pre><p>let’s see how to read, display and save an image that we wish to perform some processing on. The following steps will involve the following three functions: <strong><em>cv2.imread()</em></strong>, <strong><em>cv2.imshow()</em></strong>, and <strong><em>cv2.imwrite()</em></strong>. You will also learn how to display images using Matplotlib. So, let’s get started.</p><p><a href="https://drive.google.com/file/d/1ncaH8CUfbMQTB-21IGs_M74qyP_G-dqh/view?usp=sharing">Download</a> this picture of a cat. We will see how to perform various operations on this image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*W5Z0Rt8JWts2Inqb.jpg" /><figcaption>Picture of a cat</figcaption></figure><p>Open any python IDE you like and make a new file called ‘Playwithimages.py’, where .py represents the python extension. And write the following code to open the image with openCV</p><pre>import numpy as np<br>import cv2<br>img = cv2.imread(&#39;cat.jpg&#39;,1)<br>cv2.imshow(&#39;image&#39;,img)<br>cv2.waitKey(0)<br>cv2.destroyAllWindows()</pre><p>Let’s have a look at what this code means. The first line of code is importing a library which specifically deals with scientific computing, and is an essential component for any machine learning application that we are trying to build.</p><p>We abbreviate numpy as np for our convenience and python will recognize np as numpy from this point on wards. The same can be done with other libraries. The second line of code imports the OpenCV library for use in image processing. The third line creates a variable called img and using the function cv2.imread() we read the image of the cat that we saved.</p><blockquote>Note: For this to work the image you’re trying to read must be in the same directory as that of the python script.</blockquote><p>The function cv2.imread() has two arguments. The first refers to the image which needs to be read and the second refers to how the image needs to be read. The second argument can take values of 0,1,and -1. 0 will load the image in grayscale, -1 will load the image unchanged and 1 will load the image in color, and any transparency in the image will be neglected. By default, 1 is chosen if the second argument is not specified.</p><p>Once the image is read, the fourth line will show/display the image using the cv2.imshow() function. The function also has two arguments. The first argument is the title of the window where we want the image to be displayed. If the window doesn’t exist, a window of that name will be created. The second is the name of the variable which contains the image, which in this case is img which we created in the previous line.</p><p>The next two lines of code are intended to display the image continuously until any key is pressed on the keyboard. Once a key is pressed the image displayed will automatically be destroyed as described by the last line of the code.</p><p>cv2.imshow() command must always be put with cv2.waitkey() command. cv2.waitKey() is a keyboard binding function having it’s only argument as the time in milliseconds. The function waits for the specified number of milliseconds. If 0 is passed, it waits indefinitely until a key is stroked. It can also be set to detect specific key strokes, such as the key ‘q’ for quitting. Please note that this function also processes many other GUI events, so it is mandatory to be used for actually displaying an image.</p><p>cv2.destroyAllWindows(), as the name suggests will destroy all the windows we created. If you want to destroy any specific window, pass the exact window name as the argument into this function.</p><pre>import numpy as np<br>import cv2<br>img = cv2.imread(&#39;cat.jpg&#39;)<br>cv2.imshow(&#39;image&#39;,img)<br>i = cv2.waitKey(0) <br>if i == 27: <br>    cv2.destroyAllWindows()<br>elif i == ord(&#39;s&#39;):<br>    cv2.imwrite(&#39;cat_saved.jpg&#39;,img)<br>cv2.destroyAllWindows()</pre><p>The above code will read, display and save the file.</p><p>The cv2.imwrite() function has two arguments. The first specifies the name of the file to be saved and in the desired format. In this case, we save the file as ‘cat_saved.jpg’, and the variable which contains the picture we want to save is our second argument. This completes the first part of our objective.</p><p>Alternatively, we can also use the matplotlib library to display the images. Matplotlib is a plotting library that gives us publication quality plots of our data. Here’s how we do it:</p><pre>import numpy as np<br>import cv2<br>from matplotlib import pyplot as plt<br>img = cv2.imread(&#39;cat.jpg&#39;,0)<br>plt.imshow(img, cmap = &#39;gray&#39;, interpolation = &#39;bicubic&#39;)<br>plt.xticks([]), plt.yticks([])  # to hide tick values on X and Y axis <br>plt.show()</pre><p>The first two lines are the same as the previous code. The third line imports the pyplot package from matplotlib and the fourth reads the image in grayscale.. The following link explains the meaning of the various arguments line 5: <a href="https://matplotlib.org/api/_as_gen/matplotlib.pyplot.imshow.html">https://matplotlib.org/api/_as_gen/matplotlib.pyplot.imshow.html</a></p><h3>Grayscale and Binary Images</h3><p>It is possible to convert gray scale image to a binary image using a technique called image thresholding. The reason we do this is to further-simplify visual data for analysis.</p><p>You may be wondering why gray-scale may not be a sufficient simplification. The reason is that gray scale still has at least 255 values. Image thresholding can fundamentally simplify the image by converting everything to white or black, based on a threshold value. We have a pixel values ranging from 0 to 255.</p><p>Let’s assume that we want the threshold to be 127, then everything that was 127 and under would be converted to 0 (or black)and everything above 127 would be converted to 255 (or white).</p><p>If you don’t convert to grayscale before performing image thresholding, you will get threshold pictures, but there will be color, which doesn’t really help in most cases. This is the reason it is recommended to convert all images to gray scale before performing any binary thresholding operations.</p><p>The OpenCV function used for converting a color image to grayscale is called cv2.cvtColor()</p><pre>gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)</pre><p>The first argument is the source image, which should be a color image. The second argument specifies that the image should be converted to the Gray color space. There are other color spaces like HSV.</p><blockquote>Note: The color is converted from BGR to Gray. This is because OpenCV reads color images in the BGR format and not in the RGB format. If you need the RGB image for any reason, you can use this same command with the second argument as cv2.COLOR_BGR2RGB.</blockquote><p>The OpenCV function used for converting a grayscale image to binary is called <a href="https://docs.opencv.org/3.4/d7/d1b/group__imgproc__misc.html#gae8a4a146d1ca78c626a53577199e9c57">cv.threshold().</a></p><pre>th1, threshold = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)</pre><p>The first argument is the source image, which should be a gray scale image as explained earlier. The second argument is the threshold value which is used to classify the pixel values, usually in the range between 125–150.</p><p>In some cases, we will need to adapt to a specific picture, say a book, which has many curvatures that may cause shadows at the curvatures. In this case, with simple binary thresholding, the region at the curvature will be completely turned to black, making the entire exercise useless. For this reason, we can use adaptive thresholding.</p><pre>th2=cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,2)</pre><p>Here, the first argument img is the variable name of the image which needs to be thresholded. The second argument 255 is the value which needs to be applied if a pixel value is greater than the calculated threshold. The third argument cv2.ADAPTIVE_THRESH_MEAN_C indicates that the threshold is calculated using the mean of values around a pixel. cv2.THRESH_BINARY specifies the type of thresholding to be performed <em>after</em> a threshold is calculated. The third argument tells the block size around a pixel which is taken to calculate the mean. In this case, a <em>11×11 grid</em> around every pixel is taken to calculate the mean. The last argument specifies an overall negative correction which needs to be applied after calculating the mean. In this case, the threshold for every pixel will be <em>[mean(11×11 grid around pixel) — 2 ]</em>.</p><h3>Shrinking and Zooming</h3><p>Let’s now take a look a scaling function offered by OpenCV. We can use this function to perform tasks such as zooming and shrinking images, which becomes vital in many image processing applications. Scaling is just resizing of the image. OpenCV comes with a function <a href="https://docs.opencv.org/3.2.0/d5/df1/group__imgproc__hal__functions.html#ga2fe39d2201b12e1b961ca56b2aff9ff2">cv2.resize()</a> for this purpose. Let’s first shrink an image. Then we will zoom it back using the same scale so that we can see how the image was affected by the shrinking.</p><pre>import cv2<br>import numpy as np<br>img = cv2.imread(&#39;cat.jpg&#39;)<br>res = cv2.resize(img,None,fx=0.1, fy=0.1, interpolation = cv2.INTER_AREA)<br>res = cv2.resize(img,None,fx=10, fy=10, interpolation = cv2.INTER_AREA)</pre><p>Try experimenting by changing the scaling factors and compare the different outputs that you get! You can observe that there is an argument in the cv2.resize() function called interpolation. When the size of an image changes, we need to calculate the pixel values of the new image from the old one. This process is called interpolation and there are several ways of doing this; INTER_AREA is one such argument that helps us achieve this.</p><p>Using cv2.INTER_AREA gives a pixelated image when zooming. To get a better image when zoomed, try more complex interpolation methods like cv2.INTER_CUBIC.</p><h3>Gaussian Blur</h3><p>Just like in one-dimensional signals, images can also be filtered using various low-pass filters(LPF) and high pass filters(HPF). LPF helps in removing noise, blurring the image etc. HPF helps define the edges in any given image.</p><p>Gaussian blurring is a kind of low-pass filter that uses a “Gaussian Kernel”. A “Gaussian Kernel” is a square array of pixels where the pixel values will correspond to a set of values of a Gaussian curve which means that the image will be blurred uniformly.</p><p>The function used for this purpose is:</p><pre>cv2.GaussianBlur(image, (kernel_width,kernel_height), standard_deviation)</pre><p>In this we specify the image on which Gaussian Blur has to be applied, the width and height of the kernel which should be positive and odd, and the standard deviation in the X and Y directions as the functions’ arguments. To explore the mathematics further, click <a href="https://computergraphics.stackexchange.com/questions/39/how-is-gaussian-blur-implemented">here</a>.</p><h3>Converting BGR to HSV</h3><p>Computer vision and graphics make use of several color spaces. For example, some commonly used ones include RGB(Red, Green, Blue) and CMYK(Cyan, Magenta, Yellow, Key), which uses various combinations of primary colors to generate a spectrum of other colors.</p><p>Often, we come across scenarios where we are interested in specific colored objects in an image. This can be carried out more efficiently in alternate color spaces like HSV.</p><p>HSV is slightly different in that it is defined in a way that is similar to how humans perceive color. HSV stands for: hue, saturation, and value. This color space describes colors (H — hue or tint) in terms of their shade (S — saturation or amount of grey) and their corresponding brightness value(V- value).</p><p>The generalized function used for color conversion is</p><pre>cv2.cvtColor(input_image, flag)</pre><p>where flag determines the type of conversion. For BGR \ HSV, we use the flag cv2.COLOR_BGR2HSV.</p><p>Similarly, BGR \ Grey conversion can also done using this method where we use the flag cv2.COLOR_BGR2GRAY. To find the flags for conversions to other color spaces follow <a href="https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_colorspaces/py_colorspaces.html">this</a> link.</p><h3>Putting it all together!</h3><p>Now that we’ve understood the various processes that can be carried out on an image, it’s time to put it all together in a single code and compare the outputs to better appreciate these functions. Each of these functions have a specific purpose for various machine learning applications. We decide which technique to use based on the image available and the kind of information we wish to extract from it.</p><p>To stack the image, we use np.concatenate() function from the numpy library. This helps because the openCV images are always stored as numpy arrays, so we combine images by simply concatenating the arrays.</p><p>The following command will stack 3 images side by side</p><pre>temp1 = np.concatenate((img1,img2,img3), axis=1)</pre><p>The following command will stack one image on top of another:</p><pre>img_final = np.concatenate((temp1,temp2), axis=0)</pre><p>The first argument for this command is a list of images put within parantheses and seperated by commas — (img1,img2,…etc.). The second argument is the axis to concatenate — axis 0 signifies vertical concatenation, which means one image will be on top of the other, and axis 1 signifies horizontal concatenation, which means the images will be side-by-side.</p><h3>Final Code</h3><p>Now let’s perform all 6 manipulations we learnt, and stack all images in a 2×3 grid.</p><blockquote>Note:</blockquote><blockquote>The grid is designed to expect a BGR format of color(since most of our manipulated images are BGR). Certain images like the Gray image, the shrunk image and the HSV image are not in BGR format after manipulation. Hence they have special considerations.</blockquote><blockquote>The Gray image consists of just one array of pixels, but the BGR grid expects three arrays(B array, G array and R array). So we use the command cv2.merge((img_gray,img_gray,img_gray)) to have a gray image with three arrays. This does not affect the manipulation we have made (converting from BGR to GRAY).</blockquote><blockquote>When we shrink an image, the width and height reduces. However, the np.concatenate() command expects all arrays to be of the same size. So we will zoom the image by the same amount that we have shrunk it (shrink to 0.1 and then zoom to 10). This will show you a pixelated image.</blockquote><blockquote>All pixels in the HSV image will be of the HSV color space. Since we are displaying it on a BGR grid( since most other images are BGR), the color of the image will look extremely unnatural.</blockquote><pre>import numpy as np</pre><pre>import cv2</pre><pre>img1 = cv2.imread(&#39;cat.jpg&#39;)</pre><pre>h,w,bpp = np.shape(img1)</pre><pre>img_gray = cv2.cvtColor(img1,cv2.COLOR_BGR2GRAY)</pre><pre>img2=cv2.merge((img_gray,img_gray,img_gray))</pre><pre>th1, img3 = cv2.threshold(img2, 127, 255, cv2.THRESH_BINARY)</pre><pre>img4 = cv2.resize(img1,None,fx=0.1, fy=0.1, interpolation = cv2.INTER_AREA)</pre><pre>img4 = cv2.resize(img4,None,fx=10, fy=10, interpolation = cv2.INTER_AREA)</pre><pre>img5 = cv2.GaussianBlur(img1,(9,9),10)</pre><pre>img6 = cv2.cvtColor(img1,cv2.COLOR_BGR2HSV)</pre><pre>temp1 = np.concatenate((img1,img2,img3), axis=1)</pre><pre>temp2 = np.concatenate((img4,img5,img6), axis=1)</pre><pre>img_final = np.concatenate((temp1,temp2), axis=0)</pre><pre>cv2.imshow(&quot;result&quot;,img_final)</pre><pre>cv2.waitKey(0)</pre><pre>cv2.destroyAllWindows()</pre><h3>There you go!</h3><p>Your final output after putting all these images together will look something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/0*GGRKHOYqnPUabfO0.png" /><figcaption>Desired output of the above code</figcaption></figure><p>The images in order are — Original image, Grayscale image, Thresholded image, Shrunk and Zoomed image, Gaussian Blurred image, and image in HSV color space.</p><p>With this, you are equipped with all the necessary skills to manipulate an image and extract all the useful information necessary for your machine learning application to function effectively.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4283a245b7b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>