<?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 Jebaseelan Ravi on Medium]]></title>
        <description><![CDATA[Stories by Jebaseelan Ravi on Medium]]></description>
        <link>https://medium.com/@jebaseelanravi96?source=rss-a93a9a4c20f1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*NaF4QpJaABB3-OZXA3pQZA.jpeg</url>
            <title>Stories by Jebaseelan Ravi on Medium</title>
            <link>https://medium.com/@jebaseelanravi96?source=rss-a93a9a4c20f1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 05:37:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jebaseelanravi96/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[Scrapy Tutorial — Part 5]]></title>
            <link>https://medium.com/@jebaseelanravi96/scrapy-tutorial-part-5-ab1e04553f82?source=rss-a93a9a4c20f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab1e04553f82</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[scrapy]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Jebaseelan Ravi]]></dc:creator>
            <pubDate>Sat, 16 Apr 2022 00:26:51 GMT</pubDate>
            <atom:updated>2022-04-17T22:49:44.492Z</atom:updated>
            <content:encoded><![CDATA[<h3>Scrapy Tutorial — Part 5</h3><p>How to deploy a scrapy spider into production?</p><p>This blog is part of a tutorial series: <a href="https://medium.com/@jebaseelanravi96/scrapy-tutorial-part-1-8f8eb2567ff">PART 1</a>, <a href="https://medium.com/@jebaseelanravi96/scrapy-tutorial-part-2-edc95ced0cc1">PART 2</a>, <a href="https://medium.com/@jebaseelanravi96/15690956be00">PART 3</a>, <a href="https://medium.com/@jebaseelanravi96/e363793d4c94">PART 4</a>, <a href="https://medium.com/@jebaseelanravi96/scrapy-tutorial-part-5-ab1e04553f82">PART 5</a></p><p>Running Scrapy spiders in your local machine is very convenient for the (early) development stage, but not so much when you need to execute long-running spiders or move spiders to run in production continuously. This is where the solutions for deploying Scrapy spiders come in.</p><p>Popular choices for deploying Scrapy spiders are:</p><ul><li><a href="https://docs.scrapy.org/en/latest/topics/deploy.html#deploy-scrapyd">Scrapyd</a> (open source) — 🆓</li><li><a href="https://docs.scrapy.org/en/latest/topics/deploy.html#deploy-scrapy-cloud">Zyte Scrapy Cloud</a> (cloud-based) — 💰</li></ul><p>Let us look at how we can deploy the spider using Scrapyd.</p><h3>Deploying to a Scrapyd Server</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ku_1Gd006EaqcQyd" /><figcaption>Photo by <a href="https://unsplash.com/@wocintechchat?utm_source=medium&amp;utm_medium=referral">Christina @ wocintechchat.com</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://github.com/scrapy/scrapyd">Scrapyd</a> is an open source application to run Scrapy spiders. It provides a server with HTTP API, capable of running and monitoring Scrapy spiders.</p><p>To deploy spiders to Scrapyd, you can use the scrapyd-deploy tool provided by the <a href="https://github.com/scrapy/scrapyd-client">scrapyd-client</a> package. Please refer to the <a href="https://scrapyd.readthedocs.io/en/latest/deploy.html">scrapyd-deploy documentation</a> for more information.</p><p>Scrapyd is maintained by some of the Scrapy developers</p><p>Install the packages</p><pre>pip install scrapyd<br>pip install scrapyd-client</pre><p>Start the scrapyd server</p><pre>$ scrapyd</pre><p>You should see something like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tRlgIA3yNDY6pg9vg32H8Q.png" /><figcaption>Scrapyd server logs</figcaption></figure><p>If you launch <a href="http://localhost:6800/">http://localhost:6800/</a> in your browser you should see</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*flKFiHBIsKfoWU_ngd7DaA.png" /><figcaption>Scrapyd UI</figcaption></figure><p>Now we have the scrapyd server running we have to deploy our spider here using the following commands</p><p>Update the quotesspider/scrapy.cfg to following code</p><p>scrapy.cfg is a <em>deploy configuration file which describes how you are going to deploy your spider</em></p><pre>[settings]<br>default = quotesspider.settings</pre><pre>[deploy:local]<br>url = <a href="http://localhost:6800/">http://localhost:6800/</a> # where is your scrapyd server running<br>project = quotesspider # project name</pre><p>Now run</p><pre>$ cd quotesspider</pre><pre># format: scrapyd-deploy &lt;target&gt; -p project</pre><pre>$ scrapyd-deploy local -p quotesspider</pre><p>This will eggify your project and upload it to the target. If you have a setup.py file in your project, it will be used, otherwise one will be created automatically.If successful you should see a JSON response similar to the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OxGCtrVzsZWcwWiiXWoCmg.png" /><figcaption>Scrapy deploy logs</figcaption></figure><p>Now you can start the scheduling/running the spider using</p><pre>$ scrapyd-client schedule -p &lt;project_name&gt; &lt;spider_name&gt;</pre><pre>$ scrapyd-client schedule -p quotesspider quotes</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OpcNsNyPatZF_nXxpTxrsg.png" /><figcaption>Scrapyd schedule log</figcaption></figure><p>Now if you go to <a href="http://localhost:6800/jobs">http://localhost:6800/jobs</a> you can see our spider is running</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hxzYlyBvfclK1qCj2_isqg.png" /><figcaption>Scrapyd UI</figcaption></figure><p>You can see the log</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kX95u0CGDRMt4u_rKjCrxg.png" /><figcaption>Scrapyd log for spider run</figcaption></figure><p>Whoooo !! We have deployed our spider. You can run scrapyd in anywhere(may be in cloud) and replace the url in scrapy.cfg and deploy the same way.</p><p>That’s a wrap!!</p><p>Happy Scrapping!! 🕷</p><p>Please leave a comment if you face any issues</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab1e04553f82" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scrapy Tutorial — Part 4]]></title>
            <link>https://medium.com/@jebaseelanravi96/scrapy-tutorial-part-4-e363793d4c94?source=rss-a93a9a4c20f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/e363793d4c94</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Jebaseelan Ravi]]></dc:creator>
            <pubDate>Sat, 16 Apr 2022 00:26:09 GMT</pubDate>
            <atom:updated>2022-04-18T18:59:36.899Z</atom:updated>
            <content:encoded><![CDATA[<h3>Scrapy Tutorial — Part 4</h3><p>How to store data into DB in scrapy?</p><p><a href="https://medium.com/@jebaseelanravi96/scrapy-tutorial-part-1-8f8eb2567ff">PART 1</a>, <a href="https://medium.com/@jebaseelanravi96/scrapy-tutorial-part-2-edc95ced0cc1">PART 2</a>, <a href="https://medium.com/@jebaseelanravi96/15690956be00">PART 3</a>, <a href="https://medium.com/@jebaseelanravi96/e363793d4c94">PART 4</a>, <a href="https://medium.com/@jebaseelanravi96/scrapy-tutorial-part-5-ab1e04553f82">PART 5</a></p><p>In the previous tutorial we have created a scrapy spider to crawl <a href="https://quotes.toscrape.com/">https://quotes.toscrape.com/</a> and stored the crawled data into JSON file but in the real world we typically store the data in the Databases such as MYSQL, SQLite, Elastic search, Postgres etc</p><p>In this tutorial we will learn how to store the crawled data into SQLite database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*a_OvGh_-_bHKblaN" /><figcaption>Photo by <a href="https://unsplash.com/@hiteshchoudhary?utm_source=medium&amp;utm_medium=referral">Hitesh Choudhary</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>What is SQLite?</strong></p><p>SqLite is a DB is file format DB which means you don’t need to install any packages or installer. I have chosen this because it is easy to get started since it does not require any installation but you can this tutorial to any DB of your choice.</p><p>SQLite is the <a href="https://www.sqlite.org/mostdeployed.html">most used</a> database engine in the world. SQLite is built into all mobile phones and most computers and comes bundled inside countless other applications that people use every day.</p><h3>How to store crawled data into DB using Scrapy?</h3><p>After an item/data has been scraped by a spider, it is sent to the Item Pipeline which processes it through several components that are executed sequentially. You can think of item pipeline as a component used for post processing of the data.</p><p>Item pipeline is invoked when you call yield from your quotesspider/spiders/quotes_spiders.py</p><p>Each item pipeline component (sometimes referred as just “Item Pipeline”) is a Python class that implements a simple method. They receive an item and perform an action over it, also deciding if the item should continue through the pipeline or be dropped and no longer processed.</p><p>Typical uses of item pipelines are:</p><ul><li>cleansing HTML data</li><li>validating scraped data (checking that the items contain certain fields)</li><li>checking for duplicates (and dropping them)</li><li>storing the scraped item in a database</li></ul><p>We will be using the use case #4 in this tutorial.</p><h3>Item pipeline example</h3><p>Writing items to SQLite DB</p><p>update your quotesspider/pipelines.py to the following code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56c147f801f52529ad8f8cae967c89f3/href">https://medium.com/media/56c147f801f52529ad8f8cae967c89f3/href</a></iframe><p>Let ‘s us understand what this pipeline does</p><p>open_spider — This method is called when the spider is opened.</p><p>close_spider — This method is called when the spider is closed.</p><p>process_item — This method is called whenever a item is crawled by our spider.</p><p>Now that we created our pipeline but we need to tell the spider to use this pipeline class</p><h3>Activating an Item Pipeline component</h3><p>To activate an Item Pipeline component you must add its class to the <a href="https://docs.scrapy.org/en/latest/topics/settings.html#std-setting-ITEM_PIPELINES"><strong>ITEM_PIPELINES</strong></a> setting, like in the following example:</p><p>quotesspider/settings.py</p><pre>ITEM_PIPELINES = {<br>   &#39;quotesspider.pipelines.QuotesspiderPipeline&#39;: 300,<br>}</pre><p>That’s it , Now run your spider using ( you need to be inside quotesspider folder</p><pre>scrapy crawl quotes</pre><h3>How to Verify whether the data stored in DB?</h3><p>Open up <a href="https://sqliteonline.com/">https://sqliteonline.com/</a> on your browser which provides UI for your SQLite DB</p><p>click File-&gt;Open DB-&gt; select your sqlite file quotes.db</p><p>Once the window is opened you can run select * from quotes to see the results.</p><p>You should see something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YCjGpjorfclKvh5m466nAw.png" /><figcaption>Crawled Data stored in Sqlite DB</figcaption></figure><p>There is not auto refresh on this online tool .If you run your spider again you need to reload your file(File-&gt;Open DB-&gt; select your file quotes.db) to see the changes.</p><p>Happy Scrapping!! 🕷</p><p>Please leave a comment if you face any issues.</p><p><a href="https://medium.com/@jebaseelanravi96/scrapy-tutorial-part-1-8f8eb2567ff">PART 1</a>, <a href="https://medium.com/@jebaseelanravi96/scrapy-tutorial-part-2-edc95ced0cc1">PART 2</a>, <a href="https://medium.com/@jebaseelanravi96/15690956be00">PART 3</a>, <a href="https://medium.com/@jebaseelanravi96/e363793d4c94">PART 4</a>, <a href="https://medium.com/@jebaseelanravi96/scrapy-tutorial-part-5-ab1e04553f82">PART 5</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e363793d4c94" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scrapy Tutorial — Part 3]]></title>
            <link>https://medium.com/@jebaseelanravi96/scrapy-tutorial-part-3-15690956be00?source=rss-a93a9a4c20f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/15690956be00</guid>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Jebaseelan Ravi]]></dc:creator>
            <pubDate>Sat, 16 Apr 2022 00:26:00 GMT</pubDate>
            <atom:updated>2022-04-21T15:32:15.911Z</atom:updated>
            <content:encoded><![CDATA[<h3>Scrapy Tutorial — Part 3</h3><p>How to crawl multiple pages using scrapy?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XibyE2KN-5k82DBY" /><figcaption>Photo by <a href="https://unsplash.com/@socialcut?utm_source=medium&amp;utm_medium=referral">S O C I A L . C U T</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://medium.com/@jebaseelanravi96/scrapy-tutorial-part-1-8f8eb2567ff">PART 1</a>, <a href="https://medium.com/@jebaseelanravi96/scrapy-tutorial-part-2-edc95ced0cc1">PART 2</a>, <a href="https://medium.com/@jebaseelanravi96/15690956be00">PART 3</a>, <a href="https://medium.com/@jebaseelanravi96/e363793d4c94">PART 4</a>, <a href="https://medium.com/@jebaseelanravi96/scrapy-tutorial-part-5-ab1e04553f82">PART 5</a></p><p>In the previous blog, we have created a scrapy spider to crawl quotes and author name from our favorite website <a href="https://quotes.toscrape.com/">https://quotes.toscrape.com/</a></p><p>We were just scraping the stuff from the first page alone from <a href="https://quotes.toscrape.com/">https://quotes.toscrape.com</a>, what if you want quotes from all the pages in the website? such as</p><pre><a href="https://quotes.toscrape.com/page/3/">https://quotes.toscrape.com/page/2/</a><br><a href="https://quotes.toscrape.com/page/3/">https://quotes.toscrape.com/page/3/</a><br><a href="https://quotes.toscrape.com/page/3/">https://quotes.toscrape.com/page/4/</a></pre><p>Now that you know how to extract data from one page from our previous blog, let’s see how to follow links to next page and crawl data recursively.</p><p>First thing is to extract the link to the next page we want to follow which is next Page link . Examining our page, we can see there is a link to the next page(right bottom) with the following markup:</p><p>Right click on Next in webpage and click inspect</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u2jp8rYQdAKOxQgnFLrVNA.png" /><figcaption>Inspect the next element</figcaption></figure><p>HTML code for next page link</p><pre><br>&lt;<strong>ul</strong> class=&quot;pager&quot;&gt;<br>    &lt;<strong>li</strong> class=&quot;next&quot;&gt;<br>        &lt;<strong>a</strong> href=&quot;/page/2/&quot;&gt;Next &lt;<strong>span</strong> aria-hidden=&quot;true&quot;&gt;<strong>&amp;rarr;</strong>&lt;/<strong>span</strong>&gt;&lt;/<strong>a</strong>&gt;<br>    &lt;/<strong>li</strong>&gt;<br>&lt;/<strong>ul</strong>&gt;</pre><p>We can try extracting it in the shell:</p><pre>$ scrapy shell &#39;<a href="https://quotes.toscrape.com/">https://quotes.toscrape.com/</a>&#39;</pre><p>You should see something as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d5Cr0rM4L-xSYtW6F0ih9Q.png" /><figcaption>Scrapy shell log</figcaption></figure><pre><strong>&gt;&gt;&gt; </strong>response.xpath(&#39;//li[@class=&quot;next&quot;]/a/@href&#39;).get()<br>&#39;/page/2/&#39;</pre><p>Let’s see now our spider modified to recursively follow the link to the next page, extracting data from it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8b4cddf3c6e2fe4d793e441e5c3fe55/href">https://medium.com/media/d8b4cddf3c6e2fe4d793e441e5c3fe55/href</a></iframe><p>Now, after extracting the data, the parse() method looks for the link to the next page, builds a full absolute URL using the <a href="https://docs.scrapy.org/en/latest/topics/request-response.html#scrapy.http.Response.urljoin"><strong>urljoin()</strong></a> method (since the links can be relative) and yields a new request to the next page, registering itself as callback to handle the data extraction for the next page and to keep the crawling going through all the pages.</p><p>What you see here is Scrapy’s mechanism of following links: when you yield a Request in a callback method, Scrapy will schedule that request to be sent and register a callback method to be executed when that request finishes.</p><p>Using this, you can build complex crawlers that follow links according to rules you define, and extract different kinds of data depending on the page it’s visiting.</p><p>In our example, it creates a sort of loop, following all the links to the next page until it doesn’t find one — handy for crawling blogs, forums and other sites with pagination.</p><h3>Run the spider</h3><pre>scrapy crawl quotes -o quotes.json</pre><p>If everything is running fine, it should give you following results</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aGW4E5ToW7O4RX8sYsjfPg.png" /><figcaption>Scrapy Crawl logs</figcaption></figure><p>check whether the results are stored in quotes.json</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TboG56IKkEZLWQyQvds-Ng.png" /><figcaption>Data stored in quotes.json</figcaption></figure><p>You can see that we have recursively crawled 100 quotes from 10 pages( 10 quotes/page).</p><p>So far we have been storing the crawled data into the JSON, in the next tutorial how to store the crawled data into DB.</p><p>Happy Scrapping!! 🕷</p><p>Please leave a comment if you face any issues.</p><p><a href="https://medium.com/@jebaseelanravi96/scrapy-tutorial-part-1-8f8eb2567ff">PART 1</a>, <a href="https://medium.com/@jebaseelanravi96/scrapy-tutorial-part-2-edc95ced0cc1">PART 2</a>, <a href="https://medium.com/@jebaseelanravi96/15690956be00">PART 3</a>, <a href="https://medium.com/@jebaseelanravi96/e363793d4c94">PART 4</a>, <a href="https://medium.com/@jebaseelanravi96/scrapy-tutorial-part-5-ab1e04553f82">PART 5</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15690956be00" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scrapy Tutorial — Part 2]]></title>
            <link>https://medium.com/@jebaseelanravi96/scrapy-tutorial-part-2-edc95ced0cc1?source=rss-a93a9a4c20f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/edc95ced0cc1</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Jebaseelan Ravi]]></dc:creator>
            <pubDate>Sat, 16 Apr 2022 00:25:48 GMT</pubDate>
            <atom:updated>2022-04-16T20:32:38.542Z</atom:updated>
            <content:encoded><![CDATA[<h3>Scrapy Tutorial — Part 2</h3><h3>step by step guide to create scrapy project and data extraction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ce3BR4L8tkmaj2Pz" /><figcaption>Photo by <a href="https://unsplash.com/@hiteshchoudhary?utm_source=medium&amp;utm_medium=referral">Hitesh Choudhary</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://medium.com/@jebaseelanravi96/scrapy-tutorial-part-1-8f8eb2567ff">PART 1</a>, <a href="https://medium.com/@jebaseelanravi96/scrapy-tutorial-part-2-edc95ced0cc1">PART 2</a>, <a href="https://medium.com/@jebaseelanravi96/15690956be00">PART 3</a>, <a href="https://medium.com/@jebaseelanravi96/e363793d4c94">PART 4</a>, <a href="https://medium.com/@jebaseelanravi96/scrapy-tutorial-part-5-ab1e04553f82">PART 5</a></p><p>This is the part 2 of the scrapy tutorial, if you have not read part-1 please visit to know how scrapy works and how to setup the environment.</p><p>In the last tutorial we learnt how to create a simple scrapy spider(a simple python module), In this tutorial we will learn about</p><ol><li>How to create a scrapy project?</li><li>How to write a spider to crawl a site and extract the data from it?</li></ol><p>Why do we need scrapy project when we can create a simple python file and extract the data as we did in part 1?. This is actually a good question. The reason is scrapy project offers lot of functionality such as a post processing of the data, deduplication etc. We will see them in detail in next tutorials.</p><h3>Creating a Scrapy Project</h3><p>TL:DR : The github repo for the tutorial is <a href="https://github.com/Jebaseelanravi/scrapy-tutorials">here</a></p><p>Make sure you have installed scrapy</p><pre>$ scrapy version<br>2.6.1</pre><p>if not install scrapy via</p><pre>$ pip install scrapy</pre><p>Now we can create a project</p><pre>$ scrapy startproject quotesspider</pre><p>This is will create following structure</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*A86yufD08p-X3YelxXYRDA.png" /><figcaption>Scrapy Project structure</figcaption></figure><p>You don’t have to worry about anything right now except spiders folders where you will be putting your spiders code. Let’s move on.</p><h3>First Spider in our spider Project</h3><p>Spiders are python classes that you define and that Scrapy uses to scrape information from a website (or a group of websites). They must subclass <a href="https://docs.scrapy.org/en/latest/topics/spiders.html#scrapy.Spider"><strong>Spider</strong></a> and define the initial requests to make and how to parse the downloaded page content to extract data.</p><p>Put the following code in quotesspider/spiders/quotes_spiders.py</p><pre><strong>import</strong> <strong>scrapy</strong><br><br><br><strong>class</strong> <strong>QuotesSpider</strong>(scrapy.Spider):<br>    name = &quot;quotes&quot;<br><br>    start_urls =[&#39;<a href="https://quotes.toscrape.com/">https://quotes.toscrape.com/</a>&#39;]<br><br>    <strong>def</strong> parse(self, response):<br>        <strong>with</strong> open(&#39;quotes.html&#39;, &#39;wb&#39;) <strong>as</strong> f:<br>            f.write(response.body)<br>        self.log(f&#39;Saved file <em>quotes.html</em>&#39;)</pre><p>As you can see, our Spider subclasses <a href="https://docs.scrapy.org/en/latest/topics/spiders.html#scrapy.Spider"><strong>scrapy.Spider</strong></a> and defines some attributes and methods:</p><ul><li>name — spider name (unique to each spider class)</li></ul><p>start_urls — spider will being the crawl from this attributes. It can be list of URLs</p><p>parse — Default callback method for response . The HTML response(entire webpage) for the start_urls will be downloaded internally by scrapy and passed as an argument to this method.</p><h3>How to execute the spider</h3><p>In order to execute the spider you must be inside the project dir</p><pre>$ cd quotesspider</pre><pre># scrapy crawl &lt;spider_name&gt;</pre><pre>$ scrapy crawl quotes</pre><p>Example output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0O7z3M6pDYsWOE-eM4vodg.png" /><figcaption>Scrapy logs</figcaption></figure><p>you can see the spider is opened and started to crawl and created a new file quotes.html in current directory. Basically what we have done is downloaded the html into the file. Now let us shift gear and see how to extract data using scrapy</p><h3>How to extract the data?</h3><p>The best way to learn how to extract data with Scrapy is trying selectors using the <a href="https://docs.scrapy.org/en/latest/topics/shell.html#topics-shell">Scrapy shell</a>.</p><p>The Scrapy shell is an interactive shell where you can try and debug your scraping code very quickly, without having to run the spider. It’s meant to be used for testing data extraction code, but you can actually use it for testing any kind of code as it is also a regular Python shell</p><p>Run</p><pre>$ scrapy shell &#39;https://quotes.toscrape.com&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d5Cr0rM4L-xSYtW6F0ih9Q.png" /><figcaption>Scrapy shell</figcaption></figure><p>Using the shell you can learn and debug how to extract the data</p><pre>&gt;&gt;&gt; response<br>&lt;200 https://quotes.toscrape.com/&gt;</pre><p>Try printing the entire content of the webpage</p><pre>&gt;&gt;&gt; response.text</pre><p>You can try selecting any elements using Xpath</p><pre>&gt;&gt;&gt; response.xpath(&#39;//title&#39;)<br>[&lt;Selector xpath=&#39;//title&#39; data=&#39;&lt;title&gt;Quotes to Scrape&lt;/title&gt;&#39;&gt;]<br><strong>&gt;&gt;&gt; </strong>response.xpath(&#39;//title/text()&#39;).get()<br>&#39;Quotes to Scrape&#39;</pre><h4>what is Xpath?</h4><p>XPath is defined as <strong>XML path</strong>. It is a syntax or language for finding any element on the web page using the XML path expression. XPath is used to find the location of any element on a webpage using HTML DOM structure. Typicall Xpath expression to extract any element from webpage will be</p><pre>//element[@attr_key=&quot;attr_value&quot;]</pre><pre>//element[@attr_key=&quot;attr_value&quot;]/text() # if you want text </pre><p>for example consider the following HTML code</p><pre>&lt;html&gt;<br>&lt;<strong>span class=&quot;test&quot;</strong>&gt;Hello&lt;/<strong>span</strong>&gt;<br>&lt;/html&gt;</pre><p>if you want to extract the Hello from above HTML the `xpath` would be</p><pre># //element[@attr_key=&quot;attr_value&quot;]/text() -&gt; format</pre><pre>//span[@class=&quot;test&quot;]/text()</pre><p>We won’t cover much of XPath here, but you can read more about <a href="https://docs.scrapy.org/en/latest/topics/selectors.html#topics-selectors">using XPath with Scrapy Selectors here</a>.</p><h4>Extracting the data — quotes and author name</h4><p>Each quote in <a href="https://quotes.toscrape.com/">https://quotes.toscrape.com</a> is represented by HTML elements that look like this:</p><pre>&lt;<strong>div</strong> class=&quot;quote&quot;&gt;<br>    &lt;<strong>span</strong> class=&quot;text&quot;&gt;“The world as we have created it is a process of our<br>    thinking. It cannot be changed without changing our thinking.”&lt;/<strong>span</strong>&gt;<br>    &lt;<strong>span</strong>&gt;<br>        by &lt;<strong>small</strong> class=&quot;author&quot;&gt;Albert Einstein&lt;/<strong>small</strong>&gt;<br>        &lt;<strong>a</strong> href=&quot;/author/Albert-Einstein&quot;&gt;(about)&lt;/<strong>a</strong>&gt;<br>    &lt;/<strong>span</strong>&gt;<br>    &lt;<strong>div</strong> class=&quot;tags&quot;&gt;<br>        Tags:<br>        &lt;<strong>a</strong> class=&quot;tag&quot; href=&quot;/tag/change/page/1/&quot;&gt;change&lt;/<strong>a</strong>&gt;<br>        &lt;<strong>a</strong> class=&quot;tag&quot; href=&quot;/tag/deep-thoughts/page/1/&quot;&gt;deep-thoughts&lt;/<strong>a</strong>&gt;<br>        &lt;<strong>a</strong> class=&quot;tag&quot; href=&quot;/tag/thinking/page/1/&quot;&gt;thinking&lt;/<strong>a</strong>&gt;<br>        &lt;<strong>a</strong> class=&quot;tag&quot; href=&quot;/tag/world/page/1/&quot;&gt;world&lt;/<strong>a</strong>&gt;<br>    &lt;/<strong>div</strong>&gt;<br>&lt;/<strong>div</strong>&gt;</pre><p>You can find this by hovering over any quote and right click -&gt; inspect</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dLhhtgfRL-3xlaWLosMgLw.png" /><figcaption>Inspecting the element</figcaption></figure><p>Let’s open up scrapy shell and play a bit to find out how to extract the data we want:</p><pre>$ scrapy shell &#39;https://quotes.toscrape.com&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZtlODnjRevXIsNyYTedovQ.png" /><figcaption>Scrapy shell log</figcaption></figure><p>First we need to select the entire quoteelement then we can extract the quote and author name.</p><p>xpath expression to select the quote element</p><pre>&gt;&gt;&gt; response.xpath(&#39;//div[@class=&quot;quote&quot;]&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vA9TRhsSNAmMbDgaQwpnbA.png" /><figcaption>List of Quotes</figcaption></figure><p>The result of running response.xpath(‘//div[@class=”quote”]’)is a list-like object called <a href="https://docs.scrapy.org/en/latest/topics/selectors.html#scrapy.selector.SelectorList"><strong>SelectorList</strong></a>, which represents a list of <strong>Selector</strong> objects that wrap around XML/HTML elements and allow you to run further queries to fine-grain the selection or extract the data.</p><p>Each of the selectors returned by the query above allows us to run further queries over their sub-elements. Let’s assign the first selector to a variable, so that we can run our Xpath selectors directly on a particular quote:</p><pre>&gt;&gt; quote = response.xpath(&#39;//div[@class=&quot;quote&quot;]&#39;)[0]</pre><pre>&gt;&gt; quote<br>&lt;Selector xpath=&#39;//div[<a href="http://twitter.com/class">@class</a>=&quot;quote&quot;]&#39; data=&#39;&lt;div class=&quot;quote&quot; itemscope itemtype...&#39;&gt;</pre><p>Now, let’s extract text, author from that quote using the quote object we just created:</p><pre>&gt;&gt; quote.xpath(&#39;span/text()&#39;).get()  # xpath to get quotes</pre><pre>&#39;“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”&#39;</pre><pre>&gt;&gt; quote.xpath(&#39;span/small/text()&#39;).get()  # xpath to get the author</pre><pre>&#39;Albert Einstein&#39;</pre><p>Having figured out how to extract each bit, we can now iterate over all the quotes elements and put them together into a Python dictionary</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da55b9894d38e920c2487a258454624f/href">https://medium.com/media/da55b9894d38e920c2487a258454624f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QMVrL36Ogzwu_EdywqH6LQ.png" /><figcaption>Data Extraction log</figcaption></figure><p><strong>Full code for our spider</strong></p><p>Integrating the above logic into our quotesspider/spiders/quotes_spiders.py file. Please update the file to the following code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ae505e1b9fbbcbbdad7c8db8c06f741/href">https://medium.com/media/5ae505e1b9fbbcbbdad7c8db8c06f741/href</a></iframe><p>Run the spider</p><pre>$ scrapy crawl quotes -o quotes.json</pre><p>If you run this spider, it will output the extracted data with the log and store the data in the quotes.json:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BMbMKhS82p33zTdQFyIN3A.png" /></figure><p>In this tutorial we have crawled data from the first page alone, In the next tutorial we will see how to crawl multiple pages using scrapy</p><p>Happy Scrapping!! 🕷</p><p>Please leave a comment if you face any issues.</p><p><a href="https://medium.com/@jebaseelanravi96/scrapy-tutorial-part-1-8f8eb2567ff">PART 1</a>, <a href="https://medium.com/@jebaseelanravi96/scrapy-tutorial-part-2-edc95ced0cc1">PART 2</a>, <a href="https://medium.com/@jebaseelanravi96/15690956be00">PART 3</a>, <a href="https://medium.com/@jebaseelanravi96/e363793d4c94">PART 4</a>, <a href="https://medium.com/@jebaseelanravi96/scrapy-tutorial-part-5-ab1e04553f82">PART 5</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edc95ced0cc1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scrapy Tutorial — Part 1]]></title>
            <link>https://medium.com/@jebaseelanravi96/scrapy-tutorial-part-1-8f8eb2567ff?source=rss-a93a9a4c20f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f8eb2567ff</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Jebaseelan Ravi]]></dc:creator>
            <pubDate>Sat, 16 Apr 2022 00:23:41 GMT</pubDate>
            <atom:updated>2022-04-16T00:31:53.954Z</atom:updated>
            <content:encoded><![CDATA[<h3>Scrapy Tutorial — Part 1</h3><h3>Beginner tutorial on how to scrape any website using scrapy</h3><h3><strong>what is scrapy?</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DD6vC4HShdr5INkD" /><figcaption>Photo by <a href="https://unsplash.com/@hiteshchoudhary?utm_source=medium&amp;utm_medium=referral">Hitesh Choudhary</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://medium.com/@jebaseelanravi96/scrapy-tutorial-part-1-8f8eb2567ff">PART 1</a>, <a href="https://medium.com/@jebaseelanravi96/scrapy-tutorial-part-2-edc95ced0cc1">PART 2</a>, <a href="https://medium.com/@jebaseelanravi96/15690956be00">PART 3</a>, <a href="https://medium.com/@jebaseelanravi96/e363793d4c94">PART 4</a>, <a href="https://medium.com/@jebaseelanravi96/scrapy-tutorial-part-5-ab1e04553f82">PART 5</a></p><p>Scrapy is an python framework for crawling web sites and extracting structured data which can be used for a wide range of useful applications, like data mining, information processing or historical archival</p><p>I have divided the tutorial into 5 different parts to give you a deep understanding of what is scrapy framework and how we can crawl any website using the scraper framework</p><p>Part 1: Environmental setup and writing your first spider</p><p>Part 2: how to create a scrapy project and extract the data from web?</p><p>Part 3: how to crawl multiple pages using scrapy framework</p><p>Part 4: how to store the crawled data into a database?</p><p>Part 5: how to deploy a scrapy spider into a production?</p><p>For this tutorial series we are going to crawl</p><ol><li>Quotes</li><li>Author Name</li></ol><p>from the famous website <a href="https://quotes.toscrape.com/">https://quotes.toscrape.com/</a></p><h3><strong>Installing scrapy</strong></h3><p>If you are using Anaconda</p><pre>conda install -c conda-forge scrapy</pre><p>If you are using Python package manager pypi.</p><pre>pip install scrapy</pre><p>Now we have installed all the dependencies, let’s write some code. Here’s the code for a spider that scrapes famous quotes from website <a href="https://quotes.toscrape.com/">https://quotes.toscrape.com</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ee3d567ff56fb648df84f6353641c03/href">https://medium.com/media/1ee3d567ff56fb648df84f6353641c03/href</a></iframe><p>Put this in a text file, name it to something like first_spider.py and run the spider using the <a href="https://docs.scrapy.org/en/latest/topics/commands.html#std-command-runspider"><strong>runspider</strong></a> command</p><pre>scrapy runspider first_spider.py -o quotes.json</pre><p>If successful you should see something like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2T2RGw0qNFH6qUVZx-iwWg.png" /><figcaption>Scrapy Output</figcaption></figure><p>When this finishes you will have in the quotes.json file a list of the quotes in JSON Lines format, containing text and author, looking like this:</p><pre>{&quot;quote&quot;: &quot;\u201cThe world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.\u201d&quot;, &quot;author&quot;: &quot;Albert Einstein&quot;},</pre><pre>{&quot;quote&quot;: &quot;\u201cIt is our choices, Harry, that show what we truly are, far more than our abilities.\u201d&quot;, &quot;author&quot;: &quot;J.K. Rowling&quot;},</pre><p>That’s it , you have built your first spider and crawled data from the web.</p><p>But what actually happened when you run the command runspider . Let me explain it.</p><ol><li>When you run the command runspider scrapy looked for the scrapy start_urls in the spider class</li><li>It assumes that it need to start the crawl from start_urls and send a web request to urls mentioned in the start_urls list and get the entire HTML responseof the url in our case it is `<a href="https://quotes.toscrape.com/">https://quotes.toscrape.com/</a>`</li><li>response is nothing but entire HTML content of the webpage. You don’t have to worry about hitting the website to get the response of the websites. Scrapy does that for us in more optimised way. All you have to do is specify URL you wanted to crawl in start_urls . How cool is that?</li><li>This response is passed as a argument to default callback method( method to extract your data from HTML content). The default callback method is def parse()</li><li>In the parse callback method, we loop through the quote elements using a Xpath Selector, yield a Python dict with the extracted quote text and author</li></ol><p>Don’t worry about Xpath or anything if it does not makes sense, I did not understand it either in my very first time.We will get better.</p><p>In the next post, I will explain how to create a scrapy project and extract a data from webpage.</p><p>Happy scrapping!!! 🕷</p><p>Please leave a comment if you face any issues</p><p><a href="https://medium.com/@jebaseelanravi96/scrapy-tutorial-part-1-8f8eb2567ff">PART 1</a>, <a href="https://medium.com/@jebaseelanravi96/scrapy-tutorial-part-2-edc95ced0cc1">PART 2</a>, <a href="https://medium.com/@jebaseelanravi96/15690956be00">PART 3</a>, <a href="https://medium.com/@jebaseelanravi96/e363793d4c94">PART 4</a>, <a href="https://medium.com/@jebaseelanravi96/scrapy-tutorial-part-5-ab1e04553f82">PART 5</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f8eb2567ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Titanic Survival Prediction using Tensorflow]]></title>
            <link>https://medium.com/@jebaseelanravi96/tensorflow-predicting-the-survival-chance-81dae7f1f962?source=rss-a93a9a4c20f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/81dae7f1f962</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Jebaseelan Ravi]]></dc:creator>
            <pubDate>Thu, 24 Mar 2022 21:39:12 GMT</pubDate>
            <atom:updated>2022-03-27T22:22:05.313Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hi everyone,</h3><p>In this tutorial, you will learn to use TFLearn and TensorFlow to estimate the surviving chance of Titanic passengers using their personal information (such as gender, age, etc…). To tackle this classic machine learning task, we are going to build a deep neural network classifier.</p><h3>Prerequisite</h3><p>Make sure that you have tensorflow and tflearn installed. If you don’t, please follow these <a href="http://tflearn.org/installation/">instructions</a></p><h3>Problem Statement:</h3><p>To predict the chance of surviving of a passenger in Titanic ship.</p><h3>Problem Solving:</h3><p>1.Load the dataset</p><p>2.Preprocessing</p><p>3.Build the classifier</p><p>4.Training</p><p>5.Make Predictions.</p><h3>Overview:</h3><p>On April 15, 1912, the Titanic sank after colliding with an iceberg, killing 1502 out of 2224 passengers and crew. Although there was some element of luck involved in surviving the sinking, some groups of people were more likely to survive than others, such as women, children, and the upper-class. In this tutorial, we carry an analysis to find out who these people are.</p><h3>Libraries used:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*CCvrX4cUHljV5_XB" /></figure><p>Tensorflow and Tflearn</p><p>TensorFlow is a tool for machine learning. While it contains a wide range of functionality, TensorFlow is mainly designed for deep neural network models.</p><p>TFlearn is a modular and transparent deep learning library built on top of Tensorflow. It was designed to provide a higher-level API to TensorFlow in order to facilitate and speed-up experimentations, while remaining fully transparent and compatible with it.</p><h3>Load the dataset:</h3><p>Let’s take a look at the dataset (TFLearn will automatically download it for you). For each passenger, the following information are provided:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/0*ZroGNbLRF6oHchoK" /></figure><p>Here are some samples extracted from the dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/0*Iz0u1rGRBqMmEqha" /></figure><p>There are 2 <strong>classes</strong> in our task ‘not survived’ (class 0) and ‘survived’ (class 1), and the passengers data have 8<strong> features.</strong></p><p>The Dataset is stored in a csv file, so we can use TFLearn load_csv() function to load the data from file into a python list. We specify ‘target_column’ argument to indicate that our labels (survived or not) are located in the first column (id: 0). The function will return a tuple: (data, labels).</p><pre>from __future__ import print_function<br>import numpy as np<br>import tflearn <br># Download the Titanic dataset<br>from tflearn.datasets import titanic<br>titanic.download_dataset(&#39;titanic_dataset.csv&#39;) <br># Load CSV file, indicate that the first column represents labels<br>from tflearn.data_utils import load_csv<br>data, labels = load_csv(&#39;titanic_dataset.csv&#39;, target_column=0,<br>                        categorical_labels=True, n_classes=2)</pre><h3>Data Preprocessing :</h3><p>Data are given ‘as it’ and need some preprocessing to be ready to be used in our deep neural network classifier.</p><p>First, we will discard the fields that are not likely to help in our analysis. For example, we make the assumption that ‘name’ field will not be very useful in our task, because we estimate that a passenger name and his chance of surviving are not correlated. With such thinking, we discard ‘name’ and ‘ticket’ fields.</p><p>Then, we need to convert all our data to numerical values, because a neural network model can only perform operations over numbers. However, our dataset contains some non numerical values, such as ‘name’ or ‘sex’. Because ‘name’ is discarded, we just need to handle ‘sex’ field. In this simple case, we will just assign ‘0’ to males and ‘1’ to females.</p><p>Here is the preprocessing function:</p><pre># Preprocessing function<br>def preprocess(data, columns_to_ignore):<br>    # Sort by descending id and delete columns<br>    for id in sorted(columns_to_ignore, reverse=True):<br>        [r.pop(id) for r in data]<br>    for i in range(len(data)):<br>      # Converting &#39;sex&#39; field to float (id is 1 after removing labels column)<br>      data[i][1] = 1. if data[i][1] == &#39;female&#39; else 0.<br>    return np.array(data, dtype=np.float32)# Ignore &#39;name&#39; and &#39;ticket&#39; columns (id 1 &amp; 6 of data array)<br>to_ignore=[1, 6]# Preprocess data<br>data = preprocess(data, to_ignore)</pre><h3>Build the classifier:</h3><h3>Deep neural Network:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/243/0*RO_zYt_pTnrYKMTi" /></figure><p>We are building a 3-layers neural network using TFLearn. We need to specify the shape of our input data. In our case, each sample has a total of 6 features and we will process samples per batch to save memory, so our data input shape is [None, 6] (‘None’ stands for an unknown dimension, so we can change the total number of samples that are processed in a batch).</p><pre># Build neural network<br>net = tflearn.input_data(shape=[None, 6])<br>net = tflearn.fully_connected(net, 32)<br>net = tflearn.fully_connected(net, 32)<br>net = tflearn.fully_connected(net, 2, activation=&#39;softmax&#39;)<br>net = tflearn.regression(net)</pre><h3>Training:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/0*BuzDANFdjn7y1bON" /></figure><p>TFLearn provides a model wrapper ‘DNN’ that can automatically performs a neural network classifier tasks, such as training, prediction, save/restore, etc… We will run it for 10 epochs (the network will see all data 10 times) with a batch size of 16.</p><pre># Define model<br>model = tflearn.DNN(net)<br># Start training (apply gradient descent algorithm)<br>model.fit(data, labels, n_epoch=10, batch_size=16, show_metric=True)</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/0*xC0TphlCKUXwr_Pe" /></figure><p>Note:Once the model is trained once,you can save the model with model.save(‘filename’) and load the saved model with model.load(‘filename’)</p><p>Our model finish to train with an overall accuracy around 81%, which means that it can predict the correct outcome (survived or not) for 81% of the total passengers.</p><h3>Making predictions:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/0*wbqKvl6p-Rp9LT7P" /></figure><p>It is time to try out our model. For fun, let’s take Titanic movie protagonists (jack and rose) and calculate their chance of surviving (class 1).</p><pre># Let&#39;s create some data for DiCaprio and Winslet<br>jack = [3, &#39;Jack Dawson&#39;, &#39;male&#39;, 19, 0, 0, &#39;N/A&#39;, 5.0000]<br>rose = [1, &#39;Rose DeWitt Bukater&#39;, &#39;female&#39;, 17, 1, 2, &#39;N/A&#39;, 100.0000]<br># Preprocess data<br>jack, rose = preprocess([jack, rose], to_ignore)<br># Predict surviving chances (class 1 results)<br>pred = model.predict([jack, rose])<br>print(&quot;Jack Surviving Rate:&quot;, pred[0][1])<br>print(&quot;Rose Surviving Rate:&quot;, pred[1][1])</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7RmYve_tJZXA5xo0" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/0*3WrPZA_WU5lKA5fn" /></figure><p>Impressive! Our model accurately predicted the outcome of the movie. Odds were against Jack, but Rose had a high chance of surviving.</p><p>More generally, it can bee seen through this study that women and children passengers from first class have the highest chance of surviving, while third class male passengers have the lowest.</p><h3>Entire code:</h3><pre>from __future__ import print_functionimport numpy as np<br>import tflearn# Download the Titanic dataset<br>from tflearn.datasets import titanic<br>titanic.download_dataset(&#39;titanic_dataset.csv&#39;)# Load CSV file, indicate that the first column represents labels<br>from tflearn.data_utils import load_csv<br>data, labels = load_csv(&#39;titanic_dataset.csv&#39;, target_column=0,<br>                        categorical_labels=True, n_classes=2)<br># Preprocessing function<br>def preprocess(data, columns_to_ignore):<br>    # Sort by descending id and delete columns<br>    for id in sorted(columns_to_ignore, reverse=True):<br>        [r.pop(id) for r in data]<br>    for i in range(len(data)):<br>      # Converting &#39;sex&#39; field to float (id is 1 after removing labels column)<br>      data[i][1] = 1. if data[i][1] == &#39;female&#39; else 0.<br>    return np.array(data, dtype=np.float32)# Ignore &#39;name&#39; and &#39;ticket&#39; columns (id 1 &amp; 6 of data array)<br>to_ignore=[1, 6]# Preprocess data<br>data = preprocess(data, to_ignore)# Build neural network<br>net = tflearn.input_data(shape=[None, 6])<br>net = tflearn.fully_connected(net, 32)<br>net = tflearn.fully_connected(net, 32)<br>net = tflearn.fully_connected(net, 2, activation=&#39;softmax&#39;)<br>net = tflearn.regression(net)# Define model<br>model = tflearn.DNN(net)<br># Start training (apply gradient descent algorithm)<br>model.fit(data, labels, n_epoch=10, batch_size=16, show_metric=True)# Let&#39;s create some data for DiCaprio and Winslet<br>jack = [3, &#39;Jack Dawson&#39;, &#39;male&#39;, 19, 0, 0, &#39;N/A&#39;, 5.0000]<br>rose = [1, &#39;Rose DeWitt Bukater&#39;, &#39;female&#39;, 17, 1, 2, &#39;N/A&#39;, 100.0000]<br># Preprocess data<br>jack, rose = preprocess([jack, rose], to_ignore)<br># Predict surviving chances (class 1 results)<br>pred = model.predict([jack, rose])<br>print(&quot;Jack Surviving Rate:&quot;, pred[0][1])<br>print(&quot;Rose Surviving Rate:&quot;, pred[1][1])</pre><p>Happy coding!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81dae7f1f962" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning-Let’s Get Started]]></title>
            <link>https://medium.com/@jebaseelanravi96/machine-learning-lets-get-started-5fb10f49f892?source=rss-a93a9a4c20f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fb10f49f892</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Jebaseelan Ravi]]></dc:creator>
            <pubDate>Thu, 24 Mar 2022 21:23:59 GMT</pubDate>
            <atom:updated>2022-03-24T21:49:38.097Z</atom:updated>
            <content:encoded><![CDATA[<h3>Machine Learning -Let’s Get Started</h3><p>Machine Learning is not that much difficult to implement in our real life . Actually it is very easy to learn.Though I am not a expert in Machine learning,I would like to share my knowledge.</p><p>Prerequisite:</p><ul><li>Little knowledge in Python.</li><li>Passion to learn ML.</li></ul><p><strong>What is Machine Learning:</strong></p><p><em>Machine learning</em> is an application of artificial intelligence (AI) that provides systems the ability to automatically learn and improve from experience without being explicitly programmed.</p><p>So without taking much of your time,Let’s dive into the problem.</p><p><strong>PROBLEM STATEMENT:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3mHFLSI3VDPxCDUg" /><figcaption>Photo by <a href="https://unsplash.com/@perventuator?utm_source=medium&amp;utm_medium=referral">Bibhash Banerjee</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Create the model the classify the whether the fruit is Apple or Orange.</p><p><strong>PROBLEM SOLVING:</strong></p><p><strong>Steps in Problem Solving:</strong></p><ul><li>Create the Dataset</li><li>Create the Model</li><li>Train the Model</li><li>Make predictions</li></ul><p><strong>1.Create the Dataset:</strong></p><p>Dataset is nothing but the collections of features and the Labels.Features are the input that are necessary to classify the Fruits.Labels are the outputs of the problem(In our problem Apple and Orange are the labels)</p><p><em>Note:More accurate the Dataset is more accurate the predictions .</em></p><p>Dataset for our problem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/0*YPfUx4COrsAPltA4" /></figure><p>For example if the fruit is Smooth and weighs 130g ,it is classified as Apple .In the same way,If the fruit is bumpy and weighs around 170g it is classified as Orange .</p><p>So now we can convert the dataset into the Python 🐍 code.</p><p>Make sure you have python installed</p><pre>features = [[140,’smooth’], [130,’smooth’], [150,’bumpy’], [170, ‘bumpy’]]<br>labels = [‘apple’,’apple’,’orange’,’orange’]</pre><p>Now for calculation we are going to represent the features and labels in the <strong><em>int</em></strong> instead of a <strong><em>string</em></strong>.</p><pre>features = [[140,1], [130,1], [150,0], [170, 0]]<br>labels = [0,0,1,1]</pre><p>In the features,’1′ represents the ‘smooth’ texture sand ‘0’ represents the ‘bumpy’ texture.In the labels ‘0’ represents the fruit ‘Apple’ and ‘1’ represents the fruit ‘Orange’.</p><p><strong>2.Create the Model:</strong></p><p><strong>Decision Trees (DTs)</strong> are a non-parametric supervised learning method. The goal is to create a model that predicts the value of a target variable by learning simple decision rules inferred from the data features.In simple Words ,Decision tree makes the decision based on the input that was provided.</p><p>So now we can create the Model.</p><p>Before creating the model,we should know what is <strong>Sklearn.</strong></p><p>Sklearn is the Open source machine learning library,Which has many Classification ,regression and clustering algorithms built in.In order to solve our problem we can use DecisionTreeClassifier algorithm from the sklearn.</p><pre>pip install sklearn # install sklearn package</pre><pre>from sklearn import tree<br>features = [[140,1], [130,1], [150,0], [170, 0]]<br>labels = [0,0,1,1]<br>clf = tree.DecisionTreeClassifier()</pre><p>At this point,We have just made the model.But it cannot able to predict whether the given fruit is Apple or Orange.If our model has to predict the fruit ,We have to train the model with the Features and the Labels(ie we have to map the corresponding output for the corresponding inputs).In other words,We should teach the model that if the fruit is smooth and weighs 130g ,It is more likely to be ‘Apple’ and the same for the ‘Orange’.</p><p><strong>3.Train the Model:</strong></p><p><em>Note:There is the classifier object called </em><strong><em>fit</em></strong><em> is used to train the model.</em></p><pre>from sklearn import tree<br>features = [[140,1], [130,1], [150,0], [170, 0]]<br>labels = [0,0,1,1]<br>clf = tree.DecisionTreeClassifier()<br>clf = clf.fit(features, labels)<br></pre><p><strong>4.Make Predictions:</strong></p><p>At this point we have a trained classifier and we are ready to test it now. Suppose we want to predict a fruit which weighs 160g and is bumpy.</p><p><em>Note:The classifier object </em><strong><em>predict</em></strong><em> is used to make predictions</em></p><pre>from sklearn import tree<br>features = [[140,1], [130,1], [150,0], [170, 0]]<br>labels = [0,0,1,1]<br>clf = tree.DecisionTreeClassifier()<br>clf = clf.fit(features, labels)<br>print(clf.predict([[160,0]]))</pre><p>The output will be ‘<strong><em>0</em></strong>’ if it’s apple or ‘<strong><em>1</em></strong>’ if it’s a orange.</p><p>Looking at the dataset we can say that the fruit is <strong>Orange</strong> as it’s bumpy and also weighs more relatively. If we run the program we will find out it gives the same result .</p><p>Congrats you made your first Machine Learning Program 🙂</p><p>Happy Coding 😛</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fb10f49f892" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web scraping using Python]]></title>
            <link>https://medium.com/@jebaseelanravi96/web-scraping-using-python-e97f8a6088e0?source=rss-a93a9a4c20f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/e97f8a6088e0</guid>
            <category><![CDATA[web-crawler]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[beautifulsoup]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-scraping]]></category>
            <dc:creator><![CDATA[Jebaseelan Ravi]]></dc:creator>
            <pubDate>Thu, 24 Mar 2022 20:49:43 GMT</pubDate>
            <atom:updated>2022-03-27T22:26:47.787Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>What is web scraping?</strong></h4><p>Web scraping is the process of the extracting the required data from the internet . The tool or program that helps to achieve this is called Web scraper, Web crawlers or Spiders 🕷. I believe developer who builds web spiders are real SpiderMan 😆</p><h4>Why do we need web scraping?</h4><p>It can be used in many use cases such as</p><p>Jobboards such as indeed or glassdoor scrape the Job posting from many employer sites and show it in their sites</p><p>Search Engines such as Google scrapes millions of webpages and index it in databases and provide search solution to their users 👨.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GEU5wZS5NHvqsb595FPfZQ.png" /><figcaption>Web crawling (source google images)</figcaption></figure><h4><strong>What we are going to do?</strong></h4><p><strong><em>Today we are going to build a simple web scraper using python 🐍 to scrape jobs from Apple jobs page 🍎</em></strong></p><p>Target site: <a href="https://jobs.apple.com/en-gb/search">https://jobs.apple.com/en-gb/search</a></p><p>You can use this template to build a web scraper for your dream company to notify you whenever they post a new job</p><p><strong>Data we are going to scrape for each Job Posting:</strong></p><ol><li>Job Title 👷</li><li>Job Department/team 🖥</li><li>Date in which Job is posted 📅</li></ol><p>Enough talking,</p><h3>let’s code !!!! 💻</h3><p>Basically in web scraping we have three parts,</p><ol><li>Getting the content/HTML from the web</li><li>Extracting the data from content/HTML</li><li>Storing the extracted data</li></ol><p>So, inorder to achieve the above we will be using three python libraries</p><ol><li><a href="https://docs.python-requests.org/en/latest/">Requests</a> — To get the HTML content from the web</li><li><a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/">Beautifulsoup</a> — To extract the data from rendered content</li><li>csv — to store the data into CSV file</li></ol><p><strong>Environment setup</strong></p><p>Check if python is installed</p><pre>python -V</pre><p>Install the packages</p><pre>pip install requests<br>pip install beautifulsoup4</pre><p>Let’s go back to step number: 1️⃣ Getting the content/HTML from the web. The request package helps us achieve this by the following code</p><pre>import requests as r</pre><pre># provide the target url<br>resp = r.get(&#39;<a href="https://jobs.apple.com/en-gb/search">https://jobs.apple.com/en-gb/search</a>&#39;)</pre><p>check whether above step is success by printing out the content and status code.</p><pre>print(resp.status_code) # returns 200/302 not 4xx</pre><pre>print(resp.content) # print the HTML content</pre><p>Up to this point we have successfully fetched the content from the internet. The next task is extract the data we need from the content that Job title, job department and date posted 📅. This is where <em>Beautifulsoup</em> magic comes in.</p><p>Beautiful Soup is a library that makes it easy to scrape information ℹ️ from web pages. It sits atop an HTML or XML parser, providing Pythonic idioms for iterating, searching, and modifying the parse tree 🌲.</p><p>Let’s load the HTML content into beautiful soup object using which we can easily parse the HTML and extract the data</p><pre>from bs4 import BeautifulSoup as bs4 # import package</pre><pre>soup = bs4(resp.content, ‘html.parser’) # load the HTML content in parser</pre><p>You can see the HTML content on soup object by printing it</p><pre>print(soup.prettify())</pre><p>Now it is time to extract the data we needed from the HTML.</p><p>Beautiful soup object has a method soup.find_all() which extracts all matched elements from webpage . For example soup.find_all(&#39;a&#39;) extracts all anchor tags/element with href/link in the webpage.</p><pre>print(soup.find_all(&#39;a&#39;)[-1:])</pre><pre># Result</pre><pre>[&lt;a class=&quot;ac-gf-footer-legal-link&quot; data-analytics-title=&quot;use of cookies&quot; href=&quot;<a href="https://www.apple.com/legal/privacy/en-ww/cookies/">https://www.apple.com/legal/privacy/en-ww/cookies/</a>&quot;&gt;Use of Cookies&lt;/a&gt;]</pre><p>`soup.find_all` expression to extract job_title <strong>elements</strong> from the webpage is</p><pre>print(soup.find_all(‘a’,class_=”table—-advanced-search__title”)) #returns a list of HTML elements</pre><p>The above expression is pretty explanatory. If you go to the <a href="https://jobs.apple.com/en-gb/search">webpage</a> , hover over any one of the Job title , right click and then click inspect. You can see the element in which Job title is &lt;a&gt; tag with class name as `table — advanced-search__title`</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8PzPQbIXhiexrKdViPnaVg.png" /><figcaption>source: Author image</figcaption></figure><pre>&lt;a href=&quot;/en-gb/details/200314120/in-store-leader?team=APPST&quot; class=&quot;table--advanced-search__title&quot; id=&quot;jotTitle_PIPE-200314120&quot;&gt;IN-Store Leader&lt;/a&gt;</pre><p>Above is the Job title HTML element and <em>IN-Store Leader </em>is the Job title text</p><p>Now we need to extract the text(actual job title text) from those elements(job title HTML element)</p><pre># code to extract Job titles</pre><pre>job_titles =[]<br>for tag in soup.find_all(‘a’,class_=”table--advanced-search__title”):<br>    print(tag.text) # extract the text from the element <br>    job_titles.append(tag.text) # append to the list of title</pre><p>Using the same way we can write for date_posted and department</p><pre># code to extract date_posted<br></pre><pre>job_dates = []<br>for tag in soup.find_all(‘span’,class_=”table--advanced-search__date”):<br>    print(tag.text) # print the date_posted<br>    job_dates.append(tag.text)</pre><pre># code to extract job_dept</pre><pre>job_dept = []<br>for tag in soup.find_all(‘span’,class_=”table--advanced-search__role”):<br>    print(tag.text) # print the date_posted<br>    job_dept.append(tag.text)</pre><p>Finally we have extracted all the data we needed, now it is time to save the data into file or Database for your reference. Considering the time ⏲, I will save to CSV file</p><p>See the Job we have extracted.</p><pre>for job in zip(job_titles,job_dates,job_dept):<br>    print(job)</pre><p>Save to CSV file 📁</p><pre>import csv</pre><pre>with open(&#39;jobs.csv&#39;,&#39;w&#39;,newline=&#39;\n&#39;) as csvfile:<br>    for job in zip(job_titles,job_dates,job_dept):<br>    writer = csv.writer(csvfile,delimiter=&#39;,&#39;)<br>    writer.writerow(job)</pre><p>That’s it, now you have all your jobs in csv file. Using the same method you can scrape the job from your dream company site.</p><p>Comple code</p><pre>import requests as r<br>from bs4 import BeautifulSoup as bs4 # import package<br>import csv</pre><pre># provide the target url<br>resp = r.get(&#39;<a href="https://jobs.apple.com/en-gb/search">https://jobs.apple.com/en-gb/search</a>&#39;)<br>print(resp.status_code)<br></pre><pre>soup = bs4(resp.content, ‘html.parser’) # load the HTML content in parser</pre><pre># code to extract job_titles</pre><pre>job_titles =[]<br>for tag in soup.find_all(‘a’,class_=”table--advanced-search__title”):<br>    print(tag.text) # extract the text from the element <br>    job_titles.append(tag.text) # append to the list of title</pre><pre># code to extract date_posted</pre><pre>job_dates = []<br>for tag in soup.find_all(‘span’,class_=”table--advanced-search__date”):<br>    print(tag.text) # print the date_posted<br>    job_dates.append(tag.text)</pre><pre># code to extract job_dept</pre><pre>job_dept = []<br>for tag in soup.find_all(‘span’,class_=”table--advanced-search__role”):<br>    print(tag.text) # print the date_posted<br>    job_dept.append(tag.text)</pre><pre># write to csv file<br>with open(&#39;jobs.csv&#39;,&#39;w&#39;,newline=&#39;\n&#39;) as csvfile:<br>    for job in zip(job_titles,job_dates,job_dept):<br>        writer = csv.writer(csvfile,delimiter=&#39;,&#39;)<br>        writer.writerow(job)</pre><h3>Next Steps</h3><p>This is most basic form of web scraping. In the next blogs I will teach you how to scrape Job posting from all pages of the sites. Some sites has 20 jobs per pages and 5 pages , so totally 100 jobs. So your crawlers needs to follow the page 1 , page 2 links and crawl recursively.</p><p>Happy Crawling 🕷.</p><p>Please leave a comment if you have some queries 🙏</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e97f8a6088e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning — Titanic Survival Prediction]]></title>
            <link>https://medium.com/@jebaseelanravi96/machine-learning-series-2-jack-or-rose-bb2f3900c0b5?source=rss-a93a9a4c20f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb2f3900c0b5</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Jebaseelan Ravi]]></dc:creator>
            <pubDate>Fri, 01 Mar 2019 18:19:20 GMT</pubDate>
            <atom:updated>2022-03-27T22:20:08.582Z</atom:updated>
            <content:encoded><![CDATA[<h3>Machine Learning — Titanic Survival Prediction</h3><h3>Hi everyone,</h3><p>In this tutorial, you will learn to use TFLearn and TensorFlow to estimate the surviving chance of Titanic passengers using their personal information (such as gender, age, etc…). To tackle this classic machine learning task, we are going to build a deep neural network classifier.</p><h3>Prerequisite</h3><p>Make sure that you have tensorflow and tflearn installed. If you don’t, please follow these <a href="http://tflearn.org/installation/">instructions</a></p><h3>Problem Statement:</h3><p>To predict the chance of surviving of a passenger in Titanic ship.</p><h3>Problem Solving:</h3><p>1.Load the dataset</p><p>2.Preprocessing</p><p>3.Build the classifier</p><p>4.Training</p><p>5.Make Predictions.</p><h3>Overview:</h3><p>On April 15, 1912, the Titanic sank after colliding with an iceberg, killing 1502 out of 2224 passengers and crew. Although there was some element of luck involved in surviving the sinking, some groups of people were more likely to survive than others, such as women, children, and the upper-class. In this tutorial, we carry an analysis to find out who these people are.</p><h3>Libraries used:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*zFamNavFI_R_gzeA" /></figure><p>Tensorflow and Tflearn</p><p>TensorFlow is a tool for machine learning. While it contains a wide range of functionality, TensorFlow is mainly designed for deep neural network models.</p><p>TFlearn is a modular and transparent deep learning library built on top of Tensorflow. It was designed to provide a higher-level API to TensorFlow in order to facilitate and speed-up experimentations, while remaining fully transparent and compatible with it.</p><h3>Load the dataset:</h3><p>Let’s take a look at the dataset (TFLearn will automatically download it for you). For each passenger, the following information are provided:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/0*pElv7UQvogqyFhN3" /></figure><p>Here are some samples extracted from the dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/0*KQEBIQxfMZQ2I_Al" /></figure><p>There are 2 <strong>classes</strong> in our task ‘not survived’ (class 0) and ‘survived’ (class 1), and the passengers data have 8<strong> features.</strong></p><p>The Dataset is stored in a csv file, so we can use TFLearn load_csv() function to load the data from file into a python list. We specify ‘target_column’ argument to indicate that our labels (survived or not) are located in the first column (id: 0). The function will return a tuple: (data, labels).</p><pre>from __future__ import print_function</pre><pre>import numpy as np<br>import tflearn</pre><pre># Download the Titanic dataset<br>from tflearn.datasets import titanic<br>titanic.download_dataset(&#39;titanic_dataset.csv&#39;)</pre><pre># Load CSV file, indicate that the first column represents labels<br>from tflearn.data_utils import load_csv<br>data, labels = load_csv(&#39;titanic_dataset.csv&#39;, target_column=0,<br>                        categorical_labels=True, n_classes=2)</pre><h3>Data Preprocessing :</h3><p>Data are given ‘as it’ and need some preprocessing to be ready to be used in our deep neural network classifier.</p><p>First, we will discard the fields that are not likely to help in our analysis. For example, we make the assumption that ‘name’ field will not be very useful in our task, because we estimate that a passenger name and his chance of surviving are not correlated. With such thinking, we discard ‘name’ and ‘ticket’ fields.</p><p>Then, we need to convert all our data to numerical values, because a neural network model can only perform operations over numbers. However, our dataset contains some non numerical values, such as ‘name’ or ‘sex’. Because ‘name’ is discarded, we just need to handle ‘sex’ field. In this simple case, we will just assign ‘0’ to males and ‘1’ to females.</p><p>Here is the preprocessing function:</p><pre># Preprocessing function<br>def preprocess(data, columns_to_ignore):<br>    # Sort by descending id and delete columns<br>    for id in sorted(columns_to_ignore, reverse=True):<br>        [r.pop(id) for r in data]<br>    for i in range(len(data)):<br>      # Converting &#39;sex&#39; field to float (id is 1 after removing labels column)<br>      data[i][1] = 1. if data[i][1] == &#39;female&#39; else 0.<br>    return np.array(data, dtype=np.float32)</pre><pre># Ignore &#39;name&#39; and &#39;ticket&#39; columns (id 1 &amp; 6 of data array)<br>to_ignore=[1, 6]</pre><pre># Preprocess data<br>data = preprocess(data, to_ignore)</pre><h3>Build the classifier:</h3><h4>Deep neural Network:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/243/0*onLjyJEgWrmyCDLS" /></figure><p>We are building a 3-layers neural network using TFLearn. We need to specify the shape of our input data. In our case, each sample has a total of 6 features and we will process samples per batch to save memory, so our data input shape is [None, 6] (‘None’ stands for an unknown dimension, so we can change the total number of samples that are processed in a batch).</p><pre># Build neural network<br>net = tflearn.input_data(shape=[None, 6])<br>net = tflearn.fully_connected(net, 32)<br>net = tflearn.fully_connected(net, 32)<br>net = tflearn.fully_connected(net, 2, activation=&#39;softmax&#39;)<br>net = tflearn.regression(net)</pre><h3>Training:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/0*c7Jp8m-fsmzWWhJ7" /></figure><p>TFLearn provides a model wrapper ‘DNN’ that can automatically performs a neural network classifier tasks, such as training, prediction, save/restore, etc… We will run it for 10 epochs (the network will see all data 10 times) with a batch size of 16.</p><pre># Define model<br>model = tflearn.DNN(net)<br># Start training (apply gradient descent algorithm)<br>model.fit(data, labels, n_epoch=10, batch_size=16, show_metric=True)</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/0*o-6I9Rv2G8Jp18QZ" /></figure><p>Note:Once the model is trained once,you can save the model with model.save(‘filename’) and load the saved model with model.load(‘filename’)</p><p>Our model finish to train with an overall accuracy around 81%, which means that it can predict the correct outcome (survived or not) for 81% of the total passengers.</p><h3>Making predictions:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/0*ptwch0GYoOUvg_DW" /></figure><p>It is time to try out our model. For fun, let’s take Titanic movie protagonists (jack and rose) and calculate their chance of surviving (class 1).</p><pre># Let&#39;s create some data for DiCaprio and Winslet<br>jack = [3, &#39;Jack Dawson&#39;, &#39;male&#39;, 19, 0, 0, &#39;N/A&#39;, 5.0000]<br>rose = [1, &#39;Rose DeWitt Bukater&#39;, &#39;female&#39;, 17, 1, 2, &#39;N/A&#39;, 100.0000]<br># Preprocess data<br>jack, rose = preprocess([jack, rose], to_ignore)<br># Predict surviving chances (class 1 results)<br>pred = model.predict([jack, rose])<br>print(&quot;Jack Surviving Rate:&quot;, pred[0][1])<br>print(&quot;Rose Surviving Rate:&quot;, pred[1][1])</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hz8_YpKBebBEn-hv" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/0*FiW3O8QjzIcZ7Muv" /></figure><p>Impressive! Our model accurately predicted the outcome of the movie. Odds were against Jack, but Rose had a high chance of surviving.</p><p>More generally, it can bee seen through this study that women and children passengers from first class have the highest chance of surviving, while third class male passengers have the lowest.</p><h4>Entire code:</h4><pre>from __future__ import print_function</pre><pre>import numpy as np<br>import tflearn</pre><pre># Download the Titanic dataset<br>from tflearn.datasets import titanic<br>titanic.download_dataset(&#39;titanic_dataset.csv&#39;)</pre><pre># Load CSV file, indicate that the first column represents labels<br>from tflearn.data_utils import load_csv<br>data, labels = load_csv(&#39;titanic_dataset.csv&#39;, target_column=0,<br>                        categorical_labels=True, n_classes=2)<br></pre><pre># Preprocessing function<br>def preprocess(data, columns_to_ignore):<br>    # Sort by descending id and delete columns<br>    for id in sorted(columns_to_ignore, reverse=True):<br>        [r.pop(id) for r in data]<br>    for i in range(len(data)):<br>      # Converting &#39;sex&#39; field to float (id is 1 after removing labels column)<br>      data[i][1] = 1. if data[i][1] == &#39;female&#39; else 0.<br>    return np.array(data, dtype=np.float32)</pre><pre># Ignore &#39;name&#39; and &#39;ticket&#39; columns (id 1 &amp; 6 of data array)<br>to_ignore=[1, 6]</pre><pre># Preprocess data<br>data = preprocess(data, to_ignore)</pre><pre># Build neural network<br>net = tflearn.input_data(shape=[None, 6])<br>net = tflearn.fully_connected(net, 32)<br>net = tflearn.fully_connected(net, 32)<br>net = tflearn.fully_connected(net, 2, activation=&#39;softmax&#39;)<br>net = tflearn.regression(net)</pre><pre># Define model<br>model = tflearn.DNN(net)<br># Start training (apply gradient descent algorithm)<br>model.fit(data, labels, n_epoch=10, batch_size=16, show_metric=True)</pre><pre># Let&#39;s create some data for DiCaprio and Winslet<br>jack = [3, &#39;Jack Dawson&#39;, &#39;male&#39;, 19, 0, 0, &#39;N/A&#39;, 5.0000]<br>rose = [1, &#39;Rose DeWitt Bukater&#39;, &#39;female&#39;, 17, 1, 2, &#39;N/A&#39;, 100.0000]<br># Preprocess data<br>jack, rose = preprocess([jack, rose], to_ignore)<br># Predict surviving chances (class 1 results)<br>pred = model.predict([jack, rose])<br>print(&quot;Jack Surviving Rate:&quot;, pred[0][1])<br>print(&quot;Rose Surviving Rate:&quot;, pred[1][1])</pre><p>Happy coding!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb2f3900c0b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine learning-Iris classification]]></title>
            <link>https://medium.com/@jebaseelanravi96/machine-learning-iris-classification-33aa18a4a983?source=rss-a93a9a4c20f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/33aa18a4a983</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[iris-classification]]></category>
            <category><![CDATA[sklearn]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Jebaseelan Ravi]]></dc:creator>
            <pubDate>Wed, 01 Aug 2018 04:36:01 GMT</pubDate>
            <atom:updated>2022-03-24T21:42:08.523Z</atom:updated>
            <content:encoded><![CDATA[<p>Hai Everyone,</p><p>Welcome to the part two of the machine learning tutorial.Today we are going to develop the model that is going to classify the iris flowers for us.Before we get started to the problem I recommend you to go through the <a href="https://medium.com/@jebaseelanravi96/machine-learning-lets-get-started-5fb10f49f892">first tutorial</a>, If you are not aware of it.In the first tutorial ,We built the model that can classify whether the given fruit is apple or orange.</p><p>As far as this tutorial is concerned, It is much more similar to the first tutorial.But here I will introduce you to the some inbuilt dataset and how to perform various operations on it.</p><p>Let’s get started.</p><h3>Problem Statement:</h3><p>Create the model that can classify the different species of the Iris flower.</p><h3>Problem solving:</h3><ol><li>create the dataset.</li><li>Build the model</li><li>Train the model</li><li>Make predictions.</li></ol><h3>Iris Flower:</h3><p>Iris is the family in the flower which contains the several species such as the <em>iris.setosa,iris.versicolor,iris.virginica,etc.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*Uw37vrrKzeEWahdB" /></figure><h3>1.Create the datasets:</h3><p>Inorder to classify the different species of the Iris,We should prepare the datasets with features and labels.But <strong>sklearn </strong>comes with the inbuilt datasets for the iris classification problem.</p><p>Let us first understand the datasets</p><p>The data set consists of:</p><ul><li><strong>150 samples</strong></li><li><strong>3 labels: species of Iris (<em>Iris setosa, Iris virginica</em> and <em>Iris versicolor</em>)</strong></li><li><strong>4 features: Sepal length,Sepal width,Petal length,Petal Width in cm</strong></li></ul><p>Scikit learn only works if data is stored as numeric data, irrespective of it being a regression or a classification problem. It also requires the arrays to be stored at numpy arrays for optimization. Since, this dataset is loaded from scikit learn, everything is appropriately formatted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7H_gF1KnslexnJ3s" /></figure><p>So now let us write the python code to load the Iris dataset.</p><pre>from  sklearn import  datasets<br>iris=datasets.load_iris()</pre><p>Assign the data and target to separate variables.</p><pre>x=iris.data<br>y=iris.target</pre><p>x contains the features and y contains the labels</p><h3>Splitting the dataset;</h3><p>Since our process involve training and testing ,We should split our dataset.It can be executed by the following code</p><pre>from sklearn.model_selection import train_test_split<br>x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=.5)</pre><p>x_train contains the training features</p><p>x_test contains the testing features</p><p>y_train contains the training label</p><p>y_test contains the testing labels</p><h3>2.Build the model</h3><p>We can use any classification algorithm to solve the problem.we have solved the previous problem with decision tree algorithm,I will go with that.</p><pre>from sklearn import tree<br>classifier=tree.DecisionTreeClassifier()</pre><p>The above code will create the empty model. Inorder to provide the operations to the model we should train them.</p><p><strong><em>Note</em></strong><em>:We can also use KNeighborsClassifier(efficiency is higher)</em></p><pre>from sklearn import neighbors<br>classifier=neighbors.KNeighborsClassifier()</pre><p>At this point,We have just made the model.But it cannot able to predict whether the given flower belongs to which species of Iris .If our model has to predict the flower,We have to train the model with the Features and the Labels.</p><h3>3.Train the Model.</h3><p>We can train the model with <strong><em>fit </em></strong>function.</p><pre>classifier.fit(x_train,y_train)</pre><p>Now the model is ready to make predictions</p><h3>4.Make predictions:</h3><p>Predictions can be done with <strong><em>predict</em></strong><em> </em>function</p><pre>predictions=classifier.predict(x_test)</pre><p>these predictions can be matched with the expected output to measure the accuracy value.</p><pre>from sklearn.metrics import accuracy_score<br>print(accuracy_score(y_test,predictions))</pre><h3>Full code:</h3><pre>from  sklearn import  datasets<br>iris=datasets.load_iris()<br>x=iris.data<br>y=iris.target<br>from sklearn.model_selection import train_test_split<br>x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=.5)<br>from sklearn import tree<br>classifier=tree.DecisionTreeClassifier()<br>classifier.fit(x_train,y_train)<br>predictions=classifier.predict(x_test)<br>from sklearn.metrics import accuracy_score<br>print(accuracy_score(y_test,predictions))</pre><h3>Output:</h3><p>D:\iris_classification&gt;python classifier.py<br>0.96</p><p>So the accuracy is 96%</p><p>Congo..we have made it!!!!!!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33aa18a4a983" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>