<?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 Afnan Amin Ali on Medium]]></title>
        <description><![CDATA[Stories by Afnan Amin Ali on Medium]]></description>
        <link>https://medium.com/@afnanamin?source=rss-a149ba728698------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*aDfp0QOBAk2kNAGw.</url>
            <title>Stories by Afnan Amin Ali on Medium</title>
            <link>https://medium.com/@afnanamin?source=rss-a149ba728698------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 21:07:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@afnanamin/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[Why we need Kubernetes?]]></title>
            <link>https://medium.com/@afnanamin/why-we-need-kubernetes-6d7b007a2650?source=rss-a149ba728698------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d7b007a2650</guid>
            <dc:creator><![CDATA[Afnan Amin Ali]]></dc:creator>
            <pubDate>Thu, 20 Jan 2022 05:04:56 GMT</pubDate>
            <atom:updated>2022-01-20T05:04:56.613Z</atom:updated>
            <content:encoded><![CDATA[<h3>Docker Container Problems:</h3><p>There are some problems in docker containers which can only be solve by Kubernetes. Few of them are listed below.</p><ul><li>How would all of these containers be coordinated and scheduled?</li><li>How do you seamlessly upgrade an application without any interruption of service?</li><li>How do you monitor the health of an application, know when something goes wrong and seamlessly restart it?</li><li>Two docker containers may have same ip address so how would they communicate?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*tlPbHQMcwljN4YAXr57nDw.png" /></figure><p>In the above picture container on node1 can not communicate with the container on node2 due to same IP address. If a container must be replaced it will require a new IP address and any hard coded IP address will break.</p><h3>How does Kubernetes solve these issues :</h3><p>To make this happen that all all containers can communicate with all other containers without NAT and all nodes can communicate with all other containers without NAT let’s build a simple Kubernetes server. Below is the diagram what we are going to build.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*keCL-9kebsvsM7OSK5Er2A.png" /></figure><p>If you are using linux below is the link attached of specific commands you have to run to install Kubernetes on your machine.</p><p><a href="https://docs.google.com/document/d/1pifVgvymktLt5W4jpcgDkKw5ABrOw2-IEumw-KPvUZU/edit?usp=sharing">https://docs.google.com/document/d/1pifVgvymktLt5W4jpcgDkKw5ABrOw2-IEumw-KPvUZU/edit?usp=sharing</a></p><p>When you done with the installation things shown in below picture are running on your master node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*7riPmIlkEookvw_u7GY1qg.png" /></figure><h3><strong>Etcd:</strong></h3><p>Consistent and highly-available key value store used as Kubernetes’ backing store for all cluster data.</p><blockquote><em>As all cluster data is stored in etcd, you should always have a backup plan for it. You can easily back up your etcd data using the </em>etcdctl snapshot save<em> command. In case you are running Kubernetes on AWS, you can also back up etcd by taking a snapshot of the EBS volume.</em></blockquote><p><strong>ApiServer:</strong> The API Server is the main management point of the entire cluster. In short, it processes REST operations, validates them, and updates the corresponding objects in etcd. The API Server serves up the <a href="https://kubernetes.io/docs/concepts/overview/kubernetes-api/">Kubernetes API</a> and is intended to be a relatively simple server, with most business logic implemented in separate components or in plugins.</p><blockquote><em>The API Server is the only Kubernetes component that connects to </em><strong><em>etcd</em></strong><em>; all the other components must go through the API Server to work with the cluster state.</em></blockquote><h3><strong>Scheduler:</strong></h3><p>The Scheduler watches for unscheduled pods and binds them to nodes via the <em>/binding </em>pod sub resource API, according to the availability of the requested resources, quality of service requirements, affinity and anti-affinity specifications, and other constraints. Once the pod has a node assigned, the regular behavior of the Kubelet is triggered and the pod and its containers are created</p><h3><strong>ControllerManager:</strong></h3><p>The Kubernetes Controller Manager is a daemon that embeds the <a href="https://github.com/kubernetes/kubernetes/blob/7c75723867e9e431da323b8cc410bab928cada17/cmd/kube-controller-manager/app/controllermanager.go#L330">core control loops</a> (also known as “controllers”) shipped with Kubernetes. Basically, a controller watches the state of the cluster through the API Server watch feature and, when it gets notified, it makes the necessary changes attempting to move the current state towards the desired state. Some examples of controllers that ship with Kubernetes include the Replication Controller, Endpoints Controller, and Namespace Controller.</p><p>Controller Manager also performs lifecycle functions such as namespace creation and lifecycle, event garbage collection, terminated-pod garbage collection, cascading-deletion garbage collection, node garbage collection, etc.</p><h3>Things shown in below picture are running on your slave nodes.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*j9BmtUmOIRWR23hOmB33CA.png" /></figure><h3>kube-proxy:</h3><p>kube-proxy is a network proxy that runs on each <a href="https://kubernetes.io/docs/concepts/architecture/nodes/">node</a> in your cluster, implementing part of the Kubernetes <a href="https://kubernetes.io/docs/concepts/services-networking/service/">Service</a> concept. <a href="https://kubernetes.io/docs/reference/command-line-tools-reference/kube-proxy/">kube-proxy</a> maintains network rules on nodes. These network rules allow network communication to your Pods from network sessions inside or outside of your cluster. kube-proxy uses the operating system packet filtering layer if there is one and it’s available. Otherwise, kube-proxy forwards the traffic itself.</p><h3>kubelet:</h3><p>An agent that runs on each <a href="https://kubernetes.io/docs/concepts/architecture/nodes/">node</a> in the cluster. It makes sure that <a href="https://kubernetes.io/docs/concepts/containers/">containers</a> are running in a <a href="https://kubernetes.io/docs/concepts/workloads/pods/">Pod</a>. The kubelet takes a set of PodSpecs that are provided through various mechanisms and ensures that the containers described in those PodSpecs are running and healthy. The kubelet doesn’t manage containers which were not created by Kubernetes.</p><h3>Container runtime:</h3><p>The container runtime is the software that is responsible for running containers. Kubernetes supports several container runtimes: <a href="https://docs.docker.com/engine/">Docker</a>, <a href="https://containerd.io/docs/">containerd</a>, <a href="https://cri-o.io/#what-is-cri-o">CRI-O</a>, and any implementation of the <a href="https://github.com/kubernetes/community/blob/master/contributors/devel/sig-node/container-runtime-interface.md">Kubernetes CRI (Container Runtime Interface)</a>.</p><p>Through all these functionalities kubernetes manages to resolve the issue of same ip problem.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d7b007a2650" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Airflow]]></title>
            <link>https://medium.com/@afnanamin/introduction-to-airflow-54a7a4e34606?source=rss-a149ba728698------2</link>
            <guid isPermaLink="false">https://medium.com/p/54a7a4e34606</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[airflow-2]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[airflow]]></category>
            <dc:creator><![CDATA[Afnan Amin Ali]]></dc:creator>
            <pubDate>Tue, 30 Nov 2021 05:34:56 GMT</pubDate>
            <atom:updated>2021-11-30T05:42:54.773Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://airflow.apache.org/docs/stable/">Apache Airflow</a> is a workflow engine that will easily schedule and run your complex data pipelines. It will make sure that each task of your data pipeline will get executed in the correct order and each task gets the required resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*wmR2GrPiyGYAZiY9ssAh2Q.png" /></figure><p>Most of us have to deal with different workflows like collecting data from multiple databases, preprocessing it, upload it, and report it. Consequently, it would be great if our daily tasks just automatically trigger on defined time, and all the processes get executed in order. Apache Airflow is one such tool that can be very helpful for you. Whether you are Data Scientist, Data Engineer, or Software Engineer you will definitely find this tool useful.</p><p>In this article, we will discuss Apache Airflow, how to install it and we will create a sample workflow and code it in Python.</p><h3>Let’s start with the basic terms:</h3><p><strong>Workflow:</strong> It can be your simple calculation, creating infrastructure, perform some query in the database, bash command, python script, MySQL queries, Hive queries, etc.Workflow is divided into one or more than one task which relates to each other and forms a <strong>DAG </strong>(Directed Acyclic Graph)</p><p><strong>DAG: </strong>It<strong> </strong>is a series of tasks that you want to run as part of your workflow.A DAG is written in Python and saved as a .py file. The <strong>DAG_ID</strong> is used extensively by the tool to orchestrate the running of the DAG’s.</p><p>We specificy when a DAG should run automatically via an execution_date. A DAG is run to a specified schedule (defined by a CRON expression) this could be daily, weekly, every minute, or pretty much any other time interval.</p><p>An operator encapsulates the operation to be performed in each task in a DAG. Airflow has a wide range of built-in operators that can perform specific tasks some of which are platform-specific. Additionally, it is possible to create your own custom operators.</p><p><strong>What are the scheduled jobs?</strong></p><p>Suppose your workflow must be run every Sunday, you can schedule it in such a way that it will only be trigger on Sundays. How cool is this?<br>In simple terms, you can automate your workflow. The best part of automation is you can avoid future human errors.<br>Your DAG can be easily monitored, controlled, and triggered.</p><p><strong>What if your workflow gets fail? What if it got completed successfully? What if it took more than the expected time to complete?</strong></p><p>Well, keeping all such things in mind, apache-airflow has given such features like If your workflow gets fail, you can set it as to send an Email alert, slack notification to the required person/team.<br>You can also set it to send an email when the DAG ran successfully.</p><p>What if your task got successfully run, but took more than expected time? (In real case scenario this is a problem) — For this, you can set your SLA. Suppose your SLA time is 600 seconds. But your task took 900 seconds. Isn’t it something wrong? If this happens, it triggers the required team.</p><p><strong>Metadata Database</strong>: Airflow stores the status of all the tasks in a database and do all read/write operations of a workflow from here.</p><h3>Running Airflow in Docker</h3><p>This quick-start guide will allow you to quickly start Airflow with <a href="https://airflow.apache.org/docs/apache-airflow/stable/executor/celery.html">CeleryExecutor</a> in Docker. This is the fastest way to start Airflow.</p><p><a href="https://github.com/soumilshah1995/Learn-Apache-Airflow-in-easy-way-/tree/main/project">Learn-Apache-Airflow-in-easy-way-/project at main · soumilshah1995/Learn-Apache-Airflow-in-easy-way-</a></p><p>Download this repo and goto project directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eNikqXWZ74UHekQfb6BkPw.png" /></figure><p>Run the above command which is shown in terminal.This will automatically install all the dependencies required in docker-compose.yml file.</p><p>In dag folder you can create any dag file which can be view in the UI like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mmqI0Y682lOFs8IQ2uCByA.png" /></figure><h3>Let’s create a basic DAG:</h3><pre>try:<br><br>    from datetime import timedelta<br>    from airflow import DAG<br>    from airflow.operators.python_operator import PythonOperator<br>    from datetime import datetime<br>    import pandas as pd<br><br>    print(&quot;All Dag modules are ok ......&quot;)<br>except Exception as e:<br>    print(&quot;Error  {} &quot;.format(e))<br><br><br>def first_function_execute(**context):<br>    print(&quot;first_function_execute   &quot;)<br>    context[&#39;ti&#39;].xcom_push(key=&#39;mykey&#39;,    value=&quot;first_function_execute says Hello &quot;)<br><br><br>def second_function_execute(**context):<br>    instance = context.get(&quot;ti&quot;).xcom_pull(key=&quot;mykey&quot;)<br>    data = [{&quot;name&quot;:&quot;Soumil&quot;,&quot;title&quot;:&quot;Full Stack Software Engineer&quot;}, { &quot;name&quot;:&quot;Nitin&quot;,&quot;title&quot;:&quot;Full Stack Software Engineer&quot;},]<br>    df = pd.DataFrame(data=data)<br>    print(&#39;@&#39;*66)<br>    print(df.head())<br>    print(&#39;@&#39;*66)<br><br>    print(&quot;I am in second_function_execute got value :{} from Function 1  &quot;.format(instance))<br><br><br>with DAG(<br>        dag_id=&quot;first_dag&quot;,<br>        schedule_interval=&quot;@daily&quot;,<br>        default_args={<br>            &quot;owner&quot;: &quot;airflow&quot;,<br>            &quot;retries&quot;: 1,<br>            &quot;retry_delay&quot;: timedelta(minutes=5),<br>            &quot;start_date&quot;: datetime(2021, 1, 1),<br>        },<br>        catchup=False) as f:<br><br>    first_function_execute = PythonOperator(<br>        task_id=&quot;first_function_execute&quot;,<br>        python_callable=first_function_execute,<br>        provide_context=True,<br>        op_kwargs={&quot;name&quot;:&quot;Soumil Shah&quot;}<br>    )<br><br>    second_function_execute = PythonOperator(<br>        task_id=&quot;second_function_execute&quot;,<br>        python_callable=second_function_execute,<br>        provide_context=True,<br>    )<br><br>first_function_execute &gt;&gt; second_function_execute</pre><p>Let us understand this code line by line.</p><pre>from datetime import timedelta<br>from airflow import DAG<br>from airflow.operators.python_operator import PythonOperator<br>from datetime import datetime<br>import pandas as pd</pre><p>These are the import statements for the facility which we are using in our DAG. Since we are using python_operator we need to import PythonOperator from the airflow library.</p><pre>default_args={<br>    &quot;owner&quot;: &quot;airflow&quot;,<br>    &quot;retries&quot;: 1,<br>    &quot;retry_delay&quot;: timedelta(minutes=5),<br>    &quot;start_date&quot;: datetime(2021, 1, 1),<br>},</pre><p>These are the default argument which we can set for each task by setting the argument to each task’s constructor. We can define a dictionary of default parameters that we can use when creating tasks.</p><p><strong>Start_date</strong> for example yesterday means start as soon as it loaded into the server. We can set it at any time.</p><p><strong>Email_on_failure</strong> as False, if it is true it will send an email to the specified person/team if any particular task gets fail.</p><p><strong>Retries</strong> as 1 mean the number of retries after the task get fails.</p><p><strong>Retry_delay</strong> is set as 5 minutes means, after any specific task gets fail, it should wait exactly 5 minutes to start a retry.</p><p><strong>Email_on_retry</strong> as False, if it is true, then after a task gets fail, after every retry it will send email to the specified person/team.</p><pre>first_function_execute = PythonOperator(<br>    task_id=&quot;first_function_execute&quot;,<br>    python_callable=first_function_execute,<br>    provide_context=True,<br>    op_kwargs={&quot;name&quot;:&quot;Afnan Amin Ali&quot;}<br>)<br><br>second_function_execute = PythonOperator(<br>    task_id=&quot;second_function_execute&quot;,<br>    python_callable=second_function_execute,<br>    provide_context=True,<br>)</pre><p>In DAG everything works as an operator.<br>Example t1=SomeOperator(arguments)</p><p>We are using PythonOperator in this example.</p><p>first_function_execute is a value that is calling the Python<strong>Operator</strong> class and sends all the required arguments to it.Every task has a <strong>task_id</strong> which uniquely defines a task, and other required arguments based on what operator you are using.</p><pre>first_function_execute &gt;&gt; second_function_execute</pre><p>This means that first_function_execute will run before second_function_execute.</p><p>Airflow does have a feature for operator cross-communication called <a href="https://airflow.apache.org/docs/1.10.1/concepts.html?highlight=xcom">XCom</a>.</p><p>Airflow provides many operators some of them includes:</p><ul><li>BashOperator create ,delete directories etc.</li><li>PythonOperator — Use to call any python function in DAG</li><li>EmailOperator — Sends email</li><li>SimpleHttpOperator — Sends an HTTP request</li><li>MySqlOperator, SqliteOperator, PostgresOperator, OracleOperator, JdbcOperator — executes SQL queries.</li></ul><h3>Are you curious to know how two operators communicate with each other?</h3><p>Apache-airflow provides a feature called XCom</p><h3>XCom (Cross — Communication):</h3><p>Communication among two operators. If any operator returns some value, it gets store in xcom, airflow provides a mechanism to pull xcom value using xcom_pull() and use it in some other operation and also to push value using xcom-push().</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54a7a4e34606" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Federated Learning-A great way to train data without an outbreaking security breach]]></title>
            <link>https://medium.datadriveninvestor.com/federated-learning-a-great-way-to-train-data-without-an-outbreaking-security-breach-93e319a3d075?source=rss-a149ba728698------2</link>
            <guid isPermaLink="false">https://medium.com/p/93e319a3d075</guid>
            <category><![CDATA[federated-learning]]></category>
            <category><![CDATA[machine-learning-ai]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Afnan Amin Ali]]></dc:creator>
            <pubDate>Tue, 19 May 2020 18:01:37 GMT</pubDate>
            <atom:updated>2020-05-20T01:54:36.104Z</atom:updated>
            <content:encoded><![CDATA[<p>This blog is all about what I learn from the Facebook udacity nanodegree program for the secure and private use of AI. It starts with the basic learning of PyTorch and ends with encrypted deep learning.All resporities for this course are available at <a href="https://github.com/udacity/deep-learning-v2-pytorch"><strong>https://github.com/udacity/deep-learning-v2-pytorch</strong></a>. It consists of a bunch of tutorial notebooks for various deep learning topics. In most cases, the notebooks lead you through implementing models such as convolutional networks, recurrent networks, and GANs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eH9khOfGmUFliO940ocmsQ.png" /></figure><p>Data privacy has been a very important concern for both governments and companies these days. In one end we keep father and father to enhance the quality of the model and on the other end, we are much concerned about the privacy of that data. This leads to too much difficulty for researchers like us to solve their problems due to the limitation of data. This means that many issues can not be solved using ml techniques due to privacy. But thanks to federated learning which comes to rescue us in this difficult situation. I am super excited with you to solve these problems using federated learning, Let&#39;s get started from differential privacy.</p><blockquote><strong>The basic definition of differential privacy is that you can not be affected by allowing your data to any study or analysis</strong></blockquote><p>To understand this definition better you might hear the <strong>movie recommendation competition of Netflix</strong> in which they anonymize the data in such a way with unique integers that we even didn’t know about the user who did the rating. To ensure someone privacy the basic observation is if we remove someone from the data and the data accuracy does not get affected that means that person wasn’t leaking any statistical information into the output of the query.</p><blockquote><strong>Now the big question is can we construct a query such that when we remove someone from the database query doesn’t change?</strong></blockquote><p>yes, it can be possible, let me show you how?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84729bf9098a136423d503f32544c012/href">https://medium.com/media/84729bf9098a136423d503f32544c012/href</a></iframe><p>I hope you enjoy seeing this code which at the same time creates and removes the entry from the database but it can be attacked easily by intruders.</p><p>So here the differential privacy comes to rescue us. Consider a scenario that instead of asking each person about the crime he has done a sociologist will ask to flip the coin if it turns head you are saying honestly that you commit a crime but if the coin turns tail you may be saying it wrong so in this way we have gain privacy but lost accuracy in it. the main goal of differential privacy is that we minimize the amount of noise and maximize the amount of accuracy.</p><p>Further implementation of differential privacy is you can find on my next article .#staty tune</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93e319a3d075" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/federated-learning-a-great-way-to-train-data-without-an-outbreaking-security-breach-93e319a3d075">Federated Learning-A great way to train data without an outbreaking security breach</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GAN (Generative Adversarial Network)]]></title>
            <link>https://medium.com/swlh/gan-generative-adversarial-network-3706ebfef77e?source=rss-a149ba728698------2</link>
            <guid isPermaLink="false">https://medium.com/p/3706ebfef77e</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[generative-adversarial]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[Afnan Amin Ali]]></dc:creator>
            <pubDate>Sun, 17 May 2020 11:44:06 GMT</pubDate>
            <atom:updated>2020-05-19T20:26:39.934Z</atom:updated>
            <content:encoded><![CDATA[<p>The idea behind GANs is that you have two networks, a generator G and a discriminator D, competing against each other. The generator makes “fake” data to pass to the discriminator. The discriminator also sees real training data and predicts if the data it’s received is real or fake.</p><blockquote>The generator is trained to fool the discriminator, it wants to output data that looks <em>as close as possible</em> to real, training data.</blockquote><blockquote>The discriminator is a classifier that is trained to figure out which data is real and which is fake.</blockquote><p>What ends up happening is that the generator learns to make data that is indistinguishable from real data to the discriminator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6zMZBE6xtgGUVqkaLTBaJQ.png" /></figure><p>The general structure of a GAN is shown in the diagram above, using MNIST images as data. The latent sample is a random vector that the generator uses to construct its fake images. This is often called a <strong>latent vector</strong> and that vector space is called <strong>latent space</strong>. As the generator trains, it figures out how to map latent vectors to recognizable images that can fool the discriminator.</p><p>If you’re interested in generating only new images, you can throw out the discriminator after training. In this notebook, I’ll show you how to define and train these adversarial networks in PyTorch and generate new images!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/572497538aecfd29f9749e77b195f4b2/href">https://medium.com/media/572497538aecfd29f9749e77b195f4b2/href</a></iframe><h4><strong>visualize the data:</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f1ecc2ef46aef7689a868c53a2c216a/href">https://medium.com/media/3f1ecc2ef46aef7689a868c53a2c216a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*LpJ1SxNVk7HgLME1E7QthQ.png" /></figure><h3>Define the Model</h3><p>A GAN is comprised of two adversarial networks, a discriminator and a generator.</p><h3>Discriminator</h3><p>The discriminator network is going to be a pretty typical linear classifier. To make this network a universal function approximator, we’ll need at least one hidden layer, and these hidden layers should have one key attribute:</p><blockquote><em>All hidden layers will have a </em><a href="https://pytorch.org/docs/stable/nn.html#torch.nn.LeakyReLU"><em>Leaky ReLu</em></a><em> activation function applied to their outputs.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*MmlyI67gbhCa9M_6f1ricQ.png" /></figure><blockquote>Leaky ReLu</blockquote><p>We should use a leaky ReLU to allow gradients to flow backward through the layer unimpeded. A leaky ReLU is like a normal ReLU, except that there is a small non-zero output for negative input values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*AHBuJYKN23Bg62iT652bQw.png" /></figure><h4>Sigmoid Output</h4><p>We’ll also take the approach of using a more numerically stable loss function on the outputs. Recall that we want the discriminator to output a value 0–1 indicating whether an image is <em>real or fake</em>.</p><blockquote><em>We will ultimately use </em><a href="https://pytorch.org/docs/stable/nn.html#bcewithlogitsloss"><em>BCEWithLogitsLoss</em></a><em>, which combines a </em><em>sigmoid activation function </em><strong><em>and</em></strong><em> and binary cross entropy loss in one function.</em></blockquote><p>So, our final output layer should not have any activation function applied to it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6fb1f4bfad83fa8c0760e1e42af220ea/href">https://medium.com/media/6fb1f4bfad83fa8c0760e1e42af220ea/href</a></iframe><h3>Generator</h3><p>The generator network will be almost exactly the same as the discriminator network, except that we’re applying a <a href="https://pytorch.org/docs/stable/nn.html#tanh">tanh activation function</a> to our output layer.</p><h4>tanh Output</h4><p>The generator has been found to perform the best with tanh for the generator output, which scales the output to be between -1 and 1, instead of 0 and 1.</p><p>Recall that we also want these outputs to be comparable to the <em>real</em> input pixel values, which are read in as normalized values between 0 and 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*CPl7-ynnSwBMaiPdCTQeCA.png" /></figure><blockquote><em>So, we’ll also have to </em><strong><em>scale our real input images to have pixel values between -1 and 1</em></strong><em> when we train the discriminator.</em></blockquote><blockquote>I’ll do this in the training loop, later on.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/413b5db555c2ebe8e11d1f8015143e19/href">https://medium.com/media/413b5db555c2ebe8e11d1f8015143e19/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28f84082a66e4d2013dbbd66ee33c153/href">https://medium.com/media/28f84082a66e4d2013dbbd66ee33c153/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*K-VrZKA6NMQXy3AWZuGQiw.png" /></figure><h3>Discriminator and Generator Losses</h3><p>Now we need to calculate the losses.</p><h3>Discriminator Losses</h3><p>For the discriminator, the total loss is the sum of the losses for real and fake images, d_loss = d_real_loss + d_fake_loss.</p><p>Remember that we want the discriminator to output 1 for real images and 0 for fake images, so we need to set up the losses to reflect that.</p><p>The losses will by binary cross entropy loss with logits, which we can get with <a href="https://pytorch.org/docs/stable/nn.html#bcewithlogitsloss">BCEWithLogitsLoss</a>. This combines a sigmoid activation function <strong>and</strong> and binary cross entropy loss in one function.</p><p>For the real images, we want D(real_images) = 1. That is, we want the discriminator to classify the the real images with a label = 1, indicating that these are real. To help the discriminator generalize better, the labels are <strong>reduced a bit from 1.0 to 0.9</strong>. For this, we&#39;ll use the parameter smooth; if True, then we should smooth our labels. In PyTorch, this looks like labels = torch.ones(size) * 0.9</p><p>The discriminator loss for the fake data is similar. We want D(fake_images) = 0, where the fake images are the <em>generator output</em>, fake_images = G(z).</p><h3>Generator Loss</h3><p>The generator loss will look similar only with flipped labels. The generator’s goal is to get D(fake_images) = 1. In this case, the labels are <strong>flipped</strong> to represent that the generator is trying to fool the discriminator into thinking that the images it generates (fakes) are real!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6755dd5ad7f9a7d9401147a0758b18b2/href">https://medium.com/media/6755dd5ad7f9a7d9401147a0758b18b2/href</a></iframe><h3>Training</h3><p>Training will involve alternating between training the discriminator and the generator. We’ll use our functions real_loss and fake_loss to help us calculate the discriminator losses in all of the following cases.</p><h3>Discriminator training</h3><ol><li>Compute the discriminator loss on real, training images</li><li>Generate fake images</li><li>Compute the discriminator loss on fake, generated images</li><li>Add up the real and fake loss</li><li>Perform backpropagation + an optimization step to update the discriminator’s weights</li></ol><h3>Generator training</h3><ol><li>Generate fake images</li><li>Compute the discriminator loss on fake images, using <strong>flipped</strong> labels!</li><li>Perform backpropagation + an optimization step to update the generator’s weights</li></ol><h4>Saving Samples</h4><p>As we train, we’ll also print out some loss statistics and save some generated “fake” samples.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/598f17f2b617d641d797543cb8b4907a/href">https://medium.com/media/598f17f2b617d641d797543cb8b4907a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*LWxuasyU1qAzOqyrEH5QnA.png" /></figure><h3>Generator samples from training</h3><p>Here we can view samples of images from the generator. First we’ll look at the images we saved during training.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d64a6a1be2f0c13ea913e806cc117a73/href">https://medium.com/media/d64a6a1be2f0c13ea913e806cc117a73/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*LsG2avT8GaUt75Ju6D3FSQ.png" /></figure><p>These are samples from the final training epoch. You can see the generator is able to reproduce numbers like 1, 7, 3, 2. Since this is just a sample, it isn’t representative of the full range of images this generator can make.</p><p>hope you find this article productive to get your hands dirty with gan.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3706ebfef77e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/gan-generative-adversarial-network-3706ebfef77e">GAN (Generative Adversarial Network)</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reinforcement Learning Using Quantum Computing]]></title>
            <link>https://medium.datadriveninvestor.com/reinforcement-learning-using-quantum-computing-361a977c641d?source=rss-a149ba728698------2</link>
            <guid isPermaLink="false">https://medium.com/p/361a977c641d</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[quantum-physics]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[open-gym]]></category>
            <category><![CDATA[quantum-computing]]></category>
            <dc:creator><![CDATA[Afnan Amin Ali]]></dc:creator>
            <pubDate>Fri, 20 Mar 2020 19:27:38 GMT</pubDate>
            <atom:updated>2020-03-23T08:21:03.955Z</atom:updated>
            <content:encoded><![CDATA[<p>To understand this article you must know the basics of reinforcement learning like the concept of agent q-value and target value. A general question that can be come in your mind is that why we use quantum for training our reinforcement learning model, well you can get the answer of this by reading the whole article so let’s start your’s machine learning journey in the quantum world.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*lQqD2CbJYkaGALBZ.png" /></figure><p>The first and foremost quality of quantum circuits is that it requires fewer parameters than a conventional neural network, making them promising for modeling complex environments. For a target network, I take the architecture of a Frozen Lake.</p><p><a href="https://gym.openai.com/envs/FrozenLake-v0/">https://gym.openai.com/envs/FrozenLake-v0/</a></p><p>The targeted circuit is updated per 20 steps. For experience replay, the replay memory is set for the length of 80 to adapt to the testing environment. The process of optimization needs to calculate gradients of expectation values of quantum measurements, which can be conducted by the same circuit architecture and slightly different parameters</p><p>In the Frozen-Lake environment, there are totally 16 states. Thus, it requires 4 qubits to represent all states.I hope you all understand the meaning of the qubit.</p><p>Action and Reward in the environment are given below:</p><p>Action: there are four actions in the action space. The outputs from the quantum circuit are 0, 1, 2, 3 and they correspond to the action LEFT, DOWN, RIGHT, UP</p><p>Reward: The rewards in this environment are +1.0 for successfully achieve the goal, −0.2 for failing the task, which is stepping into the HOLE. Moreover, to encourage the agent to take the shortest path, there is also a −0.01 reward for each step taken.</p><p><a href="https://www.datadriveninvestor.com/2019/02/08/machine-learning-in-finance/">Machine Learning in Finance | Data Driven Investor</a></p><blockquote><strong>Quantum advantage on memory consumption:</strong> In the neural network-based deep Q-learning, the number of parameters will be 2 × N2 + 2 × N for frozen lake envoirment. However, with quantum circuits, the number of circuit parameters reduced to N × (3 × 2 + 1).</blockquote><p>The optimization I choose is to be RMSprop with learning rate = 0.01, alpha = 0.4 and eps = 1, which is used widely in deep reinforcement learning. The batch-size for the experience replay is 5. The epsilon-greedy strategy used in Frozen-Lake is the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*ejRA4LbTQ7LumntiupLu1w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*8YUmgtpKuw4dd4OT06kvqg.png" /></figure><p>The reward is converged on 300 episodes so no need to train more , happy coding.</p><p>All the code for this article is on my github: <a href="https://github.com/AFNANAMIN/AI_Freelancing/blob/master/Reinforcement_Learning_with_Quantum_Computing.ipynb">https://github.com/AFNANAMIN/AI_Freelancing/blob/master/Reinforcement_Learning_with_Quantum_Computing.ipynb</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fb2a0d6%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fupscri.be%2Fb2a0d6%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href">https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=361a977c641d" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/reinforcement-learning-using-quantum-computing-361a977c641d">Reinforcement Learning Using Quantum Computing</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[flask telegram bot hosting on Heroku]]></title>
            <link>https://medium.com/@afnanamin/flask-telegram-bot-hosting-on-heroku-ae0419f9c28f?source=rss-a149ba728698------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae0419f9c28f</guid>
            <category><![CDATA[telegram-bot]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-flask]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[heroku]]></category>
            <dc:creator><![CDATA[Afnan Amin Ali]]></dc:creator>
            <pubDate>Mon, 24 Feb 2020 15:34:17 GMT</pubDate>
            <atom:updated>2020-02-24T15:34:17.192Z</atom:updated>
            <content:encoded><![CDATA[<p>firstly you have to create a flask telegram app</p><p>To host on Heroku you have to create Procfile and requirements.txt file and afterwards type following commands</p><ol><li>git init</li><li>Heroku git: remote -a {heroku-project-name}#heroku-project-name includes the app name you have created on Heroku</li><li>git add.<br> git commit -m “first commit”<br> git push Heroku master</li><li>create a database (Not necessary)</li></ol><pre>heroku addons:create heroku-postgresql:hobby-dev --app appname</pre><p>5. Add a table to remote database</p><pre>heroku run python<br>&gt;&gt;&gt; from app import db<br>&gt;&gt;&gt; db.create_all()<br>&gt;&gt;&gt;exit()</pre><p>6.open the app</p><pre>heroku open</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae0419f9c28f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SUMMARY OF TENSORFLOW WITHOUT A PHD (II)]]></title>
            <link>https://medium.com/@afnanamin/summary-of-tensorflow-without-a-phd-ii-2cd47cbcc43e?source=rss-a149ba728698------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cd47cbcc43e</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Afnan Amin Ali]]></dc:creator>
            <pubDate>Sun, 09 Sep 2018 04:20:10 GMT</pubDate>
            <atom:updated>2018-09-09T04:20:10.463Z</atom:updated>
            <content:encoded><![CDATA[<p>this is the continuaton of <a href="https://medium.com/@afnanamin/summary-of-tensorflow-without-a-phd-a88397a895da">part(I)</a> of my article.Handwritten digits in the MNIST dataset are 28x28 pixel greyscale images. The simplest approach for classifying them is to use the 28x28=784 pixels as inputs for a 1-layer neural network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/0*KS6mzo--Rmc5K5gC.png" /></figure><p>Each “neuron” in a neural network does a weighted sum of all of its inputs, adds a constant called the “bias” and then feeds the result through some non-linear activation function.</p><p>Here we design a 1-layer neural network with 10 output neurons since we want to classify digits into 10 classes (0 to 9).</p><p>For a classification problem, an activation function that works well is softmax. Applying softmax on a vector is done by taking the exponential of each element and then normalising the vector (using any norm, for example the ordinary euclidean length of the vector).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/0*C6o0MrLBjiaaGqQW.png" /></figure><p>Why is “softmax” called softmax ? The exponential is a steeply increasing function. It will increase differences between the elements of the vector. It also quickly produces large values. Then, as you normalise the vector, the largest element, which dominates the norm, will be normalised to a value close to 1 while all the other elements will end up divided by a large value and normalised to something close to 0. The resulting vector clearly shows which was its largest element, the “max”, but retains the original relative order of its values, hence the “soft”.</p><p>We will now summarise the behaviour of this single layer of neurons into a simple formula using a matrix multiply. Let us do so directly for a “mini-batch” of 100 images as the input, producing 100 predictions (10-element vectors) as the output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Jl-b76kaMOpXDFs-.png" /></figure><p>Using the first column of weights in the weights matrix W, we compute the weighted sum of all the pixels of the first image. This sum corresponds to the first neuron. Using the second column of weights, we do the same for the second neuron and so on until the 10th neuron. We can then repeat the operation for the remaining 99 images. If we call X the matrix containing our 100 images, all the weighted sums for our 10 neurons, computed on 100 images are simply X.W (matrix multiply).</p><p>Each neuron must now add its bias (a constant). Since we have 10 neurons, we have 10 bias constants. We will call this vector of 10 values b. It must be added to each line of the previously computed matrix. Using a bit of magic called “broadcasting” we will write this with a simple plus sign.</p><p>“Broadcasting add” means “if you are adding two matrices but you cannot because their dimensions are not compatible, try to replicate the small one as much as needed to make it work.”</p><p>We finally apply the softmax activation function and obtain the formula describing a 1-layer neural network, applied to 100 images:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uxUVPsxDnm1P6Udk.png" /></figure><p>By the way, what is a “tensor”?<br>A “tensor” is like a matrix but with an arbitrary number of dimensions. A 1-dimensional tensor is a vector. A 2-dimensions tensor is a matrix. And then you can have tensors with 3, 4, 5 or more dimensions.</p><p>Now that our neural network produces predictions from input images, we need to measure how good they are, i.e. the distance between what the network tells us and what we know to be the truth. Remember that we have true labels for all the images in this dataset.</p><p>Any distance would work, the ordinary euclidian distance is fine but for classification problems one distance, called the “cross-entropy” is more efficient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hm6eaPayuJpVCfEt.png" /></figure><p>“One-hot” encoding means that you represent the label “6” by using a vector of 10 values, all zeros but the 6th value which is 1. It is handy here because the format is very similar to how our neural network outputs ts predictions, also as a vector of 10 values.</p><p>Training” the neural network actually means using training images and labels to adjust weights and biases so as to minimise the cross-entropy loss function. Here is how it works.</p><p>The cross-entropy is a function of weights, biases, pixels of the training image and its known label.</p><p>If we compute the partial derivatives of the cross-entropy relatively to all the weights and all the biases we obtain a “gradient”, computed for a given image, label and present value of weights and biases. Remember that we have 7850 weights and biases so computing the gradient sounds like a lot of work. Fortunately, TensorFlow will do it for us.</p><p>The mathematical property of a gradient is that it points “up”. Since we want to go where the cross-entropy is low, we go in the opposite direction. We update weights and biases by a fraction of the gradient and do the same thing again using the next batch of training images. Hopefully, this gets us to the bottom of the pit where the cross-entropy is minimal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/0*cZ0jrOe_9EBhy_W2.png" /></figure><p>In this picture, cross-entropy is represented as a function of 2 weights. In reality, there are many more. The gradient descent algorithm follows the path of steepest descent into a local minimum. The training images are changed at each iteration too so that we converge towards a local minimum that works for all images.</p><p>“Learning rate”: you cannot update your weights and biases by the whole length of the gradient at each iteration. It would be like trying to get to the bottom of a valley while wearing seven-league boots. You would be jumping from one side of the valley to the other. To get to the bottom, you need to do smaller steps, i.e. use only a fraction of the gradient, typically in the 1/1000th region. We call this fraction the “learning rate”.</p><p>To sum it up, here is how the training loop looks like:</p><p>Training digits and labels =&gt; loss function =&gt; gradient (partial derivatives) =&gt; steepest descent =&gt; update weights and biases =&gt; repeat with next mini-batch of training images and labels</p><p>Why work with “mini-batches” of 100 images and labels ?</p><p>You can definitely compute your gradient on just one example image and update the weights and biases immediately (it’s called “stochastic gradient descent” in scientific literature). Doing so on 100 examples gives a gradient that better represents the constraints imposed by different example images and is therefore likely to converge towards the solution faster. The size of the mini-batch is an adjustable parameter though. There is another, more technical reason: working with batches also means working with larger matrices and these are usually easier to optimise on GPUs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cd47cbcc43e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SUMMARY OF TENSORFLOW WITHOUT A PHD]]></title>
            <link>https://medium.com/@afnanamin/summary-of-tensorflow-without-a-phd-a88397a895da?source=rss-a149ba728698------2</link>
            <guid isPermaLink="false">https://medium.com/p/a88397a895da</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Afnan Amin Ali]]></dc:creator>
            <pubDate>Sun, 09 Sep 2018 04:00:55 GMT</pubDate>
            <atom:updated>2018-09-09T04:00:55.164Z</atom:updated>
            <content:encoded><![CDATA[<p>Its a worth reading<a href="https://codelabs.developers.google.com/codelabs/cloud-tensorflow-mnist/#0"> tutorial </a>.i recommend to read this tutorial before preceding further.this blog is all about what i learn from this tutorial.</p><p>This codelab uses the <a href="http://yann.lecun.com/exdb/mnist/">MNIST</a> dataset, a collection of 60,000 labeled digits that has kept generations of PhDs busy for almost two decades. You will solve the problem with less than 100 lines of Python / TensorFlow code.</p><p>First clone the GitHub repository for better understanding:</p><pre>$ git clone <a href="https://github.com/GoogleCloudPlatform/tensorflow-without-a-phd.git">https://github.com/GoogleCloudPlatform/tensorflow-without-a-phd.git</a><br>$ cd tensorflow-without-a-phd/tensorflow-mnist-tutorial</pre><p>When you launch the initial python script, you should see a real-time visualisation of the training process:</p><pre>$ python3 mnist_1.0_softmax.py</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2QYI6bqOIfhuO18K.png" /></figure><h3>Train a neural network:</h3><p>There are 50,000 training digits in this dataset. We feed 100 of them into the training loop at each iteration so the system will have seen all the training digits once after 500 iterations. We call this an “epoch”.</p><p>To test the quality of the recognition in real-world conditions, we must use digits that the system has NOT seen during training. Otherwise, it could learn all the training digits by heart and still fail at recognising an “8” that I just wrote. The MNIST dataset contains 10,000 test digits. Here you see about 1000 of them with all the mis-recognised ones sorted at the top (on a red background). The scale on the left gives you a rough idea of the accuracy of the classifier (% of correctly recognised test digits)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*jYGqccU8VDy99mY-.png" /></figure><p>To drive the training, we will define a loss function, i.e. a value representing how badly the system recognises the digits and try to minimise it. The choice of a loss function (here, “cross-entropy”) is explained later. What you see here is that the loss goes down on both the training and the test data as the training progresses: that is good. It means the neural network is learning. The X-axis represents iterations through the learning loop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*9NPiDOFYZVTKRyZ8.png" /></figure><p>The accuracy is simply the % of correctly recognised digits. This is computed both on the training and the test set. You will see it go up if the training goes well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*zq1Nq5SzxyvHa1jr.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*aSH6YOsn1MBMehp-.png" /></figure><p>The final two graphs represent the spread of all the values taken by the internal variables, i.e. weights and biases as the training progresses. Here you see for example that biases started at 0 initially and ended up taking values spread roughly evenly between -1.5 and 1.5. These graphs can be useful if the system does not converge well. If you see weights and biases spreading into the 100s or 1000s, you might have a problem.</p><p>The bands in the graphs are percentiles. There are 7 bands so each band is where 100/7=14% of all the values are.</p><p>Keyboard shortcuts for the visualisation GUI:<br>1 ......... display 1st graph only<br>2 ......... display 2nd graph only<br>3 ......... display 3rd graph only<br>4 ......... display 4th graph only<br>5 ......... display 5th graph only<br>6 ......... display 6th graph only<br>7 ......... display graphs 1 and 2<br>8 ......... display graphs 4 and 5<br>9 ......... display graphs 3 and 6<br>ESC or 0 .. back to displaying all graphs<br>SPACE ..... pause/resume<br>O ......... box zoom mode (then use mouse)<br>H ......... reset all zooms<br>Ctrl-S .... save current image</p><p>What are “weights” and “biases” ? How is the “cross-entropy” computed ? How exactly does the training algorithm work ? Jump to the next section to find out.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a88397a895da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[k-means clustering]]></title>
            <link>https://medium.com/@afnanamin/k-means-clustering-adb69a1a61b2?source=rss-a149ba728698------2</link>
            <guid isPermaLink="false">https://medium.com/p/adb69a1a61b2</guid>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Afnan Amin Ali]]></dc:creator>
            <pubDate>Sun, 17 Jun 2018 07:53:24 GMT</pubDate>
            <atom:updated>2018-06-17T07:53:24.040Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>objective<br>perform k-means clustering to detect network intrusion attempt<br>this is a five step process.we start with unlabel data which have no clusters.This algo creates cluster of that unlabel data.Suppose you want to calcualte error and gradient descent but you do not have so what you can do in this case? that’s why unsupervised learning comes into play .<br>let’s get start.k is the number of clusters that we want.then we place k centroids at random location.<br>How does it work ?<br>This algorithm is an iterative process. I will explain it step-by-step with the help of images.</blockquote><p>Consider a set of data as below ( You can consider it as t-shirt problem). We need to cluster this data into two groups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/0*wR_tddUJhmrjBdOH.jpg" /></figure><p><strong>Step : 1</strong> — Algorithm randomly chooses two centroids c1 and c2,(sometimes, any two data are taken as the centroids).</p><p><strong>Step : 2</strong> — It calculates the distance from each point to both centroids. If a test data is more closer to c1 then that data is labelled with ‘0’. If it is closer to c2, then labelled as ‘1’ (If more centroids are there, labelled as ‘2’,‘3’ etc).In our case, we will color all ‘0’ labelled with red, and ‘1’ labelled with blue. So we get following image after above operations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/0*arstTpV4HHb6_swX.jpg" /></figure><p><strong>Step : 3</strong> — Next we calculate the average of all blue points and red points separately and that will be our new centroids. That is c1 and c2 shift to newly calculated centroids. (Remember, the images shown are not true values and not to true scale, it is just for demonstration only).And again, perform step 2 with new centroids and label data to ‘0’ and ‘1’.</p><p>So we get result as below :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/0*stqnuEpkkoo2Zbz2.jpg" /></figure><p>Now <strong>Step — 2</strong> and <strong>Step — 3</strong> are iterated until both centroids are converged to fixed points. <em>(Or it may be stopped depending on the criteria we provide, like maximum number of iterations, or a specific accuracy is reached etc.)</em> <strong>These points are such that sum of distances between test data and their corresponding centroids are minimum</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/0*Mt35vuY3vWlfMzcB.png" /></figure><p>Final result almost looks like below :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/0*oPA6veun4bINlyhY.jpg" /></figure><p>So this is just an intuitive understanding of K-Means Clustering. For more details go to <a href="https://www.datascience.com/blog/k-means-clustering">this</a> .i think you all have question in mind how we know the value of k,if we already know that it can be classify into three types so simply k=3 but if we not know how many classfications are possible with data so we use elbow method.The idea of the elbow method is to run k-means clustering on the dataset for a range of values of <em>k</em> (say, <em>k</em> from 1 to 10 in the examples above), and for each value of <em>k</em> calculate the sum of squared errors (SSE). Like this:</p><pre>var sse = {};<br>for (var k = 1; k &lt;= maxK; ++k) {<br>    sse[k] = 0;<br>    clusters = kmeans(dataset, k);<br>    clusters.forEach(function(cluster) {<br>        mean = clusterMean(cluster);<br>        cluster.forEach(function(datapoint) {<br>            sse[k] += Math.pow(datapoint - mean, 2);<br>        });<br>    });<br>}</pre><p>Then, plot a line chart of the SSE for each value of <em>k</em>. If the line chart looks like an arm, then the “elbow” on the arm is the value of <em>k</em> that is the best.</p><h3>When should I use it?</h3><ul><li>Your data is numeric. It doesn’t work with categorical features. We’re computing the distance between real numbers!</li><li>If you don’t have labels for your data</li><li>K-means is the simplest. To implement and to run. All you need to do is choose “k” and run it a number of times.</li><li>K-means and other clustering algorithms shine when you have multivariate data. They will “work” with 1-dimensional data, but they are not very smart anymore.</li><li>useful when you have an idea of how many clusters actually exists in your space.</li></ul><h3>Other examples</h3><p><a href="https://github.com/georgymh/ml-fraud-detection">https://github.com/georgymh/ml-fraud-detection</a> (Fraud Detection)</p><p><a href="https://github.com/Datamine/MNIST-K-Means-Clustering/blob/master/Kmeans.ipynb">https://github.com/Datamine/MNIST-K-Means-Clustering/blob/master/Kmeans.ipynb</a> (MNIST without labels (finally))</p><pre><em>#matrix math</em><br><strong>import</strong> <strong>numpy</strong> <strong>as</strong> <strong>np</strong><br><em>#graphing</em><br><strong>import</strong> <strong>matplotlib.pyplot</strong> <strong>as</strong> <strong>plt</strong><br><em>#graphing animation</em><br><strong>import</strong> <strong>matplotlib.animation</strong> <strong>as</strong> <strong>animation</strong></pre><pre><em>#load textfile dataset (2D data points)</em><br><em># for each user, how many packets are sent per second and what&#39;s the size of a packet</em><br><em>#anomalies (DDOS attempts) will have lots of big packets sent in a short amount of time </em><br><strong>def</strong> load_dataset(name):<br>    <strong>return</strong> np.loadtxt(name)<br> <strong>return</strong> np.loadtxt(name)</pre><pre><em>#euclidian distance between 2 data points. For as many data points as necessary. </em><br><strong>def</strong> euclidian(a, b):<br>    <strong>return</strong> np.linalg.norm(a-b)</pre><p>O k-means algorithm With the above steps, since we needed to build our algorithm, which will receive as parameters:</p><ul><li>K: The number of clusters (required)</li><li>epsilon: The minimum error to be used in the stop condition (optional, default == 0)</li><li>Distance: The method is used to calculate the distance (Optional defalut == 0) And has the return:</li><li>the centroids</li><li>The evolution history of centroids</li><li>And the membership vector of each instance with its respective centroid</li></ul><pre><strong>def</strong> kmeans(k, epsilon=0, distance=&#39;euclidian&#39;):<br>    <em>#list to store past centroid</em><br>    history_centroids = []<br>    <em>#set the distance calculation type </em><br>    <strong>if</strong> distance == &#39;euclidian&#39;:<br>        dist_method = euclidian<br>    <em>#set the dataset<br></em> dataset = load_dataset(&#39;durudataset.txt&#39;)<br>    <em># dataset = dataset[:, 0:dataset.shape[1] - 1]</em><br>    <em># get the number of rows (instances) and columns (features) from the dataset</em><br>    num_instances, num_features = dataset.shape<br>    <em>#define k centroids (how many clusters do we want to find?) chosen randomly </em><br>    prototypes = dataset[np.random.randint(0, num_instances - 1, size=k)]<br>    <em>#set these to our list of past centroid (to show progress over time)</em><br>    history_centroids.append(prototypes)<br>    <em>#to keep track of centroid at every iteration</em><br>    prototypes_old = np.zeros(prototypes.shape)<br>    <em>#to store clusters</em><br>    belongs_to = np.zeros((num_instances, 1))<br>    norm = dist_method(prototypes, prototypes_old)<br>    iteration = 0<br>    <strong>while</strong> norm &gt; epsilon:<br>        iteration += 1<br>        norm = dist_method(prototypes, prototypes_old)<br>        <em>#for each instance in the dataset</em><br>        <strong>for</strong> index_instance, instance <strong>in</strong> enumrate(dataset):<br>            <em>#define a distance vector of size k</em><br>            dist_vec = np.zeros((k,1))<br>            <em>#for each centroid</em><br>            <strong>for</strong> index_prototype, prototype <strong>in</strong> enumerate(prototypes):<br>                <em>#compute the distance between x and centroid</em><br>                dist_vec[index_prototype] = dist_method(prototype, instance)<br>            <em>#find the smallest distance, assign that distance to a cluster</em><br>            belongs_to[index_instance, 0] = np.argmin(dist_vec)<br>            <br>        tmp_prototypes = np.zeros((k, num_features))<br>        <br>        <em>#for each cluster (k of them)</em><br>        <strong>for</strong> index <strong>in</strong> range(len(prototypes)):<br>            <em>#get all the points assigned to a cluster</em><br>            instances_close = [i <strong>for</strong> i <strong>in</strong> range(len(belongs_to)) <strong>if</strong> belongs_to[i] == index]<br>            <em>#find the mean of those points, this is our new centroid</em><br>            prototype = np.mean(dataset[instances_close], axis=0)<br>            <em>#add our new centroid to our new temporary list</em><br>            tmp_prototypes[index, :] = prototype<br>        <br>        <em>#set the new list to the current list</em><br>        prototypes = tmp_prototypes<br>        <br>        <em>#add our calculated centroids to our history for plotting</em><br>        history_centroids.append(tmp_prototypes)<br><br>    <em>#return calculated centroids, history of them all, and assignments for which cluster each datapoint belongs to</em><br>    <strong>return</strong> prototypes, history_centroids, belongs_to</pre><pre><em>#lets define a plotting algorithm for our dataset and our centroids</em><br><strong>def</strong> plot(dataset, history_centroids, belongs_to):<br>    <em>#we&#39;ll have 2 colors for each centroid cluster</em><br>    colors = [&#39;r&#39;, &#39;g&#39;]<br><br>    <em>#split our graph by its axis and actual plot</em><br>    fig, ax = plt.subplots()<br><br>    <em>#for each point in our dataset</em><br>    <strong>for</strong> index <strong>in</strong> range(dataset.shape[0]):<br>        <em>#get all the points assigned to a cluster</em><br>        instances_close = [i <strong>for</strong> i <strong>in</strong> range(len(belongs_to)) <strong>if</strong> belongs_to[i] == index]<br>        <em>#assign each datapoint in that cluster a color and plot it</em><br>        <strong>for</strong> instance_index <strong>in</strong> instances_close:<br>            ax.plot(dataset[instance_index][0], dataset[instance_index][1], (colors[index] + &#39;o&#39;))<br><br>    <em>#lets also log the history of centroids calculated via training</em><br>    history_points = []<br>    <em>#for each centroid ever calculated</em><br>    <strong>for</strong> index, centroids <strong>in</strong> enumerate(history_centroids):<br>        <em>#print them all out</em><br>        <strong>for</strong> inner, item <strong>in</strong> enumerate(centroids):<br>            <strong>if</strong> index == 0:<br>                history_points.append(ax.plot(item[0], item[1], &#39;bo&#39;)[0])<br>            <strong>else</strong>:<br>                history_points[inner].set_data(item[0], item[1])<br>                <strong>print</strong>(&quot;centroids {} {}&quot;.format(index, item))<br><br>                plt.show()<br><strong>def</strong> execute():<br>    <em>#load dataset</em><br>    dataset = load_dataset(&#39;durudataset.txt&#39;)<br>    <em>#train the model on the data</em><br>    centroids, history_centroids, belongs_to = kmeans(2)<br>    <em>#plot the results</em><br>    plot(dataset, history_centroids, belongs_to<br><br><em>#do everything</em><br>execute()</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adb69a1a61b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel in ecommerce]]></title>
            <link>https://medium.com/@afnanamin/laravel-in-ecommerce-c57c8518632d?source=rss-a149ba728698------2</link>
            <guid isPermaLink="false">https://medium.com/p/c57c8518632d</guid>
            <category><![CDATA[laravel-5]]></category>
            <category><![CDATA[ecommerce]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[website]]></category>
            <dc:creator><![CDATA[Afnan Amin Ali]]></dc:creator>
            <pubDate>Sat, 16 Jun 2018 09:49:52 GMT</pubDate>
            <atom:updated>2018-06-16T09:49:52.435Z</atom:updated>
            <content:encoded><![CDATA[<p>IN <a href="https://medium.com/@afnanamin/develop-ecommerce-website-with-laravel-50a2f540afc7">PART 1 </a>we understand how to setup the MVC framework of laravel.To understand this i recommend to watch previous blog.I am going to create HomeController. For that I am going to use <em>artisan</em>&#39;s make:controller command to create the controller. Open Terminal and go to your project folder and run the following command:</p><pre><strong>php</strong> <strong>artisan</strong> <strong>make</strong>:controller <strong>HomeController</strong></pre><p>artisan is a Laravel command line utility to perform various tasks like creating model, controllers etc. You can get a full list of commands by running php artisan. You can also write your own command for some specific purpose.</p><p>A new file will be created in app/Http/Controllers with name HomeControllers.phpwhich looks like this:</p><pre>&lt;?php</pre><pre>namespace <strong>App</strong>\<strong>Http</strong>\<strong>Controllers</strong>;</pre><pre>use <strong>Illuminate</strong>\<strong>Http</strong>\<strong>Request</strong>;</pre><pre><strong>class</strong> <strong>HomeController</strong> <strong>extends</strong> <strong>Controller</strong><br>{<br>  <br>}</pre><p>In this class I am going to create a public method called index. It is not necessary to be called <em>index</em> because it is calling the root page. You may call it as mySweetMethod, who stops you?</p><p>OK, so my index method will look like this:</p><pre><strong>public</strong> <strong>function</strong> <strong>index</strong>() {<br>    <strong>return</strong> view(&#39;index&#39;);<br>    } </pre><p>This method returns the output of view method which itself is taking a parameter here. In my case it is index. What actually it is? If you remember I created a file named index.blade.php. This function is taking name of blade file and after processing it is returning the HTML markup of the page to browser. We will discuss further in upcoming posts. If works well, now on accessing http://golmarket.dev you will the markup of our theme&#39;s index page. It is not beautiful as path of CSS and images are not correct but at least it works. If you check the source of <a href="/service/view-source:https://p.w3layouts.com/demos/july-2016/07-07-2016/grocery_store/web/">Home page</a> of the Demo you will see multiple calls of CSS and JS files are being made. It&#39;s OK but this is not what I want, neither it&#39;s recommend in modern web development. The reason is that multiple requests slow down the performance of your page. Our goal should be to have as minimal as possible requests on a page so that it loads faster. If it loads faster then chances are it will rank better on Google as speed is one of the core factor to get appeared on Google&#39;s top pages.</p><p>I am now going to tell how to optimize your page by reducing unnecessary requests into one and how to create a master layout that could be used for other inner pages. Right now if you visit the main page on your local machine, it looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/0*XlXmGzqnWa54Xz9Q" /></figure><p>It looks OK if you compare with the <a href="https://p.w3layouts.com/demos/july-2016/07-07-2016/grocery_store/web/">original source</a>. If you check the source of it you find multiple &lt;script&gt; tags and multiple .css and .js requests. We are going to eliminate that by taking advantage of another awesome Laravel tool called <a href="https://laravel.com/docs/5.4/mix">Laravel Mix</a>.</p><h3>What is Laravel Mix?</h3><p>From Laravel’s website:</p><blockquote>Laravel Mix provides a fluent API for defining <a href="https://webpack.github.io/">Webpack</a> build steps for your Laravel application using several common CSS and JavaScript pre-processors.</blockquote><blockquote>Basically <em>Laravel Mix</em> is built on top of Webpack which goes through differnt dependency modules(CSS or JS) and produce static resources so that you can use on your web pages. You don’t need to get worried about which JS file is being used in other JS as webpack takes care of dependency graph. Take look at <a href="https://webpack.js.org/concepts/">it</a> to learn concepts. If you are coming from <em>Gulp</em> world then it should not so alien for you.</blockquote><blockquote>Anyways, now go to app/resources/saas/app.scss, here you will find some initial entries like:</blockquote><pre><em>// Fonts</em><br>@<strong>import</strong> url(https://fonts.googleapis.com/css?family=Raleway:300,400,600);<br>@<strong>import</strong> &quot;variables&quot;;<br><em>// Bootstrap</em><br>@<strong>import</strong> &quot;bootstrap&quot;;</pre><p>I removed all unnecessary inline css link tags and called @import to include required libs and other files. Final app.scss will look like this:</p><pre><em>// Variables</em><br>@<strong>import</strong> &quot;variables&quot;;<br><em>// Bootstrap</em><br>@<strong>import</strong> &quot;bootstrap&quot;;<br>@<strong>import</strong> &quot;../../../node_modules/font-awesome/scss/font-awesome&quot;;<br>@<strong>import</strong> &quot;../../../node_modules/flexslider/flexslider&quot;;<br>@<strong>import</strong> &quot;style&quot;;<br>@<strong>import</strong> &quot;site&quot;;</pre><p>Now let&#39;s open webpack.min.js file which looks like this:</p><pre><strong>const</strong> { mix } = require(&#39;laravel-mix&#39;);<br><br><em>/*<br> |--------------------------------------------------------------------------<br> | Mix Asset Management<br> |--------------------------------------------------------------------------<br> |<br> | Mix provides a clean, fluent API for defining some Webpack build steps<br> | for your Laravel application. By default, we are compiling the Sass<br> | file for the application as well as bundling up all the JS files.<br> |<br> */</em><br><br>mix.js(&#39;resources/assets/js/app.js&#39;, &#39;public/js&#39;)<br>   .sass(&#39;resources/assets/sass/app.scss&#39;, &#39;public/css&#39;);</pre><p>Since Laravel Mix is ES6 based, it is using <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">destructuring assignment</a> here to assign mix variable. Read further elsewhere about it as this is not the scope of this article.he next couple of lines doing entire magic; mix.js(&#39;resources/assets/js/app.js&#39;, &#39;public/js&#39;) says to read app.js contents, pull them and put them up in public/jsafter mixing them up. Same is for mix.sass. Since it is using SAAS compatible so you may use CSS or SAAS based syntax to define your layouts. Webpack compiled them to a single CSS anyway. Now in master.blade.php, all I have to make these two calls for JS and CSS resources respectively:</p><p>&lt;script src=&quot;{!! asset(&#39;js/app.js&#39;) !!}&quot;&gt;&lt;/script&gt;<br>and<br>&lt;link rel=&quot;stylesheet&quot; href=&quot;{!! asset(&#39;css/app.css&#39;) !!}&quot;&gt;</p><p>Cool, no? No more hassle of taking care of multiple URLs in your page. In future if you want to add a new library or css file, all you have to do add in relevant <em>entry point</em> file.</p><p>Similarly, the final app/resources/js/app.js looks like this:</p><pre><strong>require</strong>(&#39;../../../node_modules/jquery/dist/jquery.min&#39;)<br><strong>require</strong>(&#39;../../../node_modules/bootstrap-sass/assets/javascripts/bootstrap.min&#39;)</pre><pre><strong>require</strong>(&#39;./move-top&#39;)<br><strong>require</strong>(&#39;./easing&#39;)<br><strong>require</strong>(&#39;../../../node_modules/flexslider/jquery.flexslider-min&#39;)<br><strong>require</strong>(&#39;./minicart.min&#39;)<br><strong>require</strong>(&#39;./site&#39;)</pre><p>Now, in order to mix them up and put in public/ folder you gotta run a command. Go to your project&#39;s root folder and run the following command:</p><pre>npm <strong>run</strong> dev</pre><p>It will read the stuff and put the final output in respective /public/ files. In our case it is app.css and app.js</p><p>If you notice the content, it is simply merging the file which is good if you are in development mode but for final deployment it is still not <em>so good</em>. Mix comes up with a command:</p><pre>npm <strong>run</strong> production</pre><p>which minify all the resources for optimal performance.</p><p>OK, so far so good, now it’s time to create our master layout a layout by emptying the middle part of it. On inspecting I figured out that I have to make the content of w3l_banner_nav_right dynamic as surrounding is something which will be repeated on other pages. I cut the markup and shifted to index.blade.php. In master.blade.php, &lt;div&gt; with the class w3l_banner_nav_right now look like this:</p><pre>&lt;div <strong>class</strong>=&quot;w3l_banner_nav_right&quot;&gt;<br>        @<strong>yield</strong>(&#39;content&#39;)<br>&lt;/div&gt;</pre><p>@yield is a directive of <a href="https://laravel.com/docs/5.4/blade">Laravel Blades</a>,a template engine offered by Laravel. If you are coming from other MVC frameworks then this should not be alien for you. Templates make things easier to manage when their is a repetitive HTML like header, footer and sidebars etc. Template engine also helps to render the output which is being prepared at Controller level. Now before I explain @yeild further, let&#39;s open to index.blade.php file which after making changes will look like this:</p><pre>@extends(&#39;layout.master&#39;)<br>@section(&#39;content&#39;)<br>    &lt;section class=&quot;slider&quot;&gt;<br>        &lt;div class=&quot;flexslider&quot;&gt;<br>            &lt;ul class=&quot;slides&quot;&gt;<br>                &lt;li&gt;<br>                    &lt;div class=&quot;w3l_banner_nav_right_banner&quot;&gt;<br>                        &lt;h3&gt;Make your &lt;span&gt;food&lt;/span&gt; with Spicy.&lt;/h3&gt;<br>                        &lt;div class=&quot;more&quot;&gt;<br>                            &lt;a href=&quot;products.html&quot; class=&quot;button--saqui button--round-l button--text-thick&quot; data-text=&quot;Shop now&quot;&gt;Shop now&lt;/a&gt;<br>                        &lt;/div&gt;<br>                    &lt;/div&gt;<br>                &lt;/li&gt;<br>                &lt;li&gt;<br>                    &lt;div class=&quot;w3l_banner_nav_right_banner1&quot;&gt;<br>                        &lt;h3&gt;Make your &lt;span&gt;food&lt;/span&gt; with Spicy.&lt;/h3&gt;<br>                        &lt;div class=&quot;more&quot;&gt;<br>                            &lt;a href=&quot;products.html&quot; class=&quot;button--saqui button--round-l button--text-thick&quot; data-text=&quot;Shop now&quot;&gt;Shop now&lt;/a&gt;<br>                        &lt;/div&gt;<br>                    &lt;/div&gt;<br>                &lt;/li&gt;<br>                &lt;li&gt;<br>                    &lt;div class=&quot;w3l_banner_nav_right_banner2&quot;&gt;<br>                        &lt;h3&gt;upto &lt;i&gt;50%&lt;/i&gt; off.&lt;/h3&gt;<br>                        &lt;div class=&quot;more&quot;&gt;<br>                            &lt;a href=&quot;products.html&quot; class=&quot;button--saqui button--round-l button--text-thick&quot; data-text=&quot;Shop now&quot;&gt;Shop now&lt;/a&gt;<br>                        &lt;/div&gt;<br>                    &lt;/div&gt;<br>                &lt;/li&gt;<br>            &lt;/ul&gt;<br>        &lt;/div&gt;<br>    &lt;/section&gt;<br>@stop</pre><p>On top there is a directive @extends(&#39;layout.master&#39;) which tells that this inner page, the index.blade.php is actually <em>extends</em> it&#39;s parent, the master.blade.php which resides in layout directory. Dot notation is being used to refer the folder itself. It is not necessary that you put in layout folder, it&#39;s all about code management and I prefer to make things modular and manageable as much as I can.<br>Ok, the next line is @section(&#39;content&#39;), this directive tells that there is a section named content, whatever you find in it it should be placed in the contentplaceholder of master.blade.php whih is then rendered and displayed by @yield(&#39;content&#39;) directive. Now you learnt what @yield does. @@stop tells to halt here and don&#39;t include further of it. Check the <a href="https://laravel.com/docs/5.4/blade#defining-a-layout">docs</a> to learn further about it.</p><p>Alright! that’s it for now. This post should help you to gain some confidence to transfer and HTML layout in Laravel system and getting idea of basics of of Laravel Mix. In next post I will touch some basics of Database features offered by Laravel. Stay tuned!</p><p>The repo of this project is being maintained <a href="https://github.com/kadnan/golmarket/">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c57c8518632d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>