<?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 Imam Muhajir on Medium]]></title>
        <description><![CDATA[Stories by Imam Muhajir on Medium]]></description>
        <link>https://medium.com/@muhajir-29?source=rss-2a3bbaeb7847------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*83mGPRlNeQ_-zWvVTY1jCg.jpeg</url>
            <title>Stories by Imam Muhajir on Medium</title>
            <link>https://medium.com/@muhajir-29?source=rss-2a3bbaeb7847------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 13:06:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@muhajir-29/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[Accelerate Your Data Processing: Building a Parallel System with Dask]]></title>
            <link>https://medium.com/analytics-vidhya/accelerate-your-data-processing-building-a-parallel-system-with-dask-bd40ac33f5e7?source=rss-2a3bbaeb7847------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd40ac33f5e7</guid>
            <category><![CDATA[data-engineer]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[dask]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Imam Muhajir]]></dc:creator>
            <pubDate>Tue, 22 Oct 2024 08:53:04 GMT</pubDate>
            <atom:updated>2024-10-22T08:58:52.512Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gFLdY30F31dFZEQL" /><figcaption>Photo by <a href="https://unsplash.com/@paulius005?utm_source=medium&amp;utm_medium=referral">Paulius Dragunas</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>When i needed faster data processing and the ability to handle large dataset, one of the best solution is parallel computing. Hovewer, as we know, setting up a parallel computing system can be highly complex and challenging. It involves a lot of configurations, especially when working with multiple servers, which can make the process overwhelming.</p><p>Due to these challengers, I found an alternative solution that would allow me to manage large-scale data quickly but with simpler installation and setup configuration. That solution is Dask Python. Dask is flexible parallel computing library in python that helps scale workloads across multiple servers or machines. It provides advanced parallelism for analytics by enabling distributed computing on large dataset that not fit in memory. Dask integrated seamlessly with python standard librarie like Pandas, Number, Scikit-learn and other, making easy to scale out your workloads without needing to completely rewrite code.</p><p><strong>Objective: Designing a Distributed System Infrastructure</strong></p><ul><li>Designing a Parellel System Infrastructure</li><li>Understand to Install Dask Python as a Parallel Computing System</li><li>Understand to Mount a Folder on Linux Using NFS</li></ul><h3>EXPLANATION</h3><p>In this discussion, we will simulate the installation of Dask Python across three different servers, with the following setup: one Dask scheduler and two Dask workers. The server configuration is as follows:</p><ul><li>127.0.0.1 → Dask Scheduler</li><li>127.0.0.2 → Dask Worker</li><li>127.0.0.3 → Dask Worker</li></ul><p>This setup will allow us to distribute tasks across multiple machines, with the scheduler managing the overall coordination and the workers executing the tasks in parallel. We will walk through the installation process on each server, configure them to work together, and demonstrate how Dask can handle parallel processing in this multi-server environment.</p><h3>Setting Up a Shared Folder Using NFS (Network File System)</h3><p>This guide walks you through configuring a folder to be shared across multiple servers using NFS. We’ll configure one server (127.0.0.1) as the NFS server, which will share the folder, and two client servers (127.0.0.2 and 127.0.0.3) that will mount and access the shared folder.</p><h4><strong>Configuration on the NFS Server (127.0.0.1)</strong></h4><ol><li>Install NFS Server</li></ol><p>First, update the package list and install the NFS server on the machine that will be sharing the folder.</p><pre>sudo apt update<br>sudo apt install nfs-kernel-server</pre><p>2. Create the Folder to Share</p><p>Next, create the directory that you want to share with the clients and set the appropriate permissions.</p><pre>sudo mkdir -p /shared/folder<br>sudo chown nobody:nogroup /shared/folder</pre><p>3. Edit the NFS Export Configuration</p><p>Open the /etc/exports file and add the following configuration to specify which clients can access the shared folder.</p><pre>sudo nano /etc/exports</pre><p>Add this line:</p><pre>/shared/folder 127.0.0.2(rw,sync,no_subtree_check) 127.0.0.3(rw,sync,no_subtree_check)</pre><p>This line allows the clients with IP addresses 127.0.0.2 and 127.0.0.3 to read and write to the shared folder.</p><p>4. Restart the NFS Server and Allow NFS Firewall</p><p>After configuring the exports, restart the NFS service to apply the changes</p><pre>sudo exportfs -a<br>sudo systemctl restart nfs-kernel-server</pre><p>Ensure that the firewall on the NFS server allows NFS traffic. Run the following command to allow access:</p><pre>sudo ufw allow from 127.0.0.1 to any port nfs</pre><h4><strong>Configuration on the NFS Clients (127.0.0.2 and 127.0.0.3)</strong></h4><ol><li>Install NFS Client</li></ol><p>On each client machine, install the NFS client package to enable mounting of the shared folder.</p><pre>sudo apt update<br>sudo apt install nfs-common</pre><p>2. Create a Mount Point</p><p>Create the directory where the shared folder from the NFS server will be mounted.</p><pre>sudo mkdir -p /shared/folder</pre><p>3. Mount the Shared Folder</p><p>Mount the shared folder from the NFS server (127.0.0.1) to the local mount point on each client.</p><pre>sudo mount 127.0.0.1:/shared/folder /shared/folder</pre><p>After mounting, check that the folder has been successfully mounted and that the shared data is accessible.</p><pre>ls /shared/folder</pre><h3>Step-by-Step Guide to Install Dask Python</h3><p>To set up Dask across multiple servers, it’s crucial to ensure that Python and all related packages are the same version on each server. This guide outlines how to prepare the system, install Python 3.10.13 from source, create a virtual environment, and install Dask on three servers (127.0.0.1, 127.0.0.2, and 127.0.0.3).</p><ol><li><strong>Preparation for Installation</strong></li></ol><p>First, update your package manager and install the necessary dependencies for compiling Python from source:</p><pre>sudo apt update<br>sudo apt-get install openssl make gcc<br>sudo apt-get install tk-dev<br>sudo apt-get install build-essential libbz2-dev libssl-dev libffi-dev libsqlite3-dev libgdbm-dev zlib1g-dev liblzma-dev libreadline-dev libncurses5-dev libxml2-dev libxmlsec1-dev libjpeg-dev libpng-dev</pre><p>These packages are required to ensure Python is built correctly with all necessary components.</p><p><strong>2. Install Python from Source</strong></p><p>Next, download and install Python 3.10.13 from source to ensure all servers are using the same version.</p><pre>cd /opt<br>sudo wget https://www.python.org/ftp/python/3.10.13/Python-3.10.13.tgz<br>sudo tar xzvf Python-3.10.13.tgz</pre><p>Change to the Python directory and build it:</p><pre>cd Python-3.10.13<br>sudo ./configure<br>sudo make<br>sudo make install</pre><p>After installation, create a symbolic link to ensure the system uses this version of Python:</p><pre>sudo ln -fs /opt/Python-3.10.13/python /usr/bin/python3.10</pre><p>Verify the installation:</p><pre>python3.10 --version</pre><p>You should see Python 3.10.13 as the output.</p><p><strong>3. Set Up Dask in a Virtual Environment</strong></p><p>Create a virtual environment for your Dask installation. First, install the virtualenv package if it’s not already installed:</p><pre>sudo apt install python3-virtualenv</pre><p>Create a directory for Dask and set up a virtual environment:</p><pre>mkdir -p /shared/folder/dask<br>cd /shared/folder/dask<br>virtualenv dask_env</pre><p>Activate the virtual environment:</p><pre>source dask_env/bin/activate</pre><p><strong>4. Create </strong><strong>requirements.txt and Install Packages</strong></p><p>Create a requirements.txt file to specify the necessary packages for Dask:</p><pre>nano requirements.txt</pre><p>Add the following lines to the file:</p><pre>numpy==1.26.4<br>pandas==2.0.0<br>dask[complete]==2024.9.0</pre><p>Install the packages using pip:</p><pre>pip install -r requirements.txt</pre><p>Check the Dask version to verify the installation:</p><pre>dask --version</pre><p><strong>5. Repeat on Other Servers</strong></p><p>Repeat the above steps for all servers (127.0.0.1, 127.0.0.2, and 127.0.0.3) to ensure consistency across the distributed environment.</p><h3>Setting Up Dask Distributed System Using Systemd</h3><p>This guide explains how to configure a distributed Dask setup across multiple servers, using systemd to manage the Dask scheduler and workers. By using systemd, we can ensure that the services run in the background and automatically restart if they fail.</p><h4>Set Up Dask Scheduler</h4><p>First, we will set up the Dask scheduler. The Dask scheduler coordinates tasks across the worker nodes.</p><ol><li><strong>Run the Dask Scheduler</strong></li></ol><p>Start by manually running the Dask scheduler:</p><pre>dask scheduler --host 127.0.0.1</pre><p>This will start the scheduler on the specified IP address (127.0.0.1 in this case).</p><p><strong>Expected Output:</strong></p><p>Once the scheduler starts, you should see output confirming that the Dask scheduler is running, with information about the dashboard and the scheduler’s address. If no errors appear, you can proceed to the next step.</p><p>To stop the running process and set it up as a systemd service, press:</p><p><strong>CTRL + C</strong></p><p><strong>2. Create a Dask Scheduler Systemd Service</strong></p><p>We will now automate the scheduler startup by creating a systemd service.</p><pre>sudo nano /etc/systemd/system/dask-scheduler.service</pre><p>Add the following content to the file:</p><pre>[Unit]<br>Description=Dask Scheduler<br>After=network.target<br><br>[Service]<br>Type=simple<br>User=your_username<br>WorkingDirectory=/shared/folder/dask<br><br># Command to activate the virtual environment and start the Dask scheduler<br>ExecStart=/bin/bash -c &#39;source /shared/folder/dask/dask_env/bin/activate &amp;&amp; dask scheduler --host 127.0.0.1&#39;<br><br># Restart the service automatically if it crashes<br>Restart=on-failure<br><br># Log output and error to systemd journal<br>StandardOutput=journal<br>StandardError=journal<br><br>[Install]<br>WantedBy=multi-user.target</pre><p>Replace your_username with the username you use on your server.</p><p><strong>3. Enable and Start the Scheduler Service</strong></p><p>Reload systemd to recognize the new service, enable it to start at boot, and then start the scheduler:</p><pre>sudo systemctl daemon-reload<br>sudo systemctl enable dask-scheduler<br>sudo systemctl start dask-scheduler</pre><p>Check the status of the Dask scheduler:</p><pre>sudo systemctl status dask-scheduler</pre><h4>Set Up Dask Worker</h4><p>Now, we will configure the Dask workers to connect to the scheduler. The workers perform the actual computation.</p><ol><li><strong>Run the Dask Worker</strong></li></ol><p>Start by manually running the Dask worker:</p><pre>dask worker 127.0.0.1:8786</pre><p>This command connects the worker to the scheduler running at 127.0.0.1 on port 8786.</p><h4>Expected Output:</h4><p>The output should show that the worker successfully connected to the scheduler. If no errors are encountered, proceed to the next step.</p><p>To stop the running process and set it up as a systemd service, press:</p><p><strong>CTRL + C</strong></p><p><strong>2. Create a Dask Worker Systemd Service</strong></p><p>Now, we will automate the worker startup by creating a systemd service for the Dask worker:</p><pre>sudo nano /etc/systemd/system/dask-worker.service</pre><p>Add the following content to the file:</p><pre>[Unit]<br>Description=Dask Worker<br>After=network.target<br><br>[Service]<br>Type=simple<br>User=your_username<br>WorkingDirectory=/shared/folder/dask<br><br># Command to activate the virtual environment and start the Dask worker<br>ExecStart=/bin/bash -c &#39;source /shared/folder/dask/dask_env/bin/activate &amp;&amp; dask worker 127.0.0.1:8786 --nthreads 96 --memory-limit 500GB&#39;<br><br># Restart the service automatically if it crashes<br>Restart=on-failure<br><br># Log output and error to systemd journal<br>StandardOutput=journal<br>StandardError=journal<br><br>[Install]<br>WantedBy=multi-user.target</pre><p>Replace your_username with your server’s username.</p><p>Reload systemd to recognize the new service, enable it to start at boot, and then start the worker:</p><pre>sudo systemctl daemon-reload<br>sudo systemctl enable dask-worker<br>sudo systemctl start dask-worker</pre><p>Check the status of the Dask worker:</p><pre>sudo systemctl status dask-worker</pre><p>Repeat the above steps for servers ( 127.0.0.2, and 127.0.0.3to ensure consistency across the distributed environment.</p><h3><strong>Testing the Dask Distributed Setup</strong></h3><p>To test your distributed Dask setup, we will create a simple Python script that connects to the Dask scheduler, performs some basic computations, and returns the result.</p><p><strong>1. Create a Python File for Testing</strong></p><p>Create a file named testing.py in your project directory:</p><pre>nano testing.py</pre><p><strong>2. Add the Following Code to </strong><strong>testing.py</strong></p><pre>from dask.distributed import Client<br>import dask.array as da<br><br># Connect to the Dask scheduler<br>client = Client(&#39;10.70.200.2:8786&#39;)<br><br># Print cluster information<br>print(client)<br><br># Example computation: Create a large Dask array and compute the sum<br>array = da.random.random((10000, 10000), chunks=(1000, 1000))<br>result = array.sum()<br><br># Submit computation to the cluster<br>print(&quot;Submitting task...&quot;)<br>result_computed = result.compute()<br>print(&quot;Computation result:&quot;, result_computed)</pre><p>In this script:</p><ul><li>We first connect to the Dask scheduler using Client(&#39;10.70.200.2:8786&#39;). Replace 10.70.200.2 with your scheduler’s actual IP address.</li><li>We then print information about the connected Dask cluster.</li><li>Next, we create a large random Dask array and calculate the sum of its elements.</li><li>The computation is submitted to the cluster using result.compute(), and the result is printed.</li></ul><p><strong>3. Run the Script</strong></p><p>Activate your Dask environment and run the testing.py script:</p><pre>source /shared/folder/dask/dask_env/bin/activate<br>python testing.py</pre><p>4. Verify Output</p><p>If everything is set up correctly, the script will:</p><ol><li>Print information about the Dask cluster.</li><li>Submit the computation to the workers.</li><li>Return the computed result of the sum.</li></ol><p>If you see the result without any errors, congratulations! You have successfully set up a distributed processing system using Dask Python.</p><h3>Conclusion</h3><p>In conclusion, setting up a distributed computing environment using Dask Python offers a powerful and efficient solution for processing large datasets. Through a straightforward installation process and the use of a scheduler and worker nodes, Dask enables users to leverage parallel computing, significantly improving data processing speeds.</p><p>By following the outlined steps, including the installation of necessary dependencies, configuration of NFS for data sharing, and the setup of Dask scheduler and workers, you have established a robust infrastructure capable of handling complex computations. The successful execution of the testing.py script demonstrates the effectiveness of this setup, confirming that tasks can be distributed and processed across multiple servers seamlessly.</p><p>This distributed system not only enhances performance but also simplifies the management of resources, making it an excellent choice for data engineers and analysts dealing with high-volume data processing needs. As you continue to explore Dask’s capabilities, you can further optimize your workflows and expand your distributed architecture to meet the growing demands of data-driven applications.</p><p>Visit my website <a href="https://imammuhajir.vercel.app/">ImamMuhajir</a> to discover more resources, tutorials, and insights related to data engineering.</p><p>I invite you to connect with me for collaboration opportunities, discussions, or if you have any questions about implementing Dask in your projects. Let’s leverage the power of data together. <br><a href="https://www.linkedin.com/in/imammuhajir92/">MyLinkend</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd40ac33f5e7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/accelerate-your-data-processing-building-a-parallel-system-with-dask-bd40ac33f5e7">Accelerate Your Data Processing: Building a Parallel System with Dask</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Engineers, Data Analysts, Data Scientist, Business Analysts, and Business Intelligence Role.]]></title>
            <link>https://medium.com/analytics-vidhya/data-engineers-data-analysts-data-scientist-business-analysts-and-business-intelligence-role-5bc4ed65c150?source=rss-2a3bbaeb7847------2</link>
            <guid isPermaLink="false">https://medium.com/p/5bc4ed65c150</guid>
            <category><![CDATA[insights]]></category>
            <category><![CDATA[analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[bussiness]]></category>
            <dc:creator><![CDATA[Imam Muhajir]]></dc:creator>
            <pubDate>Thu, 28 Oct 2021 14:23:51 GMT</pubDate>
            <atom:updated>2021-11-30T06:29:58.656Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U6CDgIAMt2l2vDoFqhwv6A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@goumbik?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Lukas Blazek</a> on <a href="https://unsplash.com/s/photos/data?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>in this article we are going to look at the role Data Engineers, Data Analysts, Data Scientists, Business Analysts, and Business Intelligence play in helping organizations into actionable insights.</p><h3>Data Engineers</h3><p>Data Engineers are people who develop and maintain data architectures and make data available for business operations and analysis.</p><p>Data Engineers work within the data ecosystem to extract, integrate, and organize data from disparate sources; clean, transform, and prepare data; design, store, and manage data in data repositories.They enable data to be accessible in formats and systems that the various business applications, as well as stakeholders like Data Analysts and Data Scientists, can utilize.</p><p>A Data Engineer must have good knowledge of programming, sound knowledge of systems and technology architectures, and an in-depth understanding of relational databases and non-relational datastores.</p><h3>Data Analyst</h3><p>a Data Analyst translates data and numbers into plain language, so organizations can make decisions. Data Analysts inspect, and clean data for deriving insights; identify correlations, find patterns, and apply statistical methods to analyze and mine data; and visualize data to interpret and present the findings of data analysis. Analysts are the people who answer questions such as “Are the users’ search experiences generally good or bad with the search functionality on our site” or “What is the popular perception of people regarding our rebranding initiatives” or “Is there a correlation between sales of one product and another.”</p><p>Data Analysts require good knowledge of spreadsheets, writing queries, and using statistical tools to create charts and dashboards. Modern data analysts also need to have some programming skills. They need strong analytical and story-telling skills.</p><h3>Data Scientists</h3><p>Data Scientists analyze data for actionable insights and build Machine Learning or Deep Learning models that train on past data to create predictive models. Data Scientists are people who answer questions such as<strong> “How many new social media followers am I likely to get next month?”</strong> or “What percentage of my customers am I likely to lose to competition in the next quarter” or “Is this financial transaction unusual for this customer?”.</p><p>Data Scientists require knowledge of Mathematics, Statistics, and a fair understanding of programming languages, databases, and building data models. They also need to have domain knowledge.</p><h3>Business Analyst / Business Intelligence</h3><p>Business Analysts leverage the work of Data Analysts and Data Scientists to look at possible implications for their business and the actions they need to take or recommend.</p><p>BI Analysts do the same, except their focus is on the market forces and external influences that shape their business. They provide business intelligence solutions by organizing and monitoring data on different business functions and exploring that data to extract insights and actionable that improve business performance.</p><h3><strong>SUMMARIZE</strong></h3><ul><li>Data Engineering converts raw data into usable data.</li><li>Data Analytics uses this data to generate insights.</li><li>Data Scientists use Data Analytics and Data Engineering to predict the future using data from the past.</li><li>Business Analysts and Business Intelligence Analysts use these insights and predictions to drive decisions that benefit and grow their business.</li></ul><p>Interestingly, it’s not uncommon for data professionals to start their career in one of the data roles and transition to another role within the data ecosystem by supplementing their skills.</p><p>Thank you for reading.</p><p><strong>References</strong></p><p><a href="https://www.coursera.org/learn/introduction-to-data-engineering/home/welcome">https://www.coursera.org/learn/introduction-to-data-engineering/home/welcome</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5bc4ed65c150" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/data-engineers-data-analysts-data-scientist-business-analysts-and-business-intelligence-role-5bc4ed65c150">Data Engineers, Data Analysts, Data Scientist, Business Analysts, and Business Intelligence Role.</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Scrapping Data of Climate from 4 Different Source.]]></title>
            <link>https://medium.com/analytics-vidhya/how-to-scrapping-data-of-climate-from-4-different-source-b9efc984ef2e?source=rss-2a3bbaeb7847------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9efc984ef2e</guid>
            <category><![CDATA[r-programming]]></category>
            <category><![CDATA[climate-crisis]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[climate-change]]></category>
            <dc:creator><![CDATA[Imam Muhajir]]></dc:creator>
            <pubDate>Wed, 13 Oct 2021 15:48:53 GMT</pubDate>
            <atom:updated>2021-11-10T05:03:03.194Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rpSLRt2El_vRub2WxFrobg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@martinsanchez?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Martin Sanchez</a> on <a href="https://unsplash.com/s/photos/map?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>INTRODUCTIONS</h3><p>Climate is the average weather where the weather is the state of the atmosphere at a certain point in time. Climate is defined as a measure of the average and the variability of the relevant quantities of certain variables (such as temperature, precipitation, or wind), over a period of time, ranging from months to years or millions of years. Climate changes are continuously due to interactions between its components and external factors such as volcanic eruptions, variations in sunlight, and factors caused by human activities such as changes in land use and the use of fossil fuels.</p><p>In this article, we will discuss some reliable sources of climate data. And how do we scrape the data?</p><h3><strong>SCRAPPING DAT</strong></h3><p>In this scrapping, we will use the R programming language, the climate package, and the CHIRPS package. The climate R package is a package that automatically downloads meteorological, and hydrologic data from the public repository. Before starting scrapping, we will first download the required packages, use the console to operate.</p><pre>install.packages(&quot;climate&quot;)<br>install.packages(&quot;chirps&quot;)</pre><p>or</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/221/1*twvvDx-O5nHbimoe18qp2g.png" /><figcaption>Screenshot by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*mSeu6QGK6aXa51jVecm5NQ.png" /><figcaption>Screenshot by Author</figcaption></figure><p>after installing the package then import the package:</p><pre>library(</pre><p>There are 4 sources of climate data available :</p><h4>1. Packages Climate</h4><p>This package is divided into several data fields, namely meteorological, hydrological dan station information.</p><h4>a. Meteorological</h4><p>Download meteorological data from the SYNOP station available on the ogimet.com web collection, the data can be hourly / per day<br>SYNOP are all meteorological stations that work under The World Meteorological Organization. the results of the scrapping will get 18 columns.</p><pre>data_meteo = meteo_ogimet(date = c(Sys.Date() - 5, Sys.Date() - 1), <br>                 interval = &quot;daily&quot;,<br>                 coords = FALSE, <br>                 station = 12330)<br>head(data_meteo)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GAC4J1OKiAmNqfFP9WriXA.png" /><figcaption>Screenshot by Author</figcaption></figure><p>The next guess will take Meteorca \ data from SYNP/CLIMATE/PRECIP from available stations at the danepubliczne.imgw.pl. the data from this source contains a lot of columns.</p><pre>m = meteo_imgw(interval = &quot;daily&quot;, rank = &quot;synop&quot;, year = 2000,  coords = TRUE)<br>head(m)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ubRF_Om--Pplpy-rY_Pggw.png" /><figcaption>Screenshot by Author</figcaption></figure><p>next, we will be scrapping co2 data of monthly from Mauna Loa Observatory.</p><pre>c = meteo_noaa_co2( )<br>head(c)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*YyuKoM16-MBiOyNjKiGe0Q.png" /><figcaption>Screenshot by Author</figcaption></figure><h4>b. Hydrological</h4><p>scrapping data hydrological hourly, daily, and monthly SYNOP/CLIMATE/PRICEP station from danepubliczne.imgw.pl.</p><pre>h = hydro_imgw(interval = &quot;semiannual_and_annual&quot;, year = 2010:2011)<br>head(h)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*HMKs5BWpTTOV3yXnMuaQ1g.png" /><figcaption>Screenshot by Author</figcaption></figure><h4>c. Station Information</h4><p>we can be scrapping data stations from a different source. first, we will be scraping data from ogimet collection. if you run in R studio, the output can automatically show a map from the data.</p><pre>nso &lt;- nearest_stations_ogimet(country = &quot;United+Kingdom&quot;,<br>                        date = Sys.Date(),<br>                        add_map = TRUE,<br>                        point = c(-1, 53),<br>                        no_of_stations = 100)<br>head(nso)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*iiC6YJE9u_6_6PjdoNbQiQ.png" /><figcaption>Screenshot by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*RiDxSB5oSOBhe0q0IYqqew.png" /><figcaption>image by author</figcaption></figure><p>besides that, we can also scrape station data sourced from the NOAA ISH meteorological repository.</p><pre>nsn &lt;-  nearest_stations_nooa(country = &quot;UNITED KINGDOM&quot;,<br>                              date = Sys.Date(),<br>                              add_map = TRUE,<br>                              point = c(-1, 53),<br>                              no_of_stations = 100)<br>head(nsn)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hTl_bdgVIDdPxmKrGtGdbg.png" /><figcaption>Screenshot by Author</figcaption></figure><p>and there is still a lot of station data from several different sources such as the IMGW-PIB station in Poland.</p><h4>2. Packages CHIRPS</h4><p>Climate Hazards Groups InfraRed Precipitation with Station data (CHIRPS)is a terrestrial rainfall database that is a combination of three rainfall information, namely global climatology, satellite-based rainfall estimates, and in-situ observed rainfall. CHIRPS data can be a solution for extreme rainfall studies in the long series.</p><pre>library(chirps)<br>lonlat &lt;- data.frame(lon = c(-55.0281,-54.9857),<br>                     lat = c(-2.8094, -2.8756))<br>dates &lt;- c(&quot;2017-12-15&quot;, &quot;2017-12-31&quot;)<br>dt &lt;- get_chirps(lonlat, dates)<br>head(dt)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*SKXex25OlyeOmcnTX9tXLA.png" /><figcaption>Screenshot by Author</figcaption></figure><h4>3. Web Physical Sciences Laboratory</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z6LtlUpcbn0tM2KyKeETJA.png" /><figcaption>Screenshot by Author</figcaption></figure><p>the web is one of the best webs in data storage. the web provides several categories of data such as surface, temperature, land, ocean, and others. on this web, data can be scrapped manually or automatically using code. example download using code. the first click one of the datasets in a table, for example, we can click “CMAP Precipitation” .</p><p><a href="https://psl.noaa.gov/data/gridded/">https://psl.noaa.gov/data/gridded/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DSupFkFGQ9HkUUUz9-F2-g.png" /><figcaption>Screenshot by Author</figcaption></figure><p>and find the download feature and copy link address. this is format code:</p><pre>download.file(url = &lt;link.download&gt;, destfile=&lt;namefile&gt;,mode= &quot;mb&quot;)</pre><p>example:</p><pre>download.file(url = &#39;<a href="https://downloads.psl.noaa.gov/Datasets/cmap/std/precip.mon.mean.nc&#39;">https://downloads.psl.noaa.gov/Datasets/cmap/std/precip.mon.mean.nc&#39;</a>, destfile = &#39;precipmeanmonthly.nc&#39;,mode = &quot;wb&quot;)</pre><p>the result has been saved in your local storage. downloading using code looks more complicated, so what are the benefits of downloading using code? the benefit of downloading using code when we have a lot of data to be scrapping. so let&#39;s look at the following example. look at the last of lists in the dataset, and you can find the dataset namely “CPC Global Temperature” and click. after that finding “download file” and choose “daily Minimum Temperature” (click ‘tmin.yyyy.nc’).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JY2eMBJv92CmiXzlNOYanA.png" /><figcaption>Screenshot by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*DYqxktVjDCiQ85qzltBtHA.png" /><figcaption>Screenshot by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ccKFi0VgRzlCEuoBKbvokg.png" /><figcaption>Screenshot by Author</figcaption></figure><p>here there are many datasets, if you download manually it will take a long time and tired. so make it automatically by coding. the result has been saved in your local storage.</p><pre>#download data CPC Daily Minimum Temperature<br>for (i in 2018:2019) {<br>  string_date &lt;- as.character(i)<br>  myfile &lt;- paste0(&quot;tmin_&quot;,string_date,&quot;.nc&quot;)<br>  myurl &lt;- paste0(&quot;ftp://ftp.cdc.noaa.gov/Datasets/cpc_global_temp/&quot;,&quot;tmin.&quot;,string_date,&quot;.nc&quot;) #bisa disesuaikan; tmax or tmin<br>  download.file(url = myurl, destfile = myfile, mode = &quot;wb&quot;)<br>}</pre><p>4. Satellite Himawari-8</p><p>Himawari-8 is a satellite launched by JMA which began operating in 2015 as a successor to the MTSAT satellite which has 16 channels and produces data every 10 minutes. The Himawari satellite carries the AHI (Advanced Himawari Imager) sensor. This satellite has a geostationary orbit with an altitude of 35,791 km. The spatial resolution of Himawari-8 data is 0.5 km (band 3), 1 km, and 2 km. Himawari-8 data was applied to monitor rainfall levels, cloud top temperatures, and sea surface temperatures.</p><pre>#### Download data Himawari LAPAN<br>  #sumber data: <a href="http://modis-catalog.lapan.go.id/monitoring/#">http://modis-catalog.lapan.go.id/monitoring/#</a><br>  #hanya tersedia beberapa hari terakhir saja <br>  <br>  rm(list = ls())<br>#ext= brick(&quot;./compile/Himawari_IND_start2020-07-01.nc&quot;)<br>#date.ex=seq(as.Date(&quot;2021-09-01&quot;),length.out = nlayers(ext),by=&#39;day&#39;)</pre><pre>from=as.Date(&quot;2021-09-05&quot;)<br>date=seq(from,Sys.Date(),by=&quot;day&quot;)<br>hr=sprintf(&quot;%02d&quot;, 0:23)</pre><pre>download_size &lt;- function(url) as.numeric(httr::HEAD(url)$headers$`content-length`)<br>for (tgl in 1:length(date)) {<br>  #tgl=1<br>  string_date=date[tgl]<br>  <br>  for (i in 1:length(hr)) {<br>    #i=1<br>    <br>    myfile &lt;- paste0(&quot;C:/&quot;,&quot;himawari_&quot;,string_date,&quot;-&quot;,as.character(hr[i]),&quot;.tif&quot;)  #save in your directory <br>    myurl &lt;- paste0(&quot;<a href="http://modis-catalog.lapan.go.id/himawari-8/GeoTIFF/">http://modis-catalog.lapan.go.id/himawari-8/GeoTIFF/</a>&quot;,string_date,&quot;/&quot;,hr[i],&quot;-00/produkRFR2.tif&quot;)<br>    <br>    if (file.exists(myfile)==F) {<br>      tryCatch(download.file(url = myurl,destfile = myfile,mode = &quot;wb&quot;, quiet = FALSE), <br>               error = function(e) print(paste0(&quot;precip_&quot;,string_date,&quot;-&quot;,as.character(hr[i]),&quot;.tif = did not exist&quot;)))<br>      <br>      if (file.exists(myfile)==T) {<br>        while (file.info(myfile)$size &lt; download_size(myurl)) {<br>          download.file(url = myurl,destfile = myfile,mode = &quot;wb&quot;, quiet = FALSE)<br>        }<br>        print(paste0(&quot;precip_&quot;,string_date,&quot;-&quot;,as.character(hr[i]),&quot;.tif = OK&quot;))<br>      }<br>    }<br>  }<br>}</pre><p>The article above is 4 sources of climate data, hopefully, it can increase knowledge and be useful for the good of data in the world. thank you for reading</p><h4>References :</h4><p><a href="https://psl.noaa.gov/data/gridded/data.cpc.globaltemp.html">https://psl.noaa.gov/data/gridded/data.cpc.globaltemp.html</a><br><a href="https://downloads.psl.noaa.gov/Datasets/cpc_global_temp/">https://downloads.psl.noaa.gov/Datasets/cpc_global_temp/</a><br><a href="http://modis-catalog.lapan.go.id/monitoring/">http://modis-catalog.lapan.go.id/monitoring/</a><br><a href="https://www.rdocumentation.org/packages/climate/versions/1.0.1">https://www.rdocumentation.org/packages/climate/versions/1.0.1</a><br><a href="https://www.rdocumentation.org/packages/chirps/versions/0.1.2/topics/chirps">https://www.rdocumentation.org/packages/chirps/versions/0.1.2/topics/chirps</a><br>power-point practice 4, data climate access from course methodology computation IPB.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9efc984ef2e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/how-to-scrapping-data-of-climate-from-4-different-source-b9efc984ef2e">How to Scrapping Data of Climate from 4 Different Source.</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quantum Convolutional Neural Network for Image Classification using Tensorflow]]></title>
            <link>https://medium.com/analytics-vidhya/quantum-convolutional-neural-network-for-image-classification-using-tensorflow-334c6c2c73f0?source=rss-2a3bbaeb7847------2</link>
            <guid isPermaLink="false">https://medium.com/p/334c6c2c73f0</guid>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[quantum-computing]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[quantum-physics]]></category>
            <dc:creator><![CDATA[Imam Muhajir]]></dc:creator>
            <pubDate>Mon, 04 Oct 2021 15:53:46 GMT</pubDate>
            <atom:updated>2021-11-10T05:09:47.341Z</atom:updated>
            <content:encoded><![CDATA[<p>Implementation Quantum in Neural Network</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g8EDtyhWL5_HjIANogigfg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@adigold1?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Adi Goldstein</a> on <a href="https://unsplash.com/s/photos/quantum-computing?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>INTRODUCTION</h3><p>Quantum computing has the potential to outperform classical computers and is expected to play an active role in various fields, in quantum machine learning, quantum computing has been found to be useful for enhanced feature representation and state approximation (Watabe et al. 2021). Quantum computing based on quantum bits (qubits) is inspired by the phenomenon of particles in quantum states. This phenomenon is a superposition phenomenon where a particle in a quantum state can have two states at once (Gultom 2017). The approach to this phenomenon is transformed into computations in 6the form of qubits, namely 0.1 or both (Kaye 2007).</p><h3>MAIN COMPONENT</h3><h4>QUBIT</h4><p>Quantum computing uses qubits as the basic unit of information, which is represented by a state vector (Gado and Younes, 2021). Dirac notation is one of the notations used in quantum mechanics which was discovered by Paul Dirac. In Dirac notation the symbol that identifies a vector is written as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/149/1*bdYmWWvHXwmnTFuiMEpzfA.png" /></figure><p>Furthermore, these notations will be operated using quantum logic gates. A qubit is the basic unit of quantum information, a quantum bit: a two-level system that can exist in a superposition of those two possible states.</p><h4>GATES AND OPERATIONS</h4><p>Quantum gates are <a href="https://en.wikipedia.org/wiki/Unitary_operators">unitary operators</a> and are described as <a href="https://en.wikipedia.org/wiki/Unitary_matrix">unitary matrices</a> relative to some <a href="https://en.wikipedia.org/wiki/Basis_(linear_algebra)">basis</a>. In <a href="https://en.wikipedia.org/wiki/Quantum_computing">quantum computing</a> and specifically the <a href="https://en.wikipedia.org/wiki/Quantum_circuit">quantum circuit</a> <a href="https://en.wikipedia.org/wiki/Model_of_computation">model of computation</a>, a <strong>quantum logic gate</strong> (or simply <strong>quantum gate</strong>) is a basic quantum circuit operating on a small number of <a href="https://en.wikipedia.org/wiki/Qubit">qubits</a>. They are the building blocks of quantum circuits like classical <a href="https://en.wikipedia.org/wiki/Logic_gate">logic gates</a> are for conventional digital circuits. A Gate is an effect that can be applied to a collection of qubits (objects with a Qid). Gates can be applied to qubits by calling theirs on method, or, alternatively calling the gate on the qubits. The object created by such calls is an Operation.</p><p>Gates versus operations</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*9KRXx2lNZ_5O-EtP86e-GA.png" /></figure><p>The above example shows the first half of a quantum teleportation circuit, found in many quantum computation textbooks. This example uses three different gates: a Hadamard (H), controlled-Not (CNOT), and measurement. These are represented in <em>cirq</em> by<em> cirq.H</em>, <em>cirq.CNOT</em>, and<em> cirq.measure</em>, respectively.<br>Quantum computing has its own logic gate, namely a quantum logic gate (quantum gate). There are several quantum logic gates, which are as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*cosLO_gSQg5b3wQyFEM7hg.png" /></figure><h4>CIRCUIT</h4><p>A Circuit is a collection of Moments. A Moment is a collection of Operations that all activities during the same abstract time slice. An Operation is some effect that operates on a specific subset of Qubits, the most common type of Operation is a GateOperation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*ii3r4xuD40H9HfwxmChsHQ.png" /></figure><h4>ARCHITECTURE CNN VS QCNN</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*f5lwIesafLq6iQMZgiZb7g.png" /></figure><p>Convolutional Neural Network (CNN) is a deep learning method used to process image data. In the process, CCN has several main layers, namely the Convolution layer, Subsampling Layer, and fully connected layer.</p><p>Quantum Convolutional Neural Network (QCNN) is a development of CNN based on quantum computing. QCNN extends the main features and structures of CNNs into quantum systems (Oh et al. 2020).</p><h3>BUILD QUANTUM CONVOLUTIONAL NEURAL NETWORK</h3><h4>INSTALL LIBRARY</h4><p>For the manufacture of a quantum convolution neural network, it is recommended to use<a href="https://research.google.com/colaboratory/"> google collab </a>or <a href="https://www.kaggle.com/code">Kaggle notebook</a>, because both environments already support the TensorFlow-Quantum package.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Fimammuhajir992%2Fquantum-convolutional-neural-network%2Fv%2F8%26cellId%3D4&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Fimammuhajir992%2Fquantum-convolutional-neural-network%2Fv%2F8%26cellId%3D4&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2Fe4f9afe7d9534c1fb9552f27c6587571%2Fpreview%2F2d00f8fde19648179b3f2a18b4288352&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/46d68ef2fca92bf55a4f4019508b1712/href">https://medium.com/media/46d68ef2fca92bf55a4f4019508b1712/href</a></iframe><p>import package</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Fimammuhajir992%2Fquantum-convolutional-neural-network%2Fv%2F8%26cellId%3D5&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Fimammuhajir992%2Fquantum-convolutional-neural-network%2Fv%2F8%26cellId%3D5&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2Fe4f9afe7d9534c1fb9552f27c6587571%2Fpreview%2F2d00f8fde19648179b3f2a18b4288352&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/8272e78e512d7ab86b774ac4c0647b3c/href">https://medium.com/media/8272e78e512d7ab86b774ac4c0647b3c/href</a></iframe><h4>INPUT DATA MNIST</h4><p>The data that will be used is the MNIST database (Modified National Institute of Standards and Technology database).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*HNhw0xfF7Gbv9bW64SRQkw.png" /><figcaption>MNIST DATABASE</figcaption></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Fimammuhajir992%2Fquantum-convolutional-neural-network%2Fv%2F8%26cellId%3D7&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Fimammuhajir992%2Fquantum-convolutional-neural-network%2Fv%2F8%26cellId%3D7&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2Fe4f9afe7d9534c1fb9552f27c6587571%2Fpreview%2F2d00f8fde19648179b3f2a18b4288352&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/44f4f92451dbc71a055a4059adeadd9c/href">https://medium.com/media/44f4f92451dbc71a055a4059adeadd9c/href</a></iframe><p>The MNIST data that will be used is only two-digit numbers 3 and 6.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Fimammuhajir992%2Fquantum-convolutional-neural-network%2Fv%2F9%26cellId%3D8&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Fimammuhajir992%2Fquantum-convolutional-neural-network%2Fv%2F9%26cellId%3D8&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2Fe4f9afe7d9534c1fb9552f27c6587571%2Fpreview%2Fb97bb93ab0d440efa3aaeac8d4a8454e&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/a39cd9f95542313f4981d3bdd596b394/href">https://medium.com/media/a39cd9f95542313f4981d3bdd596b394/href</a></iframe><p>example data:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Fimammuhajir992%2Fquantum-convolutional-neural-network%2Fv%2F9%26cellId%3D10&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Fimammuhajir992%2Fquantum-convolutional-neural-network%2Fv%2F9%26cellId%3D10&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2Fe4f9afe7d9534c1fb9552f27c6587571%2Fpreview%2Fb97bb93ab0d440efa3aaeac8d4a8454e&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/14dcd9ef07bf3f24108f1aa5b83fcb4f/href">https://medium.com/media/14dcd9ef07bf3f24108f1aa5b83fcb4f/href</a></iframe><p>In the process of implementing QCNN with large data, it still requires a large enough resource, therefore for this tutorial, we will resize data to 4 x 4 pixels, and remove contradicting data.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Fimammuhajir992%2Fquantum-convolutional-neural-network%2Fv%2F10%26cellId%3D11&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Fimammuhajir992%2Fquantum-convolutional-neural-network%2Fv%2F10%26cellId%3D11&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2Fe4f9afe7d9534c1fb9552f27c6587571%2Fpreview%2F2433a4300f57479ebbafa9aa7dff230c&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ae274379d19cd6d193c4d79c143b642/href">https://medium.com/media/3ae274379d19cd6d193c4d79c143b642/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Fimammuhajir992%2Fquantum-convolutional-neural-network%2Fv%2F12%26cellId%3D12&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Fimammuhajir992%2Fquantum-convolutional-neural-network%2Fv%2F12%26cellId%3D12&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2Fe4f9afe7d9534c1fb9552f27c6587571%2Fpreview%2Fd988b22f0c3f48109ba9faf34d3da136&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/53505ea8b78d840c9a0f6f2d2879f78f/href">https://medium.com/media/53505ea8b78d840c9a0f6f2d2879f78f/href</a></iframe><p>the next process is the binning process on pixel data with a limit value of 0.5, where a pixel value of more or equal to 0.5 will have a value of 1, and a pixel value of less than 0.5 will have a value of 0. One example of the transformation process above are as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*t2r9HJNdnMFZqBrxcqmkVA.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Fimammuhajir992%2Fquantum-convolutional-neural-network%2Fv%2F12%26cellId%3D13&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Fimammuhajir992%2Fquantum-convolutional-neural-network%2Fv%2F12%26cellId%3D13&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2Fe4f9afe7d9534c1fb9552f27c6587571%2Fpreview%2Fd988b22f0c3f48109ba9faf34d3da136&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f05459694cbdc04d61213076472673f/href">https://medium.com/media/6f05459694cbdc04d61213076472673f/href</a></iframe><p>The next stage is to prepare the cluster state as a data processing environment because the data used is 4 x 4 pixels, therefore it takes a cluster state with a total of 16 qubits, the cluster states are as follows:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Fimammuhajir992%2Fquantum-convolutional-neural-network%2Fv%2F14%26cellId%3D15&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Fimammuhajir992%2Fquantum-convolutional-neural-network%2Fv%2F14%26cellId%3D15&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2Fe4f9afe7d9534c1fb9552f27c6587571%2Fpreview%2F14769817d53b4241a650964808e67ea0&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/618ccda9b79491969de46683ec947d41/href">https://medium.com/media/618ccda9b79491969de46683ec947d41/href</a></iframe><p>The next process is to transform the data into a data circuit. In this transformation, the Pauli-x gate is added for data with a value of one, and for data with a value of zero, no Pauli-x gate is added.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Fimammuhajir992%2Fquantum-convolutional-neural-network%2Fv%2F16%26cellId%3D16&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Fimammuhajir992%2Fquantum-convolutional-neural-network%2Fv%2F16%26cellId%3D16&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2Fe4f9afe7d9534c1fb9552f27c6587571%2Fpreview%2F3dd02cc4fd464b828f03d2edf323338e&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a1c4eb660a0012e4d547a081f5cf644/href">https://medium.com/media/6a1c4eb660a0012e4d547a081f5cf644/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Fimammuhajir992%2Fquantum-convolutional-neural-network%2Fv%2F16%26cellId%3D17&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Fimammuhajir992%2Fquantum-convolutional-neural-network%2Fv%2F16%26cellId%3D17&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2Fe4f9afe7d9534c1fb9552f27c6587571%2Fpreview%2F3dd02cc4fd464b828f03d2edf323338e&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e45b33eda8bd616d128639955203839/href">https://medium.com/media/5e45b33eda8bd616d128639955203839/href</a></iframe><p>One example of the transformation above is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*uaaMsrJb288uGBPzyQbGow.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Fimammuhajir992%2Fquantum-convolutional-neural-network%2Fv%2F16%26cellId%3D18&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Fimammuhajir992%2Fquantum-convolutional-neural-network%2Fv%2F16%26cellId%3D18&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2Fe4f9afe7d9534c1fb9552f27c6587571%2Fpreview%2F3dd02cc4fd464b828f03d2edf323338e&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/3dbcd42f6c383ae1b3caeb43545b5842/href">https://medium.com/media/3dbcd42f6c383ae1b3caeb43545b5842/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Fimammuhajir992%2Fquantum-convolutional-neural-network%2Fv%2F16%26cellId%3D19&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Fimammuhajir992%2Fquantum-convolutional-neural-network%2Fv%2F16%26cellId%3D19&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2Fe4f9afe7d9534c1fb9552f27c6587571%2Fpreview%2F3dd02cc4fd464b828f03d2edf323338e&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5cc5ce86838e5214389afd3f75e0269/href">https://medium.com/media/f5cc5ce86838e5214389afd3f75e0269/href</a></iframe><h4>BUILD ARSITEKTUR</h4><p>The making of the Quantum Convolutional Neural Network Architecture has several stages, namely the manufacture of <strong>Quantum Circuits</strong>, the construction of the <strong>Quantum Layer</strong>, and the construction of the<strong> Quantum Convolutional Neural Network Architecture</strong>.</p><h4><strong>Quantum Circuit</strong></h4><p>At the stage of forming a quantum circuit, three main quantum circuits are needed, namely <em>one cubit unitary circuit</em>, <em>two-qubit unitary circuit</em>, and <em>two-qubit pooling circuit</em>, in which the quantum circuit is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*LR2pA-x1PiLkx3j33dMlhQ.png" /><figcaption><strong>One Cubit Unitary Circuit</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*_h3j7RCjys4FRN-MyZaNHQ.png" /><figcaption><strong>Two-qubit Unitary Circuit</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*vHzHOLWH7SBK4hRCRzROvQ.png" /><figcaption><strong><em>Two-qubit Pooling Circuit</em></strong></figcaption></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Fimammuhajir992%2Fquantum-convolutional-neural-network%2Fv%2F17%26cellId%3D21-24&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Fimammuhajir992%2Fquantum-convolutional-neural-network%2Fv%2F17%26cellId%3D21-24&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2Fe4f9afe7d9534c1fb9552f27c6587571%2Fpreview%2F3280073bcf22406280bfb7d2a9bbd66d&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/410b7e8b7f57c10b864905b6a4bb4bd8/href">https://medium.com/media/410b7e8b7f57c10b864905b6a4bb4bd8/href</a></iframe><p>The circuit is a component to build a quantum layer architecture. In the next stage of development of the quantum layer.</p><h4>Quantum Layer</h4><p>The construction of a quantum layer where there are three layers needed to build a Quantum Convolutional Neural Network Architecture, namely <em>quantum convolution layer</em>, <em>quantum pooling layer</em>, and <em>quantum neural network layer</em>, the layers are as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*D44rTsLnMPhNN07IXNGNgQ.png" /><figcaption><strong><em>Quantum Convolution Layer</em></strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*N1L5Hm2aXGe8lZPuircYTA.png" /><figcaption><strong>Quantum Pooling Layer</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*lql-Rrs7_EJKVDip01hlew.png" /><figcaption><strong>Quantum Neural Network Layer</strong></figcaption></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Fimammuhajir992%2Fquantum-convolutional-neural-network%2Fv%2F18%26cellId%3D25-28&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Fimammuhajir992%2Fquantum-convolutional-neural-network%2Fv%2F18%26cellId%3D25-28&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2Fe4f9afe7d9534c1fb9552f27c6587571%2Fpreview%2F6c9331aaf5d44e00a9a1f391d6ea9118&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/05e2b756028def439f457662793286ba/href">https://medium.com/media/05e2b756028def439f457662793286ba/href</a></iframe><p>The quantum convolution layer consists of seven unitary two-qubit circuits and four one-qubit unitary circuits with an additional six quantum gates. The quantum pooling layer consists of four two-qubit pooling circuits and three one-qubit unitary circuits. Furthermore, the quantum neural network layer consists of an array of Pauli-x gates and Pauli-z gates. After the formation of the quantum layer, the next step is to arrange the quantum layer into a Quantum Convolutional Neural Network Architecture.</p><h4>Build Become QCNN Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*jGiAtD1iaUFE8qDbJny2sQ.png" /></figure><p>This Quantum Convolutional Neural Network architecture consists of a <em>quantum convolution layer </em>with 16 qubit data input, a <em>quantum pooling layer</em> with 16 qubit data input, and a <em>quantum neural network layer</em> with 8 qubit data input.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Fimammuhajir992%2Fquantum-convolutional-neural-network%2Fv%2F19%26cellId%3D31-32&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Fimammuhajir992%2Fquantum-convolutional-neural-network%2Fv%2F19%26cellId%3D31-32&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2Fe4f9afe7d9534c1fb9552f27c6587571%2Fpreview%2Ff122c1c52b9b4bdf858d7b9712bb5f66&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7c79a1a6e1ad4d5de03ce15e4940ae9/href">https://medium.com/media/e7c79a1a6e1ad4d5de03ce15e4940ae9/href</a></iframe><h4>Training Model</h4><p>for this tutorial, we will try simple modeling that doesn’t take much time, with 5 epochs and using 500 data samples. If interested you can try it directly with the different parameters and how they change.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Fimammuhajir992%2Fquantum-convolutional-neural-network%2Fv%2F20%26cellId%3D34-35&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Fimammuhajir992%2Fquantum-convolutional-neural-network%2Fv%2F20%26cellId%3D34-35&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2Fe4f9afe7d9534c1fb9552f27c6587571%2Fpreview%2Fe9c8b2f41fe04f32b08982174181ec67&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/70fe2a27578c61b1e9b76ba16175eb27/href">https://medium.com/media/70fe2a27578c61b1e9b76ba16175eb27/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Fimammuhajir992%2Fquantum-convolutional-neural-network%2Fv%2F20%26cellId%3D36&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Fimammuhajir992%2Fquantum-convolutional-neural-network%2Fv%2F20%26cellId%3D36&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2Fe4f9afe7d9534c1fb9552f27c6587571%2Fpreview%2Fe9c8b2f41fe04f32b08982174181ec67&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c841e931b3c8411b29c487ae042dbae/href">https://medium.com/media/3c841e931b3c8411b29c487ae042dbae/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Fimammuhajir992%2Fquantum-convolutional-neural-network%2Fv%2F21%26cellId%3D37-39&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Fimammuhajir992%2Fquantum-convolutional-neural-network%2Fv%2F21%26cellId%3D37-39&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2Fe4f9afe7d9534c1fb9552f27c6587571%2Fpreview%2F54b6b85b8dde4fb9a4e7c0005c96269e&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/49e3cd9dfdfaae37bccd2fb4fe185ead/href">https://medium.com/media/49e3cd9dfdfaae37bccd2fb4fe185ead/href</a></iframe><p>The results of the modeling show quite good results, with the latest validation accuracy of 83.33.</p><p>This QCNN modeling still has many shortcomings and weaknesses, especially from the availability of the quantum computing environment that is not widely available, and we create the quantum environment in a classical computer, this is what causes quantum processing on a classical computer to be relatively long. I hope this paper can help readers with further research, and the development of quantum computing. I know there are still many mistakes in my writing, I hope to get feedback and suggestions.</p><p>Thank you very much for reading this article.</p><p><strong>References:</strong></p><ul><li><a href="https://www.tensorflow.org/quantum">https://www.tensorflow.org/quantum</a></li><li><a href="https://quantumai.google/cirq">https://quantumai.google/cirq</a></li><li><a href="https://en.wikipedia.org/wiki/Quantum_logic_gate">https://en.wikipedia.org/wiki/Quantum_logic_gate</a></li><li>Watabe M, Shiba K, Chen C, Sogabe M, Sakamoto K , Sogabe T. 2021. Quantum circuit learning with error backpropagation algorithm and experimental implementation. <em>Journal Quantum Rep. </em>3(2):333–349. doi.org/10.3390/quantum3020021.</li><li>Gultom. 2017. Klasifikasi data dengan quantum perceptron. <em>Jurnal Teknovasi. </em>4(1):1–9.</li><li>Kaye P, Laflamme R, Mosca M. 2007. <em>An Introduction to Quantum Computing</em>. New York: Oxford University Press.</li><li>Gado M , Younes A. 2021. Optimization of reversible curcuit using toffoli decompositions with negative controls. <em>Jurnal Symmetry . </em>13(6): 1025. doi.org/10.3390/sym13061025.</li><li>Oh S, Choi J, Kim J.2020.A tutorial on quantum Convolutional neural network (QCNN).,<em>forthcoming.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=334c6c2c73f0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/quantum-convolutional-neural-network-for-image-classification-using-tensorflow-334c6c2c73f0">Quantum Convolutional Neural Network for Image Classification using Tensorflow</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple Concept of Apache Kafka]]></title>
            <link>https://medium.com/analytics-vidhya/introduction-to-apache-kafka-841c1238d5b6?source=rss-2a3bbaeb7847------2</link>
            <guid isPermaLink="false">https://medium.com/p/841c1238d5b6</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[apache]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Imam Muhajir]]></dc:creator>
            <pubDate>Tue, 28 Sep 2021 14:52:23 GMT</pubDate>
            <atom:updated>2021-10-04T11:05:50.687Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aE3FWQSpipw-L7jkK9oW0Q.jpeg" /></figure><h3>INTRODUCTION</h3><p>Apache Kafka is an open-source distributed <strong>event streaming</strong> platform used by thousands of companies for high-performance data pipelines, streaming analytics, data integration, and mission-critical applications. <strong>event streaming</strong> is the practice of capturing data in real-time from event sources like databases, sensors, mobile devices, cloud services, and software applications</p><p><strong>The characteristics</strong> of Kafka are:<br>• It is a distributed and partitioned messaging system.<br>• It is highly fault-tolerant.<br>• It is highly scalable.<br>• It can process and send millions of messages per second to several receivers.</p><p>Kafka can be used for<strong> various purposes </strong>in an organization, such as:<br>• <strong>Messaging service,</strong> Kafka can be used to send and receive millions of messages in real-time. <br>• <strong>Real-time stream processing</strong>, Kafka can be used to process a continuous stream of information in real-time and pass it to stream processing systems such as Storm.<br><strong>• Log aggregation</strong>, Kafka can be used to collect physical log files from multiple systems and store them in a central location such as HDFS.<br>• <strong>Commit log service</strong>, Kafka can be used as an external commit log for distributed systems.<br>• <strong>Event sourcing</strong>, Kafka can be used to maintain a time-ordered sequence of events.<br>• <strong>Website Activity Tracking</strong>, Kafka can be used to process real-time website activity such as page views, searches, or other actions users may take.</p><h3>DIFFERENCES BEFORE AND AFTER USING APACHE KAFKA</h3><p>Why don’t we just use the usual method? Now we will simulate how our application does not use Apache Kafka.</p><p><strong>BEFORE</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*0JCaHKHv6amcjqsQnpeomA.png" /></figure><p>For example, we have several applications like the one above, if we don’t use publish-subscribe when the ERP app requires ORDER data, then we have to send data to the ERP, and then the App Member sends data to the ERP, every data that is transacted requires a request. With this method, it’s not efficient when you have more apps, such as 100 apps, the data transaction diagram will be more complicated, and if one app crashes, the other app crashes. therefore another method is needed.</p><p><strong>AFTER</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*-Mkp9WadEj_4ZPdSqli8nw.png" /></figure><p>After using Apache Kafka, the process of sending and receiving data through massage brokers, if an error occurs in one of the apps, it will not damage the existing flow. The above process will use <strong>publish</strong> and<strong> subscribe</strong>, publish/subscribe to transfer data in real-time and automatically through the Massage Broker. By using this method, we do not need to request the required data from a particular application, the process will be done automatically. Apache Kafka is also a<strong> Message Broker</strong> application. There are several other massage broker applications, but the most popular massage broker application is Apache Kafka.</p><h3>PUBLISHER AND SUBSCRIBER</h3><p>Apache Kafka is an application that can be used to process Publish and Subscribe. Apache Kafka is also a Message Broker application.</p><p><strong>Publish </strong>= send data <br><strong>Subscribe</strong> = receive data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*2JH3YLomHXep6FlU5MSysg.png" /></figure><p>By using publish/subscribe, all Publisher applications will send data to the topic (<strong>topic</strong> is a<strong> table</strong> if it is analogized in the database) then all subscribers will hear the data (the term for data retrieval is <strong>listening,</strong> so every incoming data will be immediately received by all subscribers). This process is what will be maintained by the message broker application.</p><p>A<strong><em> Topic </em></strong>is a category of messages in Kafka. The data in Kafka will be stored in a topic.</p><p><strong>Kafka: Topic — Database: Table</strong></p><p>Data on apache Kafka cannot be changed. In Kafka topic data cannot process updates, conceptually Kafka sends events or logs.</p><h3>KAFKA ARCHITECTURE</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*10FxhE7k7B4J-wagGsRybQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*WzHWHmnEMjaqa-rrP9XU7A.png" /></figure><ul><li><strong>The</strong> <strong>Streams API </strong>allows transforming the stream of data from input topics to output topics.</li><li><strong>The Connect API </strong>allows data ingestion from some source system into Kafka or pushes from Kafka into some sink system.</li><li><strong>The</strong> <strong>Producer API </strong>allows applications to send streams of data to topics in the Kafka cluster.</li><li><strong>The</strong> <strong>Consumer API </strong>allows applications to read streams of data from topics in the Kafka cluster.</li></ul><p>Applications can act as both producers and consumers at the same time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*geoJBq8HwuBO9yoBlLVxUw.png" /></figure><p>Kafka can’t handle its own cluster therefore it takes a zookeeper to manage Kafka. All management on Kafka will be done in zookeeper, but data will be stored in apache Kafka.</p><h3>PARTITION</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*3-XSweUVobS5d7pjtr4TGw.png" /></figure><p>Topics are divided into partitions, which are the unit of parallelism in Kafka. Partitions can be distributed across the Kafka cluster.<br>When creating a topic we can determine, we can determine how many partitions we want. Why use partitions? This is because 1 partition can only be subscribed by one app</p><p><strong>1 partition — 1 apps</strong></p><p>When using apache Kafka it is recommended to make the number of partitions more than the number of apps created.</p><p>• Each Kafka server may handle one or more partitions.<br>• A partition can be replicated across several servers for fault tolerance.<br>• One server is marked as a leader for the partition and the others are marked as followers.<br>• The leader controls the read and write for the partition, whereas, the followers replicate the data.<br>• If a leader fails, one of the followers automatically becomes the leader.<br>• ZooKeeper is used for the leader selection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*f1Jf0aQhvB3WmAiYtLE9wA.png" /></figure><p>0 to 12 is called a log, the data will increase continuously and will form a history, for example, we add data to log 0 with a value of “1” and then on log 1 with a value of “1”. duplication has no effect on this method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*vJxy4lOpRh-PvldN0TTPAQ.png" /></figure><p>The above is an example when we have 2 consumers, in consumer A the data being consumed is the 9th word (offset 9 ) and for consumer, B is consuming the 11th data (offset 11). offset function is a marker of data distribution. For example, when consumer A consumes data 1, 2,3 and then the app dies, then when the app restarts the app doesn’t need to consume data from the beginning again, and can immediately continue consuming 4, 5, 6, etc. Partition and offset are set by Kafka automatically, so no need to worry about that.</p><h3>REPLICATION</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*PnByc6-sEp3q9iOXxClUeA.png" /></figure><p>In the example above there are 3 Kafka servers, Replication is symbolized by R, and Partition is symbolized by P. For partition creation and replication will be managed by apache Kafka. In partition placement and replication, 1 server must not have the same 1 partition and 1 replication.<br>So it’s impossible <br>S = P&lt;A&gt; , R&lt;A&gt; <br>As an example: <br>Server 1 = P1 <br>Server 2 = P2, R1 <br>Server 3 = R2</p><h3>CONSUMER GROUP</h3><p>In Apache Kafka there is what is called a consumer group, the consumer group is a collection of applications, where one consumer group can only access one partition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*UMBhFh8Wh5c5u6_52zqFSQ.png" /></figure><p>In the picture above, when there are 2 similar applications, there will be duplicate data on the app because each app consumes from 2 partitions. Therefore we use a customer group to solve this problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*hsW4tvdS-0QQGBh9SNWkMg.png" /></figure><p>In the example above, one consumer group can only access one partition. And it can’t be more, therefore when you create a partition, the partition must be larger than the number of apps in one consumer group.</p><p><strong>Number of Partitions &gt;= Number of Apps</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ntl9le11Dcr8fZz9C5l19g.png" /></figure><p>The above example is a wrong example because the number of apps is greater than the number of partitions.</p><h3>RETENTION POLICY</h3><p>We know that in Kafka the data cannot be changed, therefore it requires automatic deletion of data caused by data that continues to grow from time to time. There are 2 ways to wipe data in apache Kafka:</p><ol><li><strong>Log Retention time<br></strong>Log retention time is a deletion of data based on time, for example when the data is 7 days old then the data will be deleted automatically (in Kafka the default log retention time is 7 days).</li><li><strong>Log Retention Bytes<br></strong>Log Retention Bytes is a deletion of data based on the amount of data. For example, when we have got 1 gigabyte, the old data will be deleted.</li><li><strong>Offset Retention time<br></strong>Offset Retention time is how long the offset data is stored in Kafka. Offset data is data that is stored by apache Kafka when the app that should be consuming Kafka data is not active. For example: when there is 1 inactive app, then the data will be stored in apache Kafka. If the app is inactive for a long time, the data stored in apache Kafka will increase. Therefore, an offset retention time is needed to delete the data. (default offset retention time is 7 days)</li></ol><p>Thank you for reading this article. Hopefully, this article can be useful and helpful in the development of data. don’t forget to follow and give a lot of claps. See you next time</p><h4>Source:</h4><p><a href="https://kafka.apache.org/">https://kafka.apache.org/</a><br><a href="https://www.youtube.com/watch?v=SArQUV0CE2I&amp;list=PL-CtdCApEFH8dJMuQGojbjUdLEty8mqYF">https://www.youtube.com/watch?v=SArQUV0CE2I&amp;list=PL-CtdCApEFH8dJMuQGojbjUdLEty8mqYF</a> <br><a href="https://lms.simplilearn.com/courses/2810/Big-Data-Hadoop-and-Spark-Developer/syllabus">https://lms.simplilearn.com/courses/2810/Big-Data-Hadoop-and-Spark-Developer/syllabus</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=841c1238d5b6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/introduction-to-apache-kafka-841c1238d5b6">Simple Concept of Apache Kafka</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Complete Scrapping of Twitter Data (Series Twitter Data)]]></title>
            <link>https://medium.com/analytics-vidhya/complete-scrapping-of-twitter-data-series-twitter-data-9d984bccab37?source=rss-2a3bbaeb7847------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d984bccab37</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[twitter]]></category>
            <dc:creator><![CDATA[Imam Muhajir]]></dc:creator>
            <pubDate>Sat, 18 Sep 2021 04:52:57 GMT</pubDate>
            <atom:updated>2021-10-04T12:06:40.143Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N08rqI0omj_Ye_6JOwGrJA.png" /></figure><p>List of Content:<br><strong>INTRODUCTION <br>BENEFIT <br>PREPARATION SCRAPING <br>SCRAPPING DATA</strong><br><strong>A. DATA BASED ON-SCREEN NAME</strong><br> — 1. Get User LookUp<br> — 2. Get User Time Line<br> — 3. Get Favorites<br> — 4. Get Followers<br> — 5. Get Following/Friend<br><strong>B. DATA BASED ON TWITTER POST</strong><br> — 1. Get Post LookUp<br> — 2. Get User Retweeted Post<br><strong>C. DATA BASED ON OWN ACCOUNT</strong><br> — 1. Get Home Timeline<br> — 2. Get Retweeted<br> — 3. Get Mentioned<br><strong>D. DATA BASED ON LIST</strong><br> — 1. Get List Post<br> — 2. Get List Subscribers<br> — 3. Get List Subscriptions<br> — 4. Get Members List<br><strong>D. ANOTHER DATA</strong><br> — 1. Get Trending Twitter<br> —2. Get Search User<br> — 3. Get Search</p><h3><strong>INTRODUCTION</strong></h3><p>We all know that Twitter is a big social media. Many people from our environment, good friends, friends, family, artists, athletes, companies use Twitter. Do you know? With Twitter API we can retrieve a lot of information on a Twitter account such as post when it was posted, number of likes, number of retweets, number of followers, descriptions, and many other things. In this session, we will only discuss what data can be taken from someone’s Twitter account. Maybe for the next article, we will discuss visualization, sentiment, network, and other things.</p><h3><strong>BENEFIT</strong></h3><p>What are the benefits of scrapping the Twitter account data, one of which is that we can use the data to see someone’s habit patterns, someone’s tweet sentiment, someone’s network, and many insights that we can extract from the data?</p><h3><strong>PREPARATION SCRAPING</strong></h3><p>The tool we will use is a python notebook, to access a python notebook, it can be accessed using a local computer by downloading “Jupyter Notebook” or “Anaconda” which already has a Jupyter Notebook in it. Can also use the Cloud like google collab or Kaggle notebook.</p><blockquote>Google collab : <a href="https://colab.research.google.com/">https://colab.research.google.com/</a></blockquote><blockquote>Kaggle Notebook: <a href="https://www.kaggle.com/code">https://www.kaggle.com/code</a></blockquote><p>Before retrieving and analyzing the first data, it is necessary to install several packages, the main package used in this scrapping is <strong>Advertools</strong>. For complete documentation, please refer to the following link:</p><p><a href="https://advertools.readthedocs.io/en/master/">advertools - Python</a></p><p>Let’s code, First install some packages:</p><pre>!pip install pandas <br>!pip install numpy<br>!pip install advertools </pre><p>Note: the installation can be done on the console and notebook, if you use the console when installing do not use “!” before writing code. Next, import each package above:</p><pre>import pandas as pd <br>import numpy as np <br>import advertools as adv</pre><p>Furthermore, for the scrapping process, access to the Twitter API key is also required, where you can get it in the documentation</p><p><a href="https://developer.twitter.com/en/docs/twitter-api">https://developer.twitter.com/en/docs/twitter-api</a></p><p>or for more detailed step-by-step how to get it you can also see some tutorials here on youtube or in other articles. If you are having trouble getting the Twitter API key you can use my Twitter API key temporarily by accessing the following link</p><p><a href="https://drive.google.com/file/d/19RPjWjbW-3ztVEelKAtc5RZzgWmXmNej/view?usp=sharing">Meet Google Drive - One place for all your files</a></p><pre>auth_params = {<br>&#39;app_key&#39;: &quot;xxxxxxxxxxxxxxxxxxxxxxxx&quot;,<br>&#39;app_secret&#39;: &quot;xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&quot; ,<br>&#39;oauth_token&#39;: &quot;xxxxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxx&quot;,<br>&#39;oauth_token_secret&#39;:&quot;xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&quot;,<br>}<br>adv.twitter.set_auth_params(**auth_params)</pre><h3>SCRAPPING DATA</h3><h4><strong>A. DATA BASED ON-SCREEN NAME</strong></h4><p>We can analyze and retrieve the data from the twitter account we already know. like from marvels, football clubs, basketball clubs, exes, girlfriends, and friends provided we know their username.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*7xqW3RhuB3jo6YKDX29-Zw.png" /></figure><p>For the example above, “Marvel Entertainment” is the “Twitter name” and “@Marvel” is the “screen name”. the parameter needed for the scrapping process is “screen name” namely “@Marvel” Furthermore, there are some data that can be analyzed from these key parameters:</p><h4><strong>1. Get User LookUp</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*nwXP6Nxtfuc7j-n4N4uuPg.jpeg" /></figure><p>User Lookup contains a description of the user, such as name, screen_name, location, description, URL, total followers, total friends, total lister, a total status that has been created, total status that has been liked, and others. Where there are 44 columns/variables obtained in collecting data this time. Start to code.</p><pre>lookup_user = adv.twitter.lookup_user(screen_name = &#39;Marvel&#39;)<br>print(lookup_user.shape)<br>lookup_user.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-3tR3BYy5dKyg93vLBPomw.jpeg" /></figure><p>Besides being able to specify the screen_name parameter, there are several parameters to customize the captured data, the following parameters are include_entities, trim_user, map, include_exl_alt_text, include_card_uri, and tweet_mode.</p><h4>2. Get User Time Line</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*wpwsP1FiLQwv_ZBSySqs6w.png" /></figure><p>The user timeline is a tweet made by the user, either in the form of the tweet itself, reply, or retweet. There are several main parameters used, namely <strong>“user_name”</strong> and <strong>“count”</strong>. the count is the number of tweets that we will take the user data. There are several columns/variables that we get, namely the time of making the tweet, <strong>full-text tweet, user_name, mentions, hashtags, total favorites, total retweets, user descriptions, and others</strong>. There are<strong> 75 columns/variables</strong> obtained in this scrapping.</p><pre>timeline = adv.twitter.get_user_timeline(screen_name=&#39;Marvel&#39;,count=100)<br>print(timeline.shape)<br>timeline.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ch6yZfavdV7DpGDkGwajSQ.png" /></figure><p>Besides being able to specify the screen_name and count parameters, there are several parameters to customize the data taken, the following parameters are user_id, since_id, max_id, trim_user, exclude_replies, include_rts, and tweet_mode.</p><h4>3. Get Favorites</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*ZrJCTQUuxvYJT_xx9fo5EQ.png" /></figure><p>As in the picture above, get user favorite is the get tweet, or reply that is liked by the user. For parameter variables and variables obtained are the same as scrapping get user timeline.</p><pre>get_favorites = adv.twitter.get_favorites(screen_name=&#39;Marvel&#39;, count=100)<br>print(get_favorites.shape)<br>get_favorites.head(3)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*igeOrpWzsRLDC2FHDL69jw.png" /></figure><h4>4. Get Followers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*cAAmGnR2yEf9k-8eNHdgMg.png" /></figure><p>In addition to being able to retrieve data in the form of tweets, we can also retrieve data in the form of <strong>user information</strong>, one of which is the user information of the Twitter followers. Here there are 2 scrappings:</p><ul><li><strong>Scrapping id followers</strong>, In data retrieval, only the id, can retrieve relatively large amounts of data in a relatively fast time. The amount of data generated in one request is 5000 data. We can make several requests as needed. However, the drawback is that we can’t get detailed user screen name information. The main parameter needed is screen_name, and some additional parameters are cursor, stringifiy_ids, and count.</li></ul><pre>get_followers_ids = adv.twitter.get_followers_ids( screen_name=&quot;Marvel&quot;, count = 10000)</pre><pre>print(len(get_followers_ids[&#39;ids&#39;]))<br>get_followers_ids</pre><p><strong>Output:</strong><br>1000 <br>{&#39;previous_cursor&#39;: 0,<br> &#39;next_cursor&#39;: 1710813885960930399,<br> &#39;ids&#39;: [1437949410021978117,<br> 1437948541901713409,<br> 1437947905420058628,<br> 1336494026925740032,<br> 1437948713834483713,<br> 782688591331766272,<br> 1381602541243310085,<br> 1437948842566160385,<br> 1437949440740904961, … }</p><ul><li><strong>Scrapping User Description Followers, </strong>In collecting this data, we get complete data, namely <em>name, screen_name, location, description, followers count, friends count, listed count, and others</em>. However, the drawback in this scrapping is the relatively small amount of data compared to scrapping IDs, with the amount of data obtained in 1 x request is 100 data. The main parameters used in this scrapping are screen_name and count, and some additional parameters are user_id, cursor, skip_status, include_user_entities. The number of variables or column data obtained is 48 columns.</li></ul><pre>get_followers_list = adv.twitter.get_followers_list(screen_name= &quot;Marvel&quot; , count=100)<br>print(get_followers_list.shape)<br>get_followers_list.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3VnflpPy5QSh0G9NeT1FFQ.png" /></figure><h4>5. Get Following/Friend</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*gAS8e3dMKSvwF-LsxMK-3w.png" /></figure><p>Get friend is to retrieve the following user’s data. As shown above. The parameters and variables obtained in this scrapping are the same as getting followers. There are 2 scams.</p><ul><li><strong>Scrapping id Following</strong></li></ul><pre>get_friends_ids = adv.twitter.get_friends_ids( screen_name=&quot;Marvel&quot;, count =10000 )<br>print(len(get_friends_ids[&#39;ids&#39;]))<br>get_friends_ids</pre><p>Output:<br>781<br>{&#39;previous_cursor&#39;: 0,<br> &#39;next_cursor&#39;: -1,<br> &#39;ids&#39;: [155709853,<br> 1152753054782910464,<br> 1086709184874377217,<br> 2401098489,<br> 1148979262659145728,<br> 1152749683938222080, … }</p><ul><li><strong>Scrapping User Description Followers</strong></li></ul><pre>get_friends_list = adv.twitter.get_followers_list(screen_name= “Marvel” , count=200)<br>print(get_friends_list.shape)<br>get_friends_list.head(3)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I_T8MB6dvmxupuY7MFziRA.png" /></figure><h4><strong>B. DATA BASED ON TWITTER POST</strong></h4><p>After analyzing Twitter based on a username by taking some information such as timeline, likes, followers, following, and lookup. Next, we will analyze Twitter based on Twitter posts. We can access the Twitter post on the web with the data in the tweet_id column that we got in the previous scrapping. As an example:</p><p>If you have tweet_id: 1426928601610416135.</p><p>So to access the tweet, it is enough to add tweet_id to the following URLs</p><p><a href="https://twitter.com/anyuser/status/&lt;tweet">https://twitter.com/anyuser/status/&lt;tweet_id&gt;</a></p><p>Ex: <a href="https://twitter.com/anyuser/status/&lt;tweet">https://twitter.com/anyuser/status/1438874044107948039</a></p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L4VKYvSPw4X1UqX10KTmUg.png" /></figure><p>Above is the URL used to access Twitter using tweet_id. Next, let’s scrapping some of the information we got from the Twitter post entities:</p><h4>1. Get Post LookUp</h4><p>By knowing the tweet_id we can take a description of the tweet, such as, tweet_full_text, who mentions, what hashtag I used, the number of retweets, the number of likes, replies, and others. There are 72 columns that we will get in this scrapping.</p><pre>lookup_status = adv.twitter.lookup_status(id = 1439010395587555333 )<br>print(lookup_status.shape)<br>lookup_status</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dp6v1b9VOm9yKsHriPFpMA.png" /></figure><h4>2. Get User Retweeted Post</h4><p>Furthermore, we can also scrape the retweet data from the tweet_id that we have, namely info about the user who retweeted our post, the data presented in the form of 2 types, namely tweet_id and a list of user descriptions. Conceptually, scrapping retweets based on tweet_id is the same as scrapping followers based on usernames.</p><ul><li><strong>Scrapping id retweeters</strong></li></ul><pre>retweet_id = adv.twitter.get_retweeters_ids(id=1439010395587555333)<br>print(len(retweet_id[&#39;ids&#39;]))<br>retweet_id</pre><p>Output:<br>{&#39;previous_cursor&#39;: 0,<br> &#39;next_cursor&#39;: 0,<br> &#39;ids&#39;: [816170048,<br> 391409829,<br> 1066800427423944705,<br> 1054503376514441217,<br> 870775262694318080,<br> 1421682772364513282,…]}</p><ul><li><strong>Scrapping User Description Retweeters</strong></li></ul><pre>retweet = adv.twitter.get_retweets(id =1439010395587555333)<br>print(retweet.shape)<br>retweet.head(3)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*fTfr9ritWq30nGz4G6vrew.png" /></figure><h4><strong>C. DATA BASED ON OWN ACCOUNT</strong></h4><p>On Twitter we also retrieve data based on our own account, our scrapper account is determined by the developer account that we use to access the Twitter API key, if you use my developer API key then the data that will be retrieved is my data. If you want to retrieve data about yourself you will need to have your own developer account and use your own API key.</p><h4>1. Get Home Timeline</h4><p>This scrapping is one of the unique scrapping and different from other types of scraping because each time we scrapping can produce different data according to the timeline view that we have on the Twitter app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*ekoCGkz-dZGR0UpSjnhKSg.png" /></figure><pre>home_timeline = adv.twitter.get_home_timeline()<br>print(home_timeline.shape)<br>home_timeline.head(3)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oc9mgsbXdtWN3YBonau89w.png" /></figure><h4>2. Get Retweeted</h4><p>This is my post data that was retweeted by other people, remember not the status that I retweeted. But my status was retweeted by another user.</p><pre>retweet_ofme = adv.twitter.retweeted_of_me(count = 100 )<br>print(retweet_ofme.shape)<br>retweet_ofme.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m3b5bkwcCRgdMRnZe6aH0Q.png" /></figure><h4>3. Get Mentioned</h4><p>Mention timeline is tweet data that has to mention me in it. Whether it’s a tweet, reply, or retweet quote.</p><pre>mention_timeline = adv.twitter.get_mentions_timeline(count=100)<br>print(mention_timeline.shape)<br>mention_timeline.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PlR0jh7klEjLEL0l5peWzw.png" /></figure><h4><strong>D. DATA BASED ON LIST</strong></h4><p>Twitter Lists allow you to customize, organize and prioritize the Tweets you see in your timeline. You can choose to join Lists created by others on Twitter, or from your own account, you can choose to create Lists of other accounts by group, topic, or interest. Viewing a List timeline will show you a stream of Tweets from only the accounts on that list. You can also pin your favorite Lists to the top of your Home timeline so you never miss a Tweet from the accounts that are most important to you.</p><p>How to discover lists? In your Home timeline on Twitter for iOS and Android apps, you might see a prompt to <strong>Discover new Lists</strong>. If we suggest a List to you that’s of interest, simply tap <strong>Follow</strong>. From the prompt, you can also tap <strong>Show more</strong> to browse through our Lists discovery page. There, we will show you more Lists we might think you’d like to follow and you can search for additional Lists in the search box at the top of the page.</p><p>We’ll also show you top Tweets from the Lists you follow right in your Home timeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*yfzVrQSVSbzkV7XOsDPcQw.png" /></figure><p>The next data we can scrapping is a list. There are some data that we can scan based on the list. There are 2 main parameters that we can use for scrapping lists, namely id_list and user_name list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*Kgc82pkt21qe7MeEAMYejQ.png" /></figure><p>The id_list can be found on the Twitter list URL, in the picture above the id_list is 1296872799932473345 and the user name list is @LearnedVector . after knowing these two parameters let’s code.</p><h4>1. Get List Post</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*Vp2MH_Fm-WiWu4hZt52Uag.png" /></figure><p>Scraping the status of the list. The parameter to be used is list_id.</p><pre>list_statuses = adv.twitter.get_list_statuses(list_id=1214912982846590976)<br>print(list_statuses.shape)<br>list_statuses.head(3)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lquuafamrIm-zaC8uYhJPg.png" /></figure><h4>2. Get List Subscribers</h4><pre>list_subscribers = adv.twitter.get_list_subscribers(list_id =1214912982846590976)<br>print(list_subscribers.shape)<br>list_subscribers.head(3)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1GjLjH65epnoWR8sC1Y9fg.png" /></figure><h4>3. Get List Subscriptions</h4><pre>list_subscriptions = adv.twitter.get_list_subscriptions(user_id = &#39;benthecoder1&#39;)<br>print(list_subscriptions.shape)<br>list_subscriptions.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q40LHDAkVUW_lCuhniI-rg.png" /></figure><h4>4. Get Members List</h4><pre>list_members = adv.twitter.get_list_members(list_id=1214912982846590976)<br>print(list_members.shape)<br>list_members.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ULe7XY_-m2MHe-XnF70qrw.png" /></figure><h4><strong>E. ANOTHER DATA</strong></h4><h4>1. Get Trending Twitter</h4><p>Trending twitter is widely mentioned or discussed on the internet, especially on social media Twitter. Each place has a different trending topic, each country, and region has its own trending. Therefore, before we scrapping Twitter trending data, we must determine which area we will be scraping and the id for that area. Therefore, let’s check the data list through the following code.</p><pre>available = adv.twitter.get_available_trends()<br>print(available.shape)<br>available</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BE5N7hrcBkKpKEAlUi_MaQ.png" /></figure><p>There are 8 columns and 467 rows, these 467 rows contain trending locations around the world, for each country or a certain region. For scrapping this time we will be scrapping the Indonesian state data with id 23424846.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*5NMD7nFMT_L1c2n92IzE6w.png" /></figure><pre>trend = adv.twitter.get_place_trends(ids = 23424846 )<br>print(trend.shape)<br>trend</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*--DMEbYg8U73-3KDJCr8Ag.png" /></figure><p>There are 50 top trendings obtained, and several columns containing trending, location, tweet_volume, local__rank, and others.</p><h4>2. Get Search User</h4><p>Search User allows us to retrieve search data for the user. For example, if we search for “marvel” it will generate several accounts related to “marvel”, as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ghAL9-e8VOouj36Voh2UAQ.png" /></figure><pre>search_user = adv.twitter.search_users(q = &#39;marvel&#39;, count=100)<br>print(search_user.shape)<br>search_user.head(3)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2X0xevoQkJmH4UQNYLqTuQ.png" /></figure><h4>3. Get Search</h4><p>The search method will generate tweets related to the generated keywords.</p><pre>df = adv.twitter.search(q = &quot;avengers&quot;, count = 100)<br>print(df.shape)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*eV-o2Ws5qpGVywWPSDwtDg.png" /></figure><p>In detail about the search scrapping tweet can be seen in one of my articles are:</p><p><a href="https://medium.com/analytics-vidhya/simple-scrapping-data-twitter-part-1-series-twitter-data-7a096c906103">Simple Scrapping Data Twitter (Series Twitter Data)</a></p><p>Thank you for reading this article. Hopefully, this article can be useful and helpful in the development of data. don’t forget to follow and give a lot of claps. See you next time.</p><p>Source:</p><p><a href="https://advertools.readthedocs.io/en/master/advertools.twitter.html">https://advertools.readthedocs.io/en/master/advertools.twitter.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d984bccab37" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/complete-scrapping-of-twitter-data-series-twitter-data-9d984bccab37">Complete Scrapping of Twitter Data (Series Twitter Data)</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple Scrapping Data Twitter (Series Twitter Data)]]></title>
            <link>https://medium.com/analytics-vidhya/simple-scrapping-data-twitter-part-1-series-twitter-data-7a096c906103?source=rss-2a3bbaeb7847------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a096c906103</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[scraping]]></category>
            <category><![CDATA[twitter]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Imam Muhajir]]></dc:creator>
            <pubDate>Sun, 15 Aug 2021 13:40:02 GMT</pubDate>
            <atom:updated>2021-09-15T16:29:36.023Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ytpoz6yDT6cumb9pW3OL3A.jpeg" /></figure><p>Twitter is a free social networking microblogging service that allows registered members to broadcast short posts called tweets. Twitter members can broadcast tweets and follow other users&#39; tweets by user multiple platforms and devices. You can access Twitter via the web or your mobile device. To share information on Twitter as widely as possible, we also provide companies, developers, and users with programmatic access to Twitter data throughout API.</p><p>For access to Twitter, the first we must have:</p><p>1. API Key</p><p>2. Api Secret Key</p><p>3. Access Token</p><p>4. Access Token Secret</p><p>To getting the access token you can look in here.</p><p><a href="http://For get the access token you can look in here. https://developer.twitter.com/en/docs/twitter-api/getting-started/getting-access-to-the-twitter-api">https://developer.twitter.com/en/docs/twitter-api/getting-started/getting-access-to-the-twitter-api</a></p><p>LET&#39;S GO TO CODE</p><p><strong>1. Setting Environment</strong></p><p>open code script or notebook code. We can use a notebook. Lets to access the notebook in google collaboratory.</p><p><a href="https://colab.research.google.com/">https://colab.research.google.com/</a></p><p>And new notebook create until you are ready</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*4LaUbF1JGmTaQBW4ngLtaw.png" /></figure><p>2. Install and Import Library</p><p>The library that will be used in this scrapping is advertools. so before that install the library on your computer.</p><p>in notebook code:</p><pre>!pip install advertools</pre><p>in cmd/terminal code:</p><pre>pip install advertools</pre><p>so, import your library:</p><pre>Import pandas as pd</pre><pre>Import numpy as np</pre><pre>import advertools as adv</pre><p>3. Setting Token Access Twitter</p><pre>auth_params = {</pre><pre>&#39;app_key&#39;: &quot;xxxxxxxxxxxxxxxxxxxxxxx&quot;,</pre><pre>&#39;app_secret&#39;: &quot;xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&quot; ,</pre><pre>&#39;oauth_token&#39;: &quot;xxxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxx&quot;,</pre><pre>&#39;oauth_token_secret&#39;:&quot;xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&quot;,</pre><pre>}</pre><pre>adv.twitter.set_auth_params(**auth_params)</pre><p>if you want so easy to get API, you can use my API.</p><p><a href="https://drive.google.com/file/d/19RPjWjbW-3ztVEelKAtc5RZzgWmXmNej/view?usp=sharing">Meet Google Drive - One place for all your files</a></p><p>Data that want get in this article is:</p><p>1. Get data from search keyword</p><p>This method can get all of the data about the keyword. For example, if you search “avengers” the result is tweeted that contain “avenger topic” so you can get tweet data this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*IYiOYbmz94nHBN8R_RDiKA.png" /></figure><p>So let go to scrap:</p><pre>input_keyword = &quot;avengers&quot;<br>count_data = 200</pre><pre>df = adv.twitter.search(q = input_keyword, geocode=None, lang=None, locale=None, result_type=None, count=count_data, until=None, since_id=None, max_id=None, include_entities=None, tweet_mode=None)</pre><p>You can customize the parameters of the scraper. So we can explain so detail every parameter because this is so powerful for you.</p><p><strong>q = is the main parameter keyword for scrapping</strong></p><p>(str — required) A UTF-8, URL-encoded search query of 500 characters maximum, including operators. Queries may additionally be limited by complexity.</p><p>Many kinds of value for the keyword.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*v81QX_tCV9jBQG8cQgMnqw.png" /></figure><ul><li><strong>geocode</strong> — (lat long dist — optional) Returns tweets by users located within a given radius of the given latitude/longitude. The location is preferentially taking from the Geotagging API but will fall back to their Twitter profile. The parameter value is specified by ” latitude, longitude, radius “, where radius units must be specified as either ” mi ” (miles) or ” km ” (kilometers). Note that you cannot use the near operator via the API to geocode arbitrary locations; however, you can use this geocode parameter to search near geocodes directly. A maximum of 1,000 distinct “sub-regions” will be considered when using the radius modifier.</li><li><strong>lang</strong> — (str — optional) Restricts tweets to the given language, given by an ISO 639–1 code. Language detection is best-effort.</li><li><strong>locale</strong> — (str — optional) Specify the language of the query you are sending (only ja is currently effective). This is intended for language-specific consumers and the default should work in the majority of cases.</li><li><strong>result_type</strong> — (str — optional) Optional. Specifies what type of search results you would prefer to receive. The current default is “mixed.” Valid values include: * mixed: Include both popular and real-time results in the response. * recent: return only the most recent results in the response * popular: return only the most popular results in the response.</li><li><strong>count</strong> — (int — optional) Specifies the number of results to retrieve.</li><li><strong>until</strong> — (date — optional) Returns tweets created before the given date. The date should be formatted as YYYY-MM-DD. Keep in mind that the search index has a 7-day limit. In other words, no tweets will be found for a date older than one week.</li><li><strong>since_id</strong> — (int — optional) Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets that can be accessed through the API. If the limit of Tweets has occurred since the since_id, the since_id will be forced to the oldest ID available.</li><li><strong>max_id</strong> — (int — optional) Returns results with an ID less than (that is, older than) or equal to the specified ID.</li><li><strong>include_entities</strong> — (bool — optional) The entities node will not be included when set to False.</li><li><strong>tweet_mode</strong> — (str — optional) Valid request values are compat and extended, which give compatibility mode and extended mode, respectively for Tweets that contain over 140 characters</li></ul><p>so, after that all, try to show data from scrapping</p><pre>print(df.shape)</pre><pre>print(df.head)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*9FSif5H9lqSCh4oMI8hQ6g.png" /></figure><p>Columns of data are 79 column representation info for 1 tweet data, and 200-row representation 200 data tweet we get.</p><p>Thank you very much</p><p>Source:</p><p><a href="https://whatis.techtarget.com/definition/Twitter">https://whatis.techtarget.com/definition/Twitter</a></p><p><a href="https://advertools.readthedocs.io/en/master/advertools.twitter.html">https://advertools.readthedocs.io/en/master/advertools.twitter.html</a></p><p><a href="https://developer.twitter.com/">https://developer.twitter.com/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a096c906103" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/simple-scrapping-data-twitter-part-1-series-twitter-data-7a096c906103">Simple Scrapping Data Twitter (Series Twitter Data)</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spatial Visualization and Network Analysis with Geo Pandas Python]]></title>
            <link>https://medium.com/analytics-vidhya/spatial-visualization-and-network-analysis-with-geo-pandas-python-60bfc48396c8?source=rss-2a3bbaeb7847------2</link>
            <guid isPermaLink="false">https://medium.com/p/60bfc48396c8</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[earthquake]]></category>
            <dc:creator><![CDATA[Imam Muhajir]]></dc:creator>
            <pubDate>Thu, 23 Jan 2020 07:46:35 GMT</pubDate>
            <atom:updated>2021-09-15T16:34:40.693Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DgLCASHv1nQg9gVaQRceHA.png" /></figure><p>Spatial data refers to all types of data objects or elements that are present in a geographical space or horizon. It enables the global finding and locating of individuals or devices anywhere in the world.</p><p>Spatial data is used in geographical information systems (GIS) and other geolocation or positioning services. Spatial data consists of points, lines, polygons, and other geographic and geometric data primitives, which can be mapped by location. Spatial data may be classified as scalar or vector data. Each provides distinct information pertaining to geographical or spatial locations. In this section, we can explain two types of data spatial points, spatial lines, and spatial polygons.</p><h3>1. Spatial Polygon</h3><p>In python for building with Geo pandas, you can install geo pandas in jupyter notebook with environmental Anaconda,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*N5p--HuDYh4mOCgJ5aw8jw.jpeg" /></figure><pre>pip install geopandas</pre><p>However, if you have a problem with your laptop you can use the notebook in kaggle.com, in Kaggle notebook you don’t need to install packages, Kaggle already has the geopandas package. To get data frame polygon you can search on internet, for example, you can download in my link <a href="https://www.kaggle.com/imammuhajir/map-data/settings">https://www.kaggle.com/imammuhajir/map-data/settings</a></p><p>or</p><p><a href="http://www.info-geospasial.com/2015/10/data-shp-seluruh-indonesia.html">http://www.info-geospasial.com/2015/10/data-shp-seluruh-indonesia.html</a></p><p>let’s go to try in Kaggle notebook :</p><pre>import numpy as np<br>import pandas as pd <br>import matplotlib.pyplot as plt<br>import geopandas as gpd</pre><pre>import os<br>for dirname, _, filenames in os.walk(&#39;/kaggle/input&#39;):<br>    for filename in filenames:<br>        print(os.path.join(dirname, filename))</pre><p>import data shp</p><pre>indo = gpd.read_file(&quot;/kaggle/input/map-data/INDONESIA_PROP.shp&quot;)<br>indo.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*x79l7mO27C1MGwOJxvPtnQ.png" /></figure><p>now, you can try visualization with polygon data, with package geopandas make visualization so easy …</p><pre>indo.plot(column=&#39;Propinsi&#39;, cmap=&#39;Set1&#39;, legend=True, figsize = (30,40))<br>plt.title(&#39;TITIK GEMPA&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8tm7EewJQeZ0poJ0NNIo6A.png" /></figure><p>this is visualisation polygon, now you can try filter region you can do …</p><h3>Filter Geo Pandas</h3><p>we just get region ‘’ “SUMATERA UTARA”, “SUMATERA BARAT”,”JAWA TENGAH”,”PROBANTEN”, “DI. ACEH”,”JAWA TIMUR”,”JAWA BARAT” ,”LAMPUNG” ,”DKI JAKARTA” ,”RIAU”, “JAMBI”,”BANGKA BELITUNG” ,”SUMATERA SELATAN”,”DAERAH ISTIMEWA YOGYAKARTA”</p><pre># get data <br>geo_df = gpd.read_file(&quot;/kaggle/input/map-data/INDONESIA_PROP.shp&quot;)</pre><pre># data can get <br>filter_sumatra_jawa = [ &quot;SUMATERA UTARA&quot;, &quot;SUMATERA BARAT&quot;,&quot;JAWA TENGAH&quot;,&quot;PROBANTEN&quot;,&quot;DI. ACEH&quot;,&quot;JAWA TIMUR&quot;,&quot;JAWA BARAT&quot; ,&quot;LAMPUNG&quot; ,&quot;DKI JAKARTA&quot;,&quot;RIAU&quot;, &quot;JAMBI&quot;,&quot;BANGKA BELITUNG&quot; ,&quot;SUMATERA SELATAN&quot;,&quot;DAERAH ISTIMEWA YOGYAKARTA&quot;]</pre><pre>ori_len = len(geo_df)<br>geo_df[&#39;Wilayah&#39;] = list(range(len(geo_df)))</pre><pre># filter data <br>for i in range(ori_len):<br>    if geo_df[&#39;Propinsi&#39;][i] in filter_sumatra_jawa :<br>        geo_df[&#39;Wilayah&#39;][i] = 1<br>    else:<br>        geo_df[&#39;Wilayah&#39;][i] = 0<br>geo_df = geo_df[geo_df[&#39;Wilayah&#39;] == 1]</pre><pre>geo_df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q-PL8ZZNnBD0tXMpgZLS9g.png" /></figure><p>Visualization again…</p><pre>leg_kwds = {&#39;title&#39;:&#39;NAMA WILAYAH&#39;, &#39;loc&#39;:&#39;upper left&#39;,&#39;bbox_to_anchor&#39;:(1,1.05), &#39;ncol&#39;:1}</pre><pre>geo_df.plot(column=&#39;Propinsi&#39;, cmap=&#39;Set1&#39;, legend=True, legend_kwds = leg_kwds, figsize = (20,50))</pre><pre>plt.title(&#39;TITIK GEMPA&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rSQgzMKCvuY2KuChy3tCnA.png" /></figure><h3>2. Spatial Point and Spatial Polygon</h3><p>In this visualization we can use earthquake data, you can download data from the link <a href="https://www.kaggle.com/imammuhajir/data-gempa">https://www.kaggle.com/imammuhajir/data-gempa</a></p><p>This data contains the coordinate location(latitude and longitude), a combination of two variables can make the point location in your map.</p><pre>train_09 = pd.read_csv(&#39;/kaggle/input/data-gempa/2009.csv&#39;)<br>train_10 = pd.read_csv(&#39;/kaggle/input/data-gempa/2010.csv&#39;)<br>train_11 = pd.read_csv(&#39;/kaggle/input/data-gempa/2011.csv&#39;)<br>train_12 = pd.read_csv(&#39;/kaggle/input/data-gempa/2012.csv&#39;)<br>train_13 = pd.read_csv(&#39;/kaggle/input/data-gempa/2013.csv&#39;)<br>train_14 = pd.read_csv(&#39;/kaggle/input/data-gempa/2014.csv&#39;)<br>train_15 = pd.read_csv(&#39;/kaggle/input/data-gempa/2015.csv&#39;)<br>train_16 = pd.read_csv(&#39;/kaggle/input/data-gempa/2016.csv&#39;)<br>train_17 = pd.read_csv(&#39;/kaggle/input/data-gempa/2017.csv&#39;)<br>train_18 = pd.read_csv(&#39;/kaggle/input/data-gempa/2018.csv&#39;)<br>train_all = [train_09,train_10,train_11,train_12,train_13,train_14,train_15,train_16,train_17,train_18 ]</pre><pre># me replace name stiap data<br>for i in train_all:<br>    i.columns = [&#39;index&#39;, &#39;Date&#39;, &#39;Time&#39;, &#39;Latitude&#39;, &#39;Longitude&#39;,&#39;Depth&#39;,<br>              &#39;Magnitude&#39;, &#39;TypeMag&#39;, &#39;smaj&#39;, &#39;smin&#39;, &#39;az&#39;, &#39;rms&#39;, &#39;cPhase&#39;,<br>               &#39;Region&#39;]<br>    i.drop(0,axis=0,inplace=True)<br>    <br># menyatukan data mendjadi 1 <br>train = pd.concat(train_all)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nTNVJ1ywpBiimxxvrgxzLw.png" /><figcaption>t</figcaption></figure><p>This data is very dirty, there are still data that have multiple types, to calculate or visualize we have to change to numeric data, so let&#39;s go to <strong>Cleaning Data…</strong></p><pre># mengsplit data dan membersihkan nilai menjadi number<br>train[&quot;Longitude&quot;] = train.Longitude.apply(lambda x : x.split()[0])<br>train[&quot;Depth&quot;] = train.Depth.apply(lambda x : x.split()[0])<br>train[&quot;Magnitude&quot;] = train.Magnitude.apply(lambda x : x.split()[0])<br>train[&quot;Time&quot;] = train.Time.apply(lambda x : x.split()[0])</pre><pre># meng ekstrak data <br>train[&quot;year&quot;] = train.Date.apply(lambda x : x.split(&#39;/&#39;)[2])<br>train[&quot;date&quot;] = train.Date.apply(lambda x : x.split(&#39;/&#39;)[1])<br>train[&quot;month&quot;] = train.Date.apply(lambda x : x.split(&#39;/&#39;)[0])<br>train[&quot;hour&quot;] = train.Time.apply(lambda x : x.split(&#39;:&#39;)[0])</pre><pre>train[&quot;Date&quot;] = train.Date.apply(lambda x : x.split()[0])<br>train[&#39;Date&#39;] = train[[&#39;Date&#39;, &#39;Time&#39;]].apply(lambda x : &#39; &#39;.join(x), axis = 1)<br>train[&#39;Date&#39;] = pd.to_datetime(train[&#39;Date&#39;])</pre><pre>train.index = train[&#39;Date&#39;]</pre><pre>train_len = len(train)<br>for i in range(train_len):<br>    if train[&#39;Latitude&#39;][i].split()[1] == &#39;LS&#39;:<br>        train[&#39;Latitude&#39;][i] = float(train[&#39;Latitude&#39;][i].split()[0]) * -1<br>    else:<br>        train[&#39;Latitude&#39;][i] = train[&#39;Latitude&#39;][i].split()[0]</pre><pre>train.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*x1KRD_wWJeLdSK74OcNMig.png" /></figure><p>Change format data to float and filter for Indonesia country</p><pre>#convert type data ke float<br>columns = [&#39;Latitude&#39;,&#39;Longitude&#39;, &#39;Depth&#39;, &#39;Magnitude&#39;]<br>for var in columns:<br>    train[var] = train[var].astype(&quot;float64&quot;)</pre><pre># Filter indonesia<br>train = train.loc[((train[&#39;Latitude&#39;] &gt;= -12.5) &amp; (train[&#39;Latitude&#39;] &lt;= 7) &amp;  (train[&#39;Longitude&#39;] &gt;= 94.31644) &amp; (train[&#39;Longitude&#39;] &lt;= 142.71813) )]</pre><p>Visualization of spatial data with background polygon data and coordinate data.</p><pre>leg_kwds = {&#39;title&#39;:&#39;NAMA WILAYAH&#39;, &#39;loc&#39;:&#39;upper left&#39;, &#39;bbox_to_anchor&#39;:(1,1.05), &#39;ncol&#39;:1}<br>geo_df.plot(column=&#39;Propinsi&#39;, cmap=&#39;Set1&#39;, legend=True, legend_kwds = leg_kwds, figsize = (30,30))<br>plt.title(&#39;TITIK GEMPA&#39;)</pre><pre>plt.scatter(y= train.Latitude, x = train.Longitude , c = train.Magnitude, alpha=0.8);<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*10Xh6MdsPb8ZCNCyI7Y3ew.png" /></figure><p>Filter data based on magnitude values…</p><pre>train5 = train[train[&#39;Magnitude&#39;] &gt;= 5.5]</pre><pre>leg_kwds = {&#39;title&#39;:&#39;NAMA WILAYAH&#39;, &#39;loc&#39;:&#39;upper left&#39;, &#39;bbox_to_anchor&#39;:(1,1.05), &#39;ncol&#39;:1}<br>geo_df.plot(column=&#39;Propinsi&#39;, cmap=&#39;Set1&#39;, legend=True, legend_kwds = leg_kwds, figsize = (30,30))<br>plt.title(&#39;TITIK GEMPA&#39;)</pre><pre>plt.scatter(y= train5.Latitude, x = train5.Longitude , c = train5.Magnitude, alpha=0.8);<br>plt.show()</pre><h3>3. Analysis Network station seismic with earthquake</h3><p>To do an earthquake station network analysis with an earthquake, the first stage we have to determine the earthquake station itself because the data is not known the location of the station. To determine the location of the station we assume that earthquakes that have a “smin” of less than 0.3 are earthquakes that are close to the seismic station.<br>note: “smin” is the distance of the earthquake to the nearest station</p><p>Let’s look at the results of the filtering</p><pre>train_loc = train.copy()</pre><pre>train_loc = train_loc[train_loc.smin &lt; 0.3]</pre><pre>leg_kwds = {&#39;title&#39;:&#39;NAMA WILAYAH&#39;, &#39;loc&#39;:&#39;upper left&#39;, &#39;bbox_to_anchor&#39;:(1,1.05), &#39;ncol&#39;:1}<br>geo_df.plot(column=&#39;Propinsi&#39;, cmap=&#39;Set1&#39;, legend=True, legend_kwds = leg_kwds, figsize = (30 ,30))<br>plt.title(&#39;TITIK GEMPA&#39;)</pre><pre>plt.scatter(y= train_loc.Latitude, x = train_loc.Longitude, alpha=0.8);<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FhF1aNoJjGy1jLxdJb0pnw.png" /></figure><p>After knowing the distribution of earthquake data close to the station. we must determine the exact point at the earthquake station, therefore we use K-means clustering to determine that point.</p><pre>from sklearn.cluster import KMeans</pre><pre>train_clus = train_loc[[&#39;Latitude&#39;, &#39;Longitude&#39;]]<br>num_clusters = 152</pre><pre>km = KMeans(n_clusters=num_clusters, random_state = 1)<br>km.fit(train_clus)<br>clusters = km.labels_.tolist()</pre><pre>train_clus[&#39;Clustering&#39;] = clusters</pre><pre>loc_statiun = train_clus.groupby(&#39;Clustering&#39;).mean()<br>loc_statiun = loc_statiun.reset_index()</pre><p>Visualization result:</p><pre>leg_kwds = {&#39;title&#39;:&#39;NAMA WILAYAH&#39;, &#39;loc&#39;:&#39;upper left&#39;, &#39;bbox_to_anchor&#39;:(1,1.05), &#39;ncol&#39;:1}<br>geo_df.plot(column=&#39;Propinsi&#39;, cmap=&#39;Set1&#39;, legend=False, legend_kwds = leg_kwds, figsize = (30,30))<br>plt.title(&#39;Lokasi Statiun Gempa&#39;)</pre><pre>plt.scatter(y= loc_statiun.Latitude, x = loc_statiun.Longitude, marker=&#39;^&#39;, alpha=1, c = &#39;#1f77b4&#39;);<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9JV0jygE2IYvQSpCoiH-wg.png" /></figure><h3>Analysis of the earthquake station network with the nearest earthquake point</h3><p>Create a new feature: the distance between the station and the earthquake point, the name of the nearest earthquake station</p><pre>#from pandas.tools.plotting import scatter_matrix<br>from sklearn.model_selection import StratifiedShuffleSplit<br>from sklearn.preprocessing import LabelBinarizer<br>from sklearn.preprocessing import StandardScaler<br>from geopy.distance import vincenty</pre><pre>import gc</pre><pre>statiun_coords = {}</pre><pre>for dat in loc_statiun.iterrows():<br>    row = dat[1]<br>    <br>    statiun_coords[int(row[&#39;Clustering&#39;])] = (float(row[&#39;Latitude&#39;]), float(row[&#39;Longitude&#39;]))</pre><p>Function: find closest point Earthquake.</p><pre>def closest_point(location, location_dict):<br>    &quot;&quot;&quot; take a tuple of latitude and longitude and <br>        compare to a dictionary of locations where<br>        key = location name and value = (lat, long)<br>        returns tuple of (closest_location , distance) &quot;&quot;&quot;<br>    closest_location = None<br>    for city in location_dict.keys():<br>        distance = vincenty(location, location_dict[city]).kilometers<br>        if closest_location is None:<br>            closest_location = (city, distance)<br>        elif distance &lt; closest_location[1]:<br>            closest_location = (city, distance)<br>    return closest_location</pre><pre>train_clus[&#39;close_station&#39;] = train_clus.apply(lambda x: closest_point((x[&#39;Latitude&#39;],x[&#39;Longitude&#39;]), statiun_coords), axis = 1)</pre><pre>train_clus[&#39;close_station_name&#39;] = [x[0] for x in train_clus[&#39;close_station&#39;].values]<br>train_clus[&#39;close_station_dist&#39;] = [x[1] for x in train_clus[&#39;close_station&#39;].values]</pre><pre>train[&#39;close_station&#39;] = train.apply(lambda x: closest_point((x[&#39;Latitude&#39;],x[&#39;Longitude&#39;]), statiun_coords), axis = 1)<br>train[&#39;close_station_name&#39;] = [x[0] for x in train[&#39;close_station&#39;].values]<br>train[&#39;close_station_dist&#39;] = [x[1] for x in train[&#39;close_station&#39;].values]</pre><pre>train.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l60tAolbaIra4mB8zvJdsQ.png" /></figure><p>Visualization network</p><pre>train.plot(kind=&#39;scatter&#39;, x=&#39;Longitude&#39;, y=&#39;Latitude&#39;,  marker=&#39;^&#39;, alpha=1, c = &#39;#1f77b4&#39;, figsize= (30, 10 )<br>    )</pre><pre>for line in train.iterrows():<br> dat = line[1]<br> x1 = dat[&#39;Longitude&#39;]<br> y1 = dat[&#39;Latitude&#39;]<br> p2 = statiun_coords[dat[&#39;close_station_name&#39;]]<br> x2 = p2[1]<br> y2 = p2[0]<br> plt.plot([x1,x2],[y1, y2], &#39;k-&#39;,linewidth=0.5)<br>    <br>    <br>#plt.imshow(peta_gempa,  extent=[ 93 , 118.5, -13.3 , 7.7], alpha=0.9)<br>#plt.imshow(peta_gempa,  extent=[ 90 , 115.5, -14.7 , 7.9], alpha=1)<br>plt.ylabel(&quot;Latitude&quot;, fontsize=14)<br>plt.xlabel(&quot;Longitude&quot;, fontsize=14)<br>plt.title(&quot;Map Jaringan Lokasi Stasiun dengan Gempa&quot;, fontsize = 20)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-te82pjyffoAOwrtYvLJWw.png" /></figure><p>Network with filter magnitude 5.5</p><pre>train5 = train[train[&#39;Magnitude&#39;] &gt;= 5.5]</pre><pre># graph of vectors connecting points to their nearest city</pre><pre>train5.plot(kind=&#39;scatter&#39;, x=&#39;Longitude&#39;, y=&#39;Latitude&#39;,  marker=&#39;^&#39;, alpha=1, c = &#39;#1f77b4&#39;, figsize = (30, 10)<br>    )</pre><pre>for line in train5.iterrows():<br>    <br> dat = line[1]<br> x1 = dat[&#39;Longitude&#39;]<br> y1 = dat[&#39;Latitude&#39;]<br> p2 = statiun_coords[dat[&#39;close_station_name&#39;]]<br> x2 = p2[1]<br> y2 = p2[0]<br>    <br> plt.plot([x1,x2],[y1, y2], &#39;k-&#39;,linewidth=0.5)<br>    <br>    <br>#plt.imshow(peta_gempa,  extent=[ 93 , 118.5, -13.3 , 7.7], alpha=0.9)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5v-oGP9Gj3ceetuBWRasyQ.png" /></figure><p>Thank you for reading, you can find the complete code in my Kaggle notebook</p><p><a href="https://www.kaggle.com/imammuhajir/visualisation">visualisation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60bfc48396c8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/spatial-visualization-and-network-analysis-with-geo-pandas-python-60bfc48396c8">Spatial Visualization and Network Analysis with Geo Pandas Python</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ridge Regression with Multicollinearity in Pyhton]]></title>
            <link>https://medium.com/analytics-vidhya/ridge-regression-with-multicollinearity-in-pyhton-c8f6f3385e4c?source=rss-2a3bbaeb7847------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8f6f3385e4c</guid>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[ridge-regression]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[towards-data-science]]></category>
            <category><![CDATA[data-mining]]></category>
            <dc:creator><![CDATA[Imam Muhajir]]></dc:creator>
            <pubDate>Sat, 27 Apr 2019 06:44:33 GMT</pubDate>
            <atom:updated>2021-08-26T10:08:33.166Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gJqw6ULeA4YL5vXWn9j0OQ.png" /></figure><p><strong>Definition Ridge Regression</strong></p><p>Ridge Regression is a technique for analyzing multiple regression data that suffer from multicollinearity, The particular kind used by ridge regression is known as L2 regularization . In ridge regression, the penalty is the sum of the squares of the coefficients. L2 Regularization aka Ridge Regularization — This add regularization terms in the model which are function of square of coefficients of parameters. Coefficient of parameters can approach to zero but never become zero and hence.</p><p><strong>Multicollinearity</strong></p><p>Multicollinearity, or collinearity, is the existence of near-linear relationships among the independent variables.</p><p><strong>Effects of Multicollinearity</strong></p><p>Multicollinearity can create inaccurate estimates of the regression coefficients, inflate the standard errors of the<br>regression coefficients, deflate the partial t-tests for the regression coefficients, give false, nonsignificant, p-values, and degrade the predictability of the model (and that’s just for starters).</p><p><strong>Sources of Multicollinearity</strong></p><p>To deal with multicollinearity, you must be able to identify its source. The source of the multicollinearity impacts the analysis, the corrections, and the interpretation of the linear model. There are five sources (see Montgomery [1982] for details):</p><ol><li>Data collection. In this case, the data have been collected from a narrow subspace of the independent<br>variables. The multicollinearity has been created by the sampling methodology — it does not exist in the<br>population. Obtaining more data on an expanded range would cure this multicollinearity problem. The<br>extreme example of this is when you try to fit a line to a single point.</li><li>Physical constraints of the linear model or population. This source of multicollinearity will exist no<br>matter what sampling technique is used. Many manufacturing or service processes have constraints on<br>independent variables (as to their range), either physically, politically, or legally, which will create<br>multicollinearity.</li><li>Over-defined model. Here, there are more variables than observations. This situation should be avoided.</li><li>Model choice or specification. This source of multicollinearity comes from using independent variables<br>that are powers or interactions of an original set of variables. It should be noted that if the sampling<br>subspace of independent variables is narrow, then any combination of those variables will increase the<br>multicollinearity problem even further.</li><li>Outliers. Extreme values or outliers in the X-space can cause multicollinearity as well as hide it. We call<br>this outlier-induced multicollinearity. This should be corrected by removing the outliers before ridge<br>regression is applied</li></ol><p><strong>Detection of Multicollinearity</strong></p><p>There are several methods of detecting multicollinearity. We mention a few.</p><ol><li>Begin by studying pairwise scatter plots of pairs of independent variables, looking for near-perfect relationships. Also glance at the correlation matrix for high correlations. Unfortunately, multicollinearity does not always show up when considering the variables two at a time.</li><li>Consider the variance inflation factors (VIF). VIFs over 10 indicate collinear variables.</li><li>Eigenvalues of the correlation matrix of the independent variables near zero indicate multicollinearity. Instead of looking at the numerical size of the eigenvalue, use the condition number. Large condition indicate multicollinearity.</li><li>Investigate the signs of the regression coefficients. Variables whose regression coefficients are opposite in sign from what you would expect may indicate multicollinearity.</li></ol><p><strong>Correction for Multicollinearity</strong></p><p>Depending on what the source of multicollinearity is, the solutions will vary. If the multicollinearity has been created by the data collection, collect additional data over a wider X-subspace. If the choice of the linear model has increased the multicollinearity, simplify the model by using variable selection techniques. If an observation or two has induced the multicollinearity, remove those observations. Above all, use care in selecting the variables at the outset. When these steps are not possible, you might try ridge regression.</p><p><strong>Ridge Regression Models<br></strong>Following the usual notation, suppose our regression equation is written in matrix form as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*4LAWVCcRHkL9S7mdk9zjIA.png" /></figure><p>where <strong>Y</strong> is the dependent variable, <strong>X</strong> represents the independent variables, <strong>B</strong> is the regression coefficients to be estimated, and <strong>e</strong> represents the errors are residuals.</p><p>Hand on to Ridge Regression</p><pre>import mglearn<br>from sklearn.model_selection import train_test_split<br>X, y = mglearn.datasets.load_extended_boston()<br>X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)</pre><p>Out:</p><p>Training set score: 0.89<br>Test set score: 0.75</p><p>Ridge is a more restricted model, so this model overfit. A less complex model means worse performance on the training set, but if you over complex model, this is bad because can overfitt. How much importance the model places on simplicity versus training set performance can be specified by the user, using the alpha parameter. In the previous example, we used the default parameter alpha=1.0 . There is no reason why this will give us the best trade-off, though.<br>The optimum setting of alpha depends on the particular dataset we are using.<br>Increasing alpha forces coefficients to move more toward zero, which decreases training set performance but might help generalization. For example:</p><pre>ridge10 = Ridge(alpha=10).fit(X_train, y_train)</pre><pre>print(&quot;Training set score: {:.2f}&quot;.format(ridge10.score(X_train, y_train)))</pre><pre>print(&quot;Test set score: {:.2f}&quot;.format(ridge10.score(X_test, y_test)))</pre><p><strong>Out:</strong></p><p>Training set score: 0.79<br>Test set score: 0.64</p><p>Decreasing alpha allows the coefficients to be less restricted. For very small values of alpha , coefficients are barely restricted at all</p><pre>ridge01 = Ridge(alpha=0.1).fit(X_train, y_train)</pre><pre>print(&quot;Training set score: {:.2f}&quot;.format(ridge01.score(X_train, y_train)))</pre><pre>print(&quot;Test set score: {:.2f}&quot;.format(ridge01.score(X_test, y_test)))</pre><p><strong>Out:</strong></p><p>Training set score: 0.93<br>Test set score: 0.77</p><p>We can get a more qualitative insight into how the alpha parameter changes the model by inspecting the coef_ attribute of models with different values of alpha . A higher alpha means a more restricted model, so we expect the entries of coef_ to have smaller magnitude for a high value of alpha than for a low value of alpha .for out comparision we use Linear Regresssion. This is confirmed in the plot in:</p><pre>from sklearn.linear_model import LinearRegression<br>lr = LinearRegression().fit(X_train, y_train)</pre><pre>import matplotlib.pyplot as plt</pre><pre>plt.plot(ridge.coef_, &#39;s&#39;, label=&quot;Ridge alpha=1&quot;)<br>plt.plot(ridge10.coef_, &#39;^&#39;, label=&quot;Ridge alpha=10&quot;)<br>plt.plot(ridge01.coef_, &#39;v&#39;, label=&quot;Ridge alpha=0.1&quot;)<br>plt.plot(lr.coef_, &#39;o&#39;, label=&quot;LinearRegression&quot;)</pre><pre>plt.xlabel(&quot;Coefficient index&quot;)<br>plt.ylabel(&quot;Coefficient magnitude&quot;)<br>plt.hlines(0, 0, len(lr.coef_))<br>plt.ylim(-25, 25)<br>plt.legend()</pre><p><strong>Out:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mzaZzHaBErkZ_rIOwmcoGQ.png" /><figcaption>Comparing coefficient magnitudes for ridge regression with different values<br>of alpha and linear regression</figcaption></figure><p>Here, the x-axis enumerates the entries of coef_ : x=0 shows the coefficient associated with the first feature, x=1 the coefficient associated with the second feature, and so on up to x=100 . The y-axis shows the numeric values of the corresponding values of the coefficients. The main takeaway here is that for alpha=10 , the coefficients are mostly between around –3 and 3. The coefficients for the Ridge model with alpha=1 are somewhat larger. The dots corresponding to alpha=0.1 have larger magnitude still, and many of the dots corresponding to linear regression without any regularization (which would be alpha=0 ) are so large they are outside of the chart.</p><p>Another way to understand the influence of regularization is to fix a value of alpha but vary the amount of training data available. For Figure 2, we subsampled the Boston Housing dataset and evaluated LinearRegression and Ridge(alpha=1) on subsets of increasing size (plots that show model performance as a function of dataset size are called learning curves):</p><pre>mglearn.plots.plot_ridge_n_samples()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TbHff9JCeCBeS4gRKTRJ4w.png" /><figcaption>figure 2. Learning curves for ridge regression and linear regression on the Boston<br>Housing dataset</figcaption></figure><p>As one would expect, the training score is higher than the test score for all dataset sizes, for both ridge and linear regression. Because ridge is regularized, the training score of ridge is lower than the training score for linear regression across the board. However, the test score for ridge is better, particularly for small subsets of the data. For less than 400 data points, linear regression is not able to learn anything. As more and more data becomes available to the model, both models improve, and linear regression catches up with ridge in the end. The lesson here is that with enough training data, regularization becomes less important, and given enough data, ridge and linear regression will have the same performance (the fact that this happens here when using the full dataset is just by chance). Another interesting aspect of Figure 2 is the decrease in training performance for linear regression. If more data is added, it becomes harder for a model to overfit, or memorize the data.</p><h4>Objective = RSS + α * (sum of square of coefficients)</h4><p>Here, α (alpha) is the parameter which balances the amount of emphasis given to minimizing RSS vs minimizing sum of square of coefficients. α can take various values:</p><ol><li><strong>α = 0:</strong></li></ol><p>The objective becomes same as simple linear regression.</p><p>We’ll get the same coefficients as simple linear regression.</p><p><strong>2. α = ∞:</strong></p><p>The coefficients will be zero. Why? Because of infinite weightage on square of coefficients, anything less than zero will make the objective infinite.</p><p><strong>3. 0 &lt; α &lt; ∞:</strong></p><p>The magnitude of α will decide the weightage given to different parts of objective.</p><p>The coefficients will be somewhere between 0 and ones for simple linear regression.</p><p>I hope this gives some sense on how α would impact the magnitude of coefficients. One thing is for sure that any non-zero value would give values less than that of simple linear regression. By how much? We’ll find out soon. Leaving the mathematical details for later, lets see ridge regression in action on the same problem as above.</p><h4>Objective = RSS + α * (sum of square of coefficients)</h4><p>Here, α (alpha) is the parameter which balances the amount of emphasis given to minimizing RSS vs minimizing sum of square of coefficients. α can take various values:</p><ol><li><strong>α = 0:</strong></li></ol><ul><li>The objective becomes same as simple linear regression.</li><li>We’ll get the same coefficients as simple linear regression.</li></ul><ol><li><strong>α = ∞:</strong></li></ol><ul><li>The coefficients will be zero. Why? Because of infinite weightage on square of coefficients, anything less than zero will make the objective infinite.</li></ul><ol><li><strong>0 &lt; α &lt; ∞:</strong></li></ol><ul><li>The magnitude of α will decide the weightage given to different parts of objective.</li><li>The coefficients will be somewhere between 0 and ones for simple linear regression.</li></ul><p>I hope this gives some sense on how α would impact the magnitude of coefficients. One thing is for sure that any non-zero value would give values less than that of simple linear regression. By how much? We’ll find out soon. Leaving the mathematical details for later, lets see ridge regression in action on the same problem as above.</p><h4>Objective = RSS + α * (sum of square of coefficients)</h4><p>Here, α (alpha) is the parameter which balances the amount of emphasis given to minimizing RSS vs minimizing sum of square of coefficients. α can take various values:</p><ol><li><strong>α = 0:</strong></li></ol><ul><li>The objective becomes same as simple linear regression.</li><li>We’ll get the same coefficients as simple linear regression.</li></ul><ol><li><strong>α = ∞:</strong></li></ol><ul><li>The coefficients will be zero. Why? Because of infinite weightage on square of coefficients, anything less than zero will make the objective infinite.</li></ul><ol><li><strong>0 &lt; α &lt; ∞:</strong></li></ol><ul><li>The magnitude of α will decide the weightage given to different parts of objective.</li><li>The coefficients will be somewhere between 0 and ones for simple linear regression.</li></ul><p>I hope this gives some sense on how α would impact the magnitude of coefficients. One thing is for sure that any non-zero value would give values less than that of simple linear regression. By how much? We’ll find out soon. Leaving the mathematical details for later, lets see ridge regression in action on the same problem as above.</p><p>I hope this will be useful, don’t forget to applaud, if you don’t understand, please comment</p><p>reference</p><p>Andreas C.Muller and Sarah Guido. 2017. Introduction to machine learning with pyhton</p><p>NCSS Statictical software chapter 335, RIDGE REGRESSION</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8f6f3385e4c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/ridge-regression-with-multicollinearity-in-pyhton-c8f6f3385e4c">Ridge Regression with Multicollinearity in Pyhton</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[K-Neighbors Regression Analysis in Python]]></title>
            <link>https://medium.com/analytics-vidhya/k-neighbors-regression-analysis-in-python-61532d56d8e4?source=rss-2a3bbaeb7847------2</link>
            <guid isPermaLink="false">https://medium.com/p/61532d56d8e4</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[k-nearest-neighbours]]></category>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Imam Muhajir]]></dc:creator>
            <pubDate>Sat, 20 Apr 2019 08:34:55 GMT</pubDate>
            <atom:updated>2020-02-08T15:10:48.598Z</atom:updated>
            <content:encoded><![CDATA[<p>K nearest neighbors is a simple algorithm that stores all available cases and predict the numerical target based on a similarity measure (e.g., distance functions). KNN has been used in statistical estimation and pattern recognition already in the beginning of 1970’s as a non-parametric technique. <strong>Algorithm</strong> A simple implementation of KNN regression is to calculate the average of the numerical target of the K nearest neighbors. Another approach uses an inverse distance weighted average of the K nearest neighbors. KNN regression uses the same distance functions as KNN classification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/0*M_DPxG7ORoUisdPG.png" /></figure><p>The above three distance measures are only valid for continuous variables. In the case of categorical variables you must use the Hamming distance, which is a measure of the number of instances in which corresponding symbols are different in two strings of equal length.</p><p>The prediction using a single neighbor is just the target value of the nearest neighbor.</p><p>Let’s go to hands on, in this article I use the dataset from mglearn, the first step if you don’t have package in your note book, install in cmd/anaconda prompt..</p><pre>pip install mglearn</pre><p>After that, you can plot k-neighbors regression with n_neighbors = 1.</p><pre>import mglearn <br>import matplotlib.pyplot as plt</pre><pre>mglearn.plots.plot_knn_regression(n_neighbors=1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZDCp9usTtL_d2SfIguPeiQ.png" /><figcaption>figure 1. predictions make by one-nearst-neighbor regression on the wave dataset</figcaption></figure><p>Again, this k-neighbors regression just use 1 n_neighbors, you can use more than the single closest neighbor for regression, and the prediction is the average or mean of relevant neighbors. Let us see…</p><pre>mglearn.plots.plot_knn_regression(n_neighbors=3)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TiuvdKWf7Pgy_vVFImtpPA.png" /><figcaption>figure 2 . predictions make by three- nearest-neighbors regression on the wave dataset</figcaption></figure><p>Now we can make predict on the test data use knn regresson with n_neightbors = 3</p><pre>from sklearn.neighbors import KNeighborsRegressor<br>X, y = mglearn.datasets.make_wave(n_samples=40)</pre><pre># split the wave dataset into a training and a test set<br>X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)</pre><pre># instantiate the model and set the number of neighbors to consider to 3<br>reg = KNeighborsRegressor(n_neighbors=3)</pre><pre># fit the model using the training data and training targets<br>reg.fit(X_train, y_train)</pre><p>If you have done the above, you can use your model on test data</p><pre>print(reg.score(reg.score(X_test, y_test)))</pre><p>out : 0.83</p><p><strong>ANALYZING KNEIGHBORS REGRESSOR</strong></p><p>We can analyse how accuracy gets affected by n_neighbors: We can use different value 3 n_neighbors, and explain where good value n_neighbors for model.</p><pre>fig, axes = plt.subplots(1, 3, figsize=(15, 4))<br># create 1,000 data points, evenly spaced between -3 and 3<br>line = np.linspace(-3, 3, 1000).reshape(-1, 1)<br>for n_neighbors, ax in zip([1, 3, 9], axes):<br>    # make predictions using 1, 3, or 9 neighbors<br>    reg = KNeighborsRegressor(n_neighbors=n_neighbors)<br>    reg.fit(X_train, y_train)<br>    ax.plot(line, reg.predict(line))<br>    ax.plot(X_train, y_train, &#39;^&#39;, c=mglearn.cm2(0),   <br>             markersize=8)<br>    ax.plot(X_test, y_test, &#39;v&#39;, c=mglearn.cm2(1), markersize=8)<br>    ax.set_title(&quot;{} neighbor(s)\n train score: {:.2f} test  <br>              score: {:.2f}&quot;.format(n_neighbors,    <br>              reg.score(X_train, y_train),reg.score(X_test, <br>              y_test)))<br>    ax.set_xlabel(&quot;Feature&quot;)<br>    ax.set_ylabel(&quot;Target&quot;)<br>axes[0].legend([&quot;Model predictions&quot;, &quot;Training data/target&quot;,&quot;Test   <br>    data/target&quot;], loc=&quot;best&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-KaKtDqGeHSdqV4i7WyGyA.png" /></figure><p>As we can see from the plot, using only a single neighbor, each point in the training set has an obvious influence on the predictions, and the predicted values go through all of the data points. This leads to a very unsteady prediction. Considering more neighbors leads to smoother predictions, but these do not fit the training data as well.</p><p>ref : Andreas C.Muller and Sarah Guido. 2017. Introduction to machine learning with pyhton</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61532d56d8e4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/k-neighbors-regression-analysis-in-python-61532d56d8e4">K-Neighbors Regression Analysis in Python</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>