<?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 Anveshrithaa S on Medium]]></title>
        <description><![CDATA[Stories by Anveshrithaa S on Medium]]></description>
        <link>https://medium.com/@anveshrithaas?source=rss-96b0fc955cbc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*EmvkkQ1IBbamnVDR.jpg</url>
            <title>Stories by Anveshrithaa S on Medium</title>
            <link>https://medium.com/@anveshrithaas?source=rss-96b0fc955cbc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 11:31:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anveshrithaas/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[End-to-end Machine learning pipeline on Databricks — Part 5]]></title>
            <link>https://medium.com/analytics-vidhya/end-to-end-machine-learning-pipeline-on-databricks-part-5-c10273e2cd88?source=rss-96b0fc955cbc------2</link>
            <guid isPermaLink="false">https://medium.com/p/c10273e2cd88</guid>
            <category><![CDATA[machine-learning-pipeline]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Anveshrithaa S]]></dc:creator>
            <pubDate>Sun, 12 Jul 2020 05:31:23 GMT</pubDate>
            <atom:updated>2020-07-22T13:52:31.606Z</atom:updated>
            <content:encoded><![CDATA[<h3>End-to-end Machine learning pipeline on Databricks — Part 5</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/0*LbN4hy3OppJz2tYd.PNG" /></figure><p>In the <a href="https://medium.com/@anveshrithaas/machine-learning-in-pyspark-part-4-5813e831922f">previous blog</a> we started with machine learning in PySpark by implementing a linear regression model for housing price prediction using Spark’s machine learning library.</p><p>In this blog we will create an end-to-end machine learning pipeline. Unlike the example in the previous blog, we’ll be working on a cloud-based unified data analytics platform built around Apache Spark- Databricks, to get the taste of working with Apache Spark for large-scale data processing, analytics and machine learning just like how data scientists and engineers apply advanced analytics techniques and machine learning models at scale for solving real-world problems. Databricks allows us to easily build, scale and deploy machine learning models in very less time. It delivers fully managed Spark clusters, interactive workspace for data exploration and visualization, production pipeline scheduler and a platform to facilitate Spark-based applications.</p><p>To understand more about how this works, let’s get hands-on by creating an end-to-end machine learning pipeline in PySpark on the Databricks platform. This starts with loading the data in the DataFrames and performing exploratory data analysis and then moving on to the unified pipeline creation which is a combination of <strong>transformers</strong> and<strong> estimators</strong> that are collectively referred to as the pipeline stages and then finally evaluation of the machine learning model. A transformer is an algorithm that transforms one dataframe to another. It includes feature transformers and learned models. An estimator is an algorithm that fits or trains on a data by implementing the fit() method on a dataframe to produce a model which is a transformer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*ZxJqKzA4v_qB8XP3riugKQ.png" /><figcaption>Source: AIEngineering</figcaption></figure><p>In this blog, we’ll build a machine learning pipeline in PySpark for a bank marketing use case. The dataset has information about a phone call based marketing campaign that a bank carried out for persuading customers to subscribe a term deposit and our task is to analyse it and identify the patterns that will help us find conclusions in order to develop future strategies to get customers subscribed to a term deposit. Basically, this is going to be a binary classification problem where the goal is to predict if a client will subscribe or not (yes or no). The data set we will be using for this can be downloaded <a href="https://www.kaggle.com/janiobachmann/bank-marketing-dataset">here</a>.</p><h4>Setting up databricks environment</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/0*hZDHkwfxzDXEh40_" /></figure><p>Before we start building the pipeline, we have to first setup our Databricks environment. Databricks provides a free community edition that includes features to work with decent sized datasets which will be more than enough for what we are going to do in this blog.</p><ul><li>First go to the <a href="https://databricks.com/try-databricks">official databricks website</a>. Once you get there, fill in your details to sign up and get started.</li><li>You’ll be asked to choose a platform between the databricks platform free trial and the community edition. While the databricks platform free trial offered on either AWS or Azure cloud platform provides advanced features such as collaborative environment, unlimited clusters, job scheduler, native integration with ML frameworks etc that are meant for businesses, the community edition provides access to a free micro-cluster (6GB, without worker nodes) as well as a cluster manager and a notebook environment, ideal to get started with Spark. For this tutorial, the community edition should suffice.</li><li>Once the email verification is done, we are good to go. In the welcome page you’ll see options to create new notebook, table, cluster etc. Let’s start by creating a cluster.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d-dyBnOjm7wC6LDhJ40yKw.png" /></figure><ul><li>To create a new cluster, give a name for your cluster, select a databricks runtime version and click on create cluster.</li></ul><p><strong><em>Note:</em></strong><em> In the community edition, the cluster will automatically terminate after an idle period of two hours.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fRlP7pDBMOP5KNuiKJE2-g.png" /></figure><p>It takes some time for the cluster to be created. When the cluster state changes from ‘pending’ to ‘running’ it means the cluster is created and is currently running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jKbPDmlijSiRR6tXzXsVgg.png" /></figure><p>When you click on your cluster, you can see multiple tabs on the top. When you click on the Libraries tab, there’ll be an option ‘Install New’ which lets you install various packages and libraries that you’ll be needing. The Notebooks tab displays the notebooks running with the cluster. You can also see the log information in the Event log and Driver log tabs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6gfwKu1Ogwv5L62aPIjLVw.png" /></figure><p>Once the cluster is created, let’s go to the Data section that displays the data already available for use. If we want to use a new data then click on ‘Add Data’ to load the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*9T01Du24CeH19XOIOkNSNw.png" /></figure><p>Once you click ‘Add Data’ you’ll be provided with various options for adding the data. You may add the data by simply uploading it from your local filesystem or by connecting to Amazon S3 bucket or upload the data to the Databricks File System (DBFS) or add data from other sources like Amazon Kinesis, Cassandra, Kafka, JDBC etc. By clicking create table in Notebook, it will open a new notebook with the data loaded into it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*pf9x8LGetwVyluufKNDh6A.png" /></figure><p>One way of getting the data is to connect with AWS environment and pull the data from the S3 bucket by giving the necessary permissions to get the data to the Databricks Spark environment. Amazon S3 is nothing but a storage service offered by AWS with high scalability, security and performance to store any amount of data for a wide range of use cases. It is used by several companies including various leading enterprises across all industries to store their massive amount of data and retrieve it at anytime from anywhere on the web.</p><h4>Getting started with AWS</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*lo2Q78gYSGnqLk_d" /></figure><p>For the machine learning pipeline that we are going to create, let’s try pulling the data from the Amazon S3 bucket just to get an idea of how data scientists and data engineers handle large amount of data using cloud storage for real-world use cases. To do this, we have to create an S3 bucket, upload the data into it, connect the Databricks environment with AWS and pull the data from the S3 bucket into our Spark environment.</p><p><strong>Setting up AWS account</strong></p><p>For this, firstly we need to have an AWS account. If you don’t have one, you can register for an AWS free tier account (that includes 12 months of free tier access).</p><ul><li>Visit the <a href="https://aws.amazon.com/">AWS website</a></li><li>Click on ‘Create an AWS Account’ and enter your details and click ‘Continue’.</li><li>Next, select the account type — professional or personal and start filling your contact information and proceed to the next step by clicking ‘Create account and continue’.</li><li>Once this step is done, it will ask you for the payment card details. Even a free tier account will need you to enter these details. But you will not be charged unless your usage exceeds the AWS free tier limits.</li><li>Once this is done, you’ll be asked to confirm your identity through phone number verification. Enter your phone number and click on ‘Send SMS’ to receive the verification code to that mobile number.</li><li>Enter the verification code to successfully verify your identity.</li><li>Finally, from the three plans listed, select the basic plan for a free tier.</li></ul><p>That’s it. Your AWS free tier account has been successfully created and now you are ready to login to the AWS console using your credentials and start using the AWS services. The AWS free tier account provides access up to 5 GB of storage in Amazon S3. The data that we’ll be using for our machine learning pipeline is a small dataset for the purpose of simplicity. But in real-world scenario, the data handled by data scientists and analysts may even go up to terabytes.</p><p><strong>Creating S3 bucket and storing the data</strong></p><p>Now that we have setup our AWS account, let’s begin by uploading the already downloaded data set in the Amazon S3 bucket. Before that, we have to create a S3 bucket. To do this,</p><ul><li>login to your AWS account and in your AWS Management Console, search for S3 under AWS services and click on it.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oa-lMjkY70VZBoa9ZR-IWg.png" /></figure><ul><li>Once you come into the S3 window, click on create bucket to create a new bucket into which we will store our data.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SW5ODKT2FLL7Ssr-tW8L2A.png" /></figure><ul><li>Give the bucket a unique name and select the region that is nearest to your Databricks cluster region in order to minimize latency. Once it is done, click on create. You need not worry about the configure options or set permissions and directly go on to create the cluster after giving it a name and selecting the region.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NN_i38gMvZV1LRtNtSsfpg.png" /></figure><ul><li>Now, you’ll see the newly created S3 bucket. Click on the bucket.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_P9W_RldJIYdeQGgVOgWbg.png" /></figure><ul><li>Inside this, click on the Upload button to upload our dataset in this S3 bucket.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fhk4HrV3BBQ6GOesfp51pA.png" /></figure><ul><li>Click on add files to add the dataset. Choose the dataset that you have to upload from your local filesystem.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3IvizH84x9P3wmPNcWo2ig.png" /></figure><ul><li>Now the selected files that you want to upload will appear in the list. Verify and upload to store it in the S3 bucket. It will take some time to get uploaded.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q-vmcv0-I1pdS2D3jHjR2g.png" /></figure><p>Once it is uploaded successfully, you’ll see it appear on the screen. Now we have stored the data in the S3 bucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AaBaz2GVCeIxH4RR0tUKMQ.png" /></figure><p>Now, how do we access this data outside S3? How do we get it into our Databricks Spark environment? One way to do is by setting the S3 bucket permission visible to all so that anyone can access it. A more secure way is to get an access key ID and a secret access key and use it in our Spark environment to pull the data from the bucket. That is what we are going to do here.</p><ul><li>To get the access ID and key, go to services and search for IAM and click on it.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5bYfqLRhyPDXBF0Zndh__g.png" /></figure><ul><li>Once you get there, click on the ‘Users’ option under Access Management from the menu in the left side of the window. Then click on the ‘Add user’ option.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*50_1aOMpSPc0D_hQYD_J9g.png" /></figure><ul><li>Set the user details by giving a user name. Then select the access type as Programmatic access in order to get the access key ID and the secret key which can be used in our Spark program to access the data from the S3 bucket. Then click on ‘Next Permissions’.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nak-s13mKp-SDx1nunMjpw.png" /></figure><ul><li>Here, select the ‘Attach existing policies directly’ and search for S3. From the list that is displayed, select the ‘AmazonS3FullAccess’ option to give both read and write permissions. For read only permission, select the ‘AmazonS3ReadOnlyAccess’ option. After selecting, click on ‘Next Tags’.</li><li>Skip the optional ‘Add Tags’ step and continue.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Otnx8r7XnvqQVnC8KDQkIw.png" /></figure><ul><li>Review once and click Create user to get the Access ID and secret Key.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gz0_s90c89kM3c3_T5qKKg.png" /></figure><p>Here, you can find your access key ID and secret access Key for the S3 bucket and we can use this in our PySpark program to access the data. Note that the secret access key should not be shared, as anyone who has the secret key will have complete access to your S3 bucket and can make changes to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5JfTngOXcOvTpf_cbpe9ZA.png" /></figure><p>While this just one way of getting the data for our pipeline, it is not necessary that you do it this way. If you are unable to setup the Amazon S3 bucket, you can very well upload the data directly to the Databricks environment which is a much simpler way.</p><h4><strong>Uploading data directly to databricks environment without AWS (alternate method)</strong></h4><ul><li>As we already saw, in the Data section when you click on ‘Add Data’ you’ll have the option to upload file. Select that and browse for files from your local file system to upload.</li><li>Once it is uploaded, click Create table with UI. Then select the cluster with which you want the data to be attached. I will be using the cluster that we have already created in the beginning.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*GvEmKP5KBb7LNgkx2xAEUg.png" /></figure><ul><li>Scroll down and under the ‘Specify table attributes’, give the table name, file type, column delimeter (comma in case of CSV file) and select ‘First row as header’, ‘infer schema’ and ‘Multi-line’ and click ‘Create Table’.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LCCKEDgn58QzF0E98DCjhw.png" /></figure><p>The schema of the table is displayed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GPjf0SP6CjlphpRpaWliXg.png" /></figure><h4>Creating a new notebook in databricks</h4><p>Now let’s create a new notebook (similar to Jupyter Notebbok) to start with our Spark program for building a machine learning pipeline.</p><ul><li>Go to the main window of Databricks and click on ‘New notebook’ option to create a new notebook.</li><li>Assign a name to the notebook, select the language (we’ll be using python) and select the cluster with which you want to attach the notebook. Once it is done, click on ‘Create’ to open a new notebook. Now we are good to go.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*NvV5Zf-L0b6_F-jZysyxbw.png" /></figure><h4>Writing our Spark program for ML pipeline</h4><p>Let’s get started with writing our Spark program. Firstly, let’s begin by importing the data from the S3 bucket using the access key ID and the secret access key. If you have directly uploaded the data in the Databricks environment rather than using Amazon S3, then skip the following code snippet and directly get started by just specifying the file location (See the next code snippet).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/287f90be7987b06b638e2180f706ccdc/href">https://medium.com/media/287f90be7987b06b638e2180f706ccdc/href</a></iframe><p>When you run the cell, you’ll get the following output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*9404s1UzHoECNhtl2fqHRg.png" /></figure><p><strong><em>Note: </em></strong><em>While using Databricks notebook, you need not explicitly create SparkContext or SparkSession. Instead use the already defined variables ‘sc’ for SparkContext, ‘spark’ for SparkSession and ‘sqlContext’ for SQLContext.</em></p><p>Next, Specify the dataset location and the file type and configure the CSV options such as setting the first row of the dataset as the header, the column delimiter, inferring the schema etc. and finally display the dataset. In case, you have directly uploaded the dataset in the databricks environment then start by specifying the file location as “/FileStore/tables/BankMarketing.csv”</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14e56be13aa1341d2c770a93348da764/href">https://medium.com/media/14e56be13aa1341d2c770a93348da764/href</a></iframe><p>The dataframe is created and displayed as shown.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N2WxZ4CvLBlype0ZFXFBNA.png" /></figure><p>Next, print the schema of the dataframe using <em>printSchema()</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e33036f5651e1b00d8f50e9be4a65b78/href">https://medium.com/media/e33036f5651e1b00d8f50e9be4a65b78/href</a></iframe><p>Here we can see that the dataset has 17 attributes and the data type of each attribute is displayed. Here ‘<em>deposit</em>’ is the target variable with two class labels (Yes and No) and the remaining attributes are the independent variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*RP3zqTHsrb0jFzI0Kt-7GQ.png" /><figcaption>Schema of the DataFrame (output)</figcaption></figure><p>Then, display the count of each class label (Yes and No) in the dataset using <em>groupBy() </em>and <em>count() </em>to check if the dataset is balanced.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eec0d0d256aa311bd8c4b6fa5021588c/href">https://medium.com/media/eec0d0d256aa311bd8c4b6fa5021588c/href</a></iframe><p>This gives the count of the examples under each class label in the dataset. And we can see that this dataset is well balanced with almost equal number of instances in each class label — 5873 examples with class label ‘No’ and 5289 examples with class label ‘Yes’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/194/1*aXl946nCOvOzt_w85JK_Yg.png" /></figure><p>As we already saw in the schema, this data has variables that are of both String as well as numeric type (integer). Let’s get all the columns that are of type integer using <em>dtypes().</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ff912214fd6c80e153c6aeeba6ad33c/href">https://medium.com/media/4ff912214fd6c80e153c6aeeba6ad33c/href</a></iframe><p>The following variables have numeric values in the dataframe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*cJLZJW9l2bqwsueMMPxl0g.png" /><figcaption>Columns with numeric type (output)</figcaption></figure><p><strong><em>Note:</em></strong><em> We can also convert the Spark dataframe to Pandas dataframe using toPandas(). We can use Pandas dataframe to have a better tabular view of the data.</em></p><p><em>Example:</em></p><pre>df.select(numeric_features).toPandas().head(5)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*ZjkPXaNMfsvFagEdhzSmOQ.png" /><figcaption>Tabular view of Pandas DataFrame</figcaption></figure><p>Apart from the numeric type columns the remaining columns are categorical variables. In order to make them suitable for the model to learn from, we have to convert the categorical variables to a binary representation by one-hot encoding. We will first use <em>StringIndexer</em> to convert the categorical column to indices and then convert these indexed categories into one-hot encoded variables. The target variable (label) is also encoded into a single column vector using the <em>StringIndexer</em>. We append the string indexer and one-hot encoder of the categorical variables and the string indexer of the label to the pipeline stages.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/383ae7fbfae50dac0f26d6121f37868a/href">https://medium.com/media/383ae7fbfae50dac0f26d6121f37868a/href</a></iframe><p>Next, we will use <em>VectorAssembler </em>that combines a list of columns into a single vector column to convert all the independent variables into a single feature vector. This will separate the independent variables (features) from the target variable (label). A <em>VectorAssembler</em> accepts numeric, boolean and vector types for the input columns. Here, all the independent variables (numeric columns + categorical columns) are converted into a single vector called features. Then this vector assembler is appended as a pipeline stage.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be05cefba961a1671c4b9c2312940a9a/href">https://medium.com/media/be05cefba961a1671c4b9c2312940a9a/href</a></iframe><p>Once we have added all the stages of the pipeline, it’s time to create the pipeline. Here, we create the pipeline with these stages and then fit the pipeline to the dataframe and transform it. We’ll select <em>‘label’</em> (target variable) and <em>‘features’</em> (vector of all the independent variables) as the columns for the dataframe.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d97ad66f5039a597c669bb7be5a4682/href">https://medium.com/media/7d97ad66f5039a597c669bb7be5a4682/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*z0e9SFPZKMNZUzO21MrwKA.png" /><figcaption>Schema of the DataFrame (output)</figcaption></figure><p>Now, the data is ready for the model. Let’s split it into training and test set for training the model and then testing the model on unseen data. Here, we are dividing the data in 80:20 train/test split ratio.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2007d1a4dd4b53531918a876094823d9/href">https://medium.com/media/2007d1a4dd4b53531918a876094823d9/href</a></iframe><p>Now it’s time to create a binary classifier and we’ll choose logistic regression model for classification. First, we’ll initialize the model and then fit it to the training data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5fbfb6b9dc9871fd8826f31af05641f2/href">https://medium.com/media/5fbfb6b9dc9871fd8826f31af05641f2/href</a></iframe><p>Once the model is created and fitted on the training set, let us plot the ROC curve for this binary classifier by plotting the true positive rate against the false positive rate. We are doing this by converting the it to Pandas and then plotting.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c37de904e75c6cb00cf57f1fab422179/href">https://medium.com/media/c37de904e75c6cb00cf57f1fab422179/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*TKuWZ7rF0eAKH3CtLvTMXw.png" /></figure><p>Now we’ll evaluate the performance of the model on the training data using two performance metrics namely accuracy and area under ROC curve.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53ff8546c71c1beaa72cc70ae8d3479d/href">https://medium.com/media/53ff8546c71c1beaa72cc70ae8d3479d/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*h13NfsD-yADhXrP_pQKmmA.png" /></figure><p>The training accuracy of the model turns out to be 0.8257 while the area under ROC curve turns out to be 0.9033. But evaluating the model performance on the training data is not a good idea. So, we’ll use the test set to make predictions and evaluate the model based based on that.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c97062a64b98d798526bed64625b9e63/href">https://medium.com/media/c97062a64b98d798526bed64625b9e63/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/209/1*mawmF3jYh91y_g-HPYsLUg.png" /><figcaption>Model’s predictions (Output)</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/768a5d3ecf63c13191d2ba212bf69bea/href">https://medium.com/media/768a5d3ecf63c13191d2ba212bf69bea/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*o3Kr9DEL9zSiQPc3L9i-sg.png" /></figure><p>The accuracy of the model when tested on previously unseen data turns out to be around 82.4% and the area under ROC curve is 0.9047. We see that there is not much difference between the performance of the model on training and testing data.</p><p><strong>Hyper-parameter tuning</strong></p><p>While building the logistic regression model, we assigned the default hyperparameters for the model. Tuning these to find the optimal hyperparameters can greatly improve the model performance. To do that, we can perform grid search using <em>ParamGridBuilder</em> and <em>CrossValidator </em>which is equivalent to Sklearn’s <em>GridSearchCV</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c035d773343ec5288440e3d3a411425/href">https://medium.com/media/7c035d773343ec5288440e3d3a411425/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*E284WfvBGB0lXLcWxSf9Yg.png" /></figure><p>This is the area under ROC curve of the best possible classification model created from various combinations of the specified hyperparameter values.</p><p>There is scope for improvement in the performance of the model. You can try improving the model by carrying out more data preprocessing steps such as missing value imputation, feature selection etc. and adding them as stages in the pipeline. You can access this notebook<a href="https://github.com/Anveshrithaa/PySpark-ML-Pipeline"> here</a>.</p><p>In this blog we have learnt how to use a cloud based unified analytics platform for our Spark application, how to store the data in Amazon S3 bucket and access it from the Spark environment and finally how to build an end-to-end machine learning pipeline in Spark. Rather than just reading, getting hands-on and playing around with it will give you a better understanding. Make sure to try building your own pipeline for any machine learning use case of your choice. Perform exploratory analysis on the data, analyze it and do the necessary preprocessing of data and finally build and train the model. Last but not the least, strive to improve the performance of the model. Happy coding!</p><p>Check out the other blogs in this series</p><p><a href="https://medium.com/@anveshrithaas/getting-started-with-apache-spark-part-1-91b379204ae0"><strong><em>Part 1— Getting started with Apache Spark</em></strong></a></p><p><a href="https://medium.com/@anveshrithaas/introduction-to-pyspark-part-2-6d6113e31592"><strong><em>Part 2 — Introduction to PySpark</em></strong></a></p><p><a href="https://medium.com/@anveshrithaas/understanding-spark-rdds-part-3-3b1b9331652a"><strong><em>Part 3 — Understanding Spark RDDs</em></strong></a></p><p><a href="https://medium.com/@anveshrithaas/machine-learning-in-pyspark-part-4-5813e831922f"><strong><em>Part 4 — Machine Learning with PySpark</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c10273e2cd88" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/end-to-end-machine-learning-pipeline-on-databricks-part-5-c10273e2cd88">End-to-end Machine learning pipeline on Databricks — Part 5</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[Machine Learning in PySpark — Part 4]]></title>
            <link>https://medium.com/analytics-vidhya/machine-learning-in-pyspark-part-4-5813e831922f?source=rss-96b0fc955cbc------2</link>
            <guid isPermaLink="false">https://medium.com/p/5813e831922f</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[spark-mllib]]></category>
            <category><![CDATA[apache-spark]]></category>
            <dc:creator><![CDATA[Anveshrithaa S]]></dc:creator>
            <pubDate>Sun, 12 Jul 2020 05:26:56 GMT</pubDate>
            <atom:updated>2020-07-22T13:52:51.868Z</atom:updated>
            <content:encoded><![CDATA[<h3>Machine Learning in PySpark — Part 4</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*ml6bP0O8M8u2Frk0_YmYCQ.jpeg" /></figure><p>While we step into the era of big data where we deal with massive amounts of data every day, the world is simultaneously pacing towards Machine Learning and AI. In the recent years, with the increase in the amount of data being produced each day, machine learning has seen a tremendous upsurge in its importance and prevalence in almost every domain. Especially in the present-day, most of the business enterprises are in need to process massive amount of data for a better understanding by turning data into business through analysis to find meaningful insights to deal with risks and opportunities in order to have a competitive advantage for the business. Machine learning plays a pivotal role in this process.</p><p>Industries use Apache Spark deployed on large clusters for large-scale data analysis by creating unified machine learning pipelines. This is possible with Spark’s MLlib library that facilitates machine learning on Spark. PySpark MLlib is Spark’s machine learning library and acts as a wrapper over the PySpark core that provides a set of unified API for machine learning to perform data analysis using distributed implementation of various machine leaning algorithms like classification, regression, clustering etc.</p><p>In this blog, we will not cover theoretical concepts. Instead, we’ll have a hands-on session where you’ll learn by coding along. I assume that you have enough knowledge on machine learning as a pre-requisite in order to get the best out this. Let’s get started with machine learning in Spark using its MLlib library by creating a simple linear regression model for predicting prices of houses using a housing price dataset. While the dataset used is small enough for Pandas to be very well used instead of Spark, for the purpose of a simple demonstration of how machine learning is done in PySpark we go with this dataset. The dataset can be downloaded <a href="https://github.com/Anveshrithaa/housing-price-prediction-pyspark/blob/master/housing.csv">here</a>.</p><p>We are good to go. Let’s get started!</p><h4><strong>Creating SparkContext</strong></h4><pre>from pyspark.sql import SparkSession</pre><pre>spark = SparkSession.builder.master(“local”)\<br>.appName(“Housing Price Prediction”)\<br>.config(“spark.executor.memory”, “1gb”)\<br>.getOrCreate()</pre><pre>sc = spark.sparkContext</pre><h4>Data exploration and preprocessing</h4><p>The first and one of the most important steps is data pre-processing where the data is converted into a clean and usable data so that it is feasible for analysis and training the model. The data that is used, significantly determines the performance of the machine learning model. Thus, data exploration, cleaning, pre-processing and feature engineering help in improving the model performance.</p><p>The dataset contains 20,640 instances on 9 attributes</p><ul><li><strong><em>Longitude</em></strong></li><li><strong><em>Latitude</em></strong></li><li><strong><em>Housing median age</em></strong> — Median age of a house within a block. A lower number means a newer building</li><li><strong><em>Total rooms</em></strong> — Total number of rooms within a block</li><li><strong><em>Total bedrooms</em></strong> — Total number of bedrooms within a block</li><li><strong><em>Population </em></strong>— Total number of people living within a block</li><li><strong><em>Households </em></strong>— Total number of households in a block</li><li><strong><em>Median income</em></strong> — Median income for households within a block</li><li><strong><em>Median house value</em></strong> (dependent variable) — Median house value for households within a block</li><li><strong><em>Ocean proximity</em></strong> — Location of the house w.r.t ocean</li></ul><p><strong>Loading the data</strong></p><p>To get started, let’s load the data into the Spark environment. We can directly create a PySpark dataframe (just like Pandas dataframe) by reading the data from the CSV using the <em>spark.read.csv() </em>method. Set <em>header = True</em> to have the first row of the CSV as the header.</p><p><strong><em>Note:</em></strong><em> DataFrame supports variety of data types on which machine learning can be applied.</em></p><pre>myDF = spark.read.csv(‘C:/Users/a/pyspark/housing.csv’, header=True)</pre><p>As the first step, let us explore the data that we have loaded. We will spend some time in inspecting it in order to understand the dataset and the characteristics of the data, so that it’ll be helpful in determining the pre-processing steps to be carried out.</p><p>Now that the data is loaded, we can use the <em>printSchema()</em> method to understand the schema of the dataframe. You can also get the header using the <em>df.columns</em> which returns the column names.</p><pre>myDF.printSchema()</pre><pre>myDF.columns</pre><p><strong><em>Output:</em></strong></p><pre>root<br> |-- longitude: string (nullable = true)<br> |-- latitude: string (nullable = true)<br> |-- housing_median_age: string (nullable = true)<br> |-- total_rooms: string (nullable = true)<br> |-- total_bedrooms: string (nullable = true)<br> |-- population: string (nullable = true)<br> |-- households: string (nullable = true)<br> |-- median_income: string (nullable = true)<br> |-- median_house_value: string (nullable = true)</pre><pre>[‘longitude’, ‘latitude’, ‘housing_median_age’, ‘total_rooms’, ‘total_bedrooms’, ‘population’, ‘households’, ‘median_income’, ‘median_house_value’]</pre><p>Here, you can see that all the columns are of the type string. But for a more efficient analysis, we’ll need to convert the columns into float data type. To do that, we will create a function that converts the data type of each column of the dataframe to float. The <em>withColumn()</em> function is used to manipulate (rename, change the value, convert the datatype) an existing column in a dataframe or to create a new column.</p><pre>from pyspark.sql.types import *</pre><pre>def convertColDatatype(df, colNames, newDatatype):<br>      for colName in colNames:<br>           df= df.withColumn(colName, df[colName].cast(newDatatype))<br>      return df</pre><pre>columns= myDF.columns<br>myDF= convertColDatatype(myDF, columns, FloatType())<br>myDF.printSchema()</pre><p><strong><em>Ouptut:</em></strong></p><pre>root<br> | — longitude: float (nullable = true)<br> | — latitude: float (nullable = true)<br> | — housing_median_age: float (nullable = true)<br> | — total_rooms: float (nullable = true)<br> | — total_bedrooms: float (nullable = true)<br> | — population: float (nullable = true)<br> | — households: float (nullable = true)<br> | — median_income: float (nullable = true)<br> | — median_house_value: float (nullable = true)</pre><p>Now all the columns in the dataframe are converted to float data type.</p><p>Further, to display the dataframe in a table format use the <em>show() </em>method (displays the top 20 rows by default) and to select particular columns use the <em>select()</em> method. You can also try using other methods like <em>take(), top(), head()</em> and <em>first()</em> to get the rows of the dataframe.</p><pre>myDF.show()</pre><p><strong><em>Output:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*Y5DWk5GPSrCiuMZb0fqA6g.png" /></figure><pre>#Select and display first 5 rows of data from the selected columns<br>myDF.select(‘total_bedrooms’, ‘median_income’).show(5)</pre><p><strong><em>Output:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/1*Xxn0X7FsXi_0gPcXASq_MA.png" /></figure><p>Use the <em>count()</em> method on the dataframe to get the total number of rows in the dataframe. You can always make use of <em>groupBy(), sort(), count(), distinct()</em> etc. to explore more. Let’s say, for example, you want to know the ten highest distinct median house value for the blocks.</p><pre>print(myDF.count())</pre><pre>myDF.sort(“median_house_value”,ascending=False)\<br>.select(“median_house_value”).distinct().show(10)</pre><p><strong><em>Output:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*XwMk9kekaPXt1laso4wq_A.png" /></figure><p>Now let’s get the summary of the data using the <em>describe()</em> method. This gives the count, mean, standard deviation, minimum and the maximum value of each column. This helps us to gain insights into details like the range and the distribution of the data which will be useful for deciding how to preprocess the data.</p><pre>myDF.describe().show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*4exJsy9rizsUz93fzvrkWQ.png" /></figure><p>From the min and max values, we can see that the data in few columns is spread across a wide range of values. To fix this, we have to normalize the data which we’ll be doing later.</p><p><strong>Handling missing values and null values</strong></p><p>To check if there are any null values in the data, let’s count the number of null values in each column using <em>isnull()</em> and display it.</p><pre>from pyspark.sql.functions import *</pre><pre>myDF.select([count(when(isnull(c), c))\<br>.alias(c) for c in myDF.columns]).show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*njTzJFRgXLn_tnpT_PANVg.png" /></figure><p>Here, we can see that there are more than 200 null values in the ‘total_bedrooms’ column. To fix this, we will replace all the null values in that column with the mean of the available values in the column. The mean of the column ‘total_bedrooms’ turns out to be around 537 from the output of the describe() function.</p><pre>#replace null values in the column with the mean value</pre><pre>myDF= myDF.fillna({‘total_bedrooms’: 537})</pre><pre>myDF.select([count(when(isnull(c), c))\<br>.alias(c) for c in myDF.columns]).show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*xk3XbSXQMi5WFhIxeZJ-IQ.png" /></figure><p>Now, you can see that we don’t have any null values in our dataframe.</p><p>Next, you would have noticed that the target variable ‘<em>median_house_value</em>’ contains values that are quite big. To fix this, let’s express it in units of 100,000.</p><p><strong><em>Note:</em></strong> <em>While this is absolutely not necessary to do, this is just to show the different ways we can pre-process the data. It would still be fine even if you skip this step.</em></p><pre>from pyspark.sql.functions import *</pre><pre>#Divide all the values in the ‘median_house_value’ column by 100,000</pre><pre>myDF = myDF.withColumn(“median_house_value”, col(“median_house_value”)/100000)</pre><pre>#myDF.take(2)</pre><p>Further, you can also try doing feature engineering by creating new features from the available data and add them to the existing data. Here, we have variables like<em> total_rooms</em>, <em>total_bedroom</em>s and <em>population</em> which denote the cumulative values for an entire block. From these features we can derive additional attributes like <em>population_per_household</em>, <em>bedrooms_per_household</em> or <em>rooms _per_household</em> for each block by dividing the values of the available features (population, total bedrooms and total rooms respectively) by the total number of households in that block. This will give the average number of bedrooms/rooms/people in each household of that block. For this, use the <em>select(), col() </em>and <em>withColumn()</em> methods to work with the columns.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3bf21ffee88173e5b42a3c898852471/href">https://medium.com/media/d3bf21ffee88173e5b42a3c898852471/href</a></iframe><p><strong><em>Output:</em></strong></p><blockquote>[‘longitude’, ‘latitude’, ‘housing_median_age’, ‘total_rooms’, ‘total_bedrooms’, ‘population’, ‘households’, ‘median_income’, ‘median_house_value’, ‘population_per_household’, ‘rooms_per_household’, ‘bedrooms_per_household’]</blockquote><p>You can see that the new columns are added to the dataframe. While we have added a few new features, we can also remove some of the features that might not be considered necessary or useful for analysis. We’ll drop attributes like <em>latitude, longitude, total_rooms and total_bedrooms</em>. You may use the <em>df.drop() </em>method to discard the columns that you don’t need. Here, we will use the <em>select()</em> method to select and rearrange the required columns in the dataframe.</p><pre>myDF= myDF.select(‘median_house_value’, ‘housing_median_age’, ‘median_income’, ‘population’, ‘households’, ‘population_per_household’, ‘rooms_per_household’)</pre><p>Now that we have re-ordered the columns in the dataframe, it’s time for us to separate the target variable (<em>median_house_value</em>) which is the first column in the dataframe from the independent variables (columns other than the target variable). To do this, we will convert the dataframe into an RDD containing the target variable and a DenseVector of all the independent variables using <em>map() </em>and <em>DenseVector()</em>. Once it is done, convert it back to a dataframe using <em>createDataFrame() </em>that takes the data as the first argument and the column names as the second argument. A DenseVector stores arrays of values.</p><pre>from pyspark.ml.linalg import DenseVector</pre><pre>#x[0] is the target variable (label) and x[1:] are the features</pre><pre>data = myDF.rdd.map(lambda x: (x[0], DenseVector(x[1:])))</pre><pre>#creating a dataframe with columns ‘label’ (target variable) and #‘features’(dense vector of independent variables)</pre><pre>myDF = spark.createDataFrame(data, [“label”, “features”])<br>myDF.printSchema()</pre><p><strong><em>Output:</em></strong></p><pre>root<br> |-- label: double (nullable = true)<br> |-- features: vector (nullable = true)</pre><p>Here, the<em> features</em> column contains the dense vector of all the independent variables (arrays of values of independent variables) and the <em>label</em> column contains the target variable.</p><p>Once this is done, before moving on to building the model, we have one more pre-processing step to be carried out. As we already saw that the range of the values in few columns is big, we have to normalize the data using <em>StandardScalar</em> that transforms the data such that the mean is 0 and the standard deviation is 1. Here the input columns are the features to be scaled and the output column will be the resulting scaled features which will be included as the third column in the dataframe.</p><pre>from pyspark.ml.feature import StandardScaler</pre><pre>ss= StandardScaler(inputCol=”features”, outputCol=”scaled_features”)</pre><pre>scaler = ss.fit(myDF)</pre><pre>myDF = scaler.transform(myDF)</pre><pre>myDF.printSchema()</pre><pre>myDF.take(1)</pre><p><strong><em>Output:</em></strong></p><pre>root<br> | — label: double (nullable = true)<br> | — features: vector (nullable = true)<br> | — scaled_features: vector (nullable = true)</pre><pre>[Row(label=4.526, features=DenseVector([41.0, 8.3252, 322.0, 126.0, 2.5556, 6.9841]), scaled_features=DenseVector([3.2577, 4.3821, 0.2843, 0.3296, 0.2461, 2.8228]))]</pre><p>Now the data preprocessing is done and we are finally ready to get started with building the machine learning model. By now you would have understood how exploratory data analysis helps us in gathering information about the data for further preprocessing. The simple exploratory analysis of the data gave us a brief idea of how the data is structured, facilitating us to decide on the preprocessing steps to make the data cleaner and suitable for the model.</p><h4>Building the machine learning model</h4><p>Now it’s time for us to get started with building the machine learning model. Since this is a regression problem, we will go with a simple linear regression model. Before we start creating the model let’s split the pre-processed data into the training and test sets using <em>randomSplit()</em>. You can either follow 80:20 or 75:25 train/test split ratio.</p><pre>train, test = myDF.randomSplit([.8,.2],seed=1)</pre><p>To initialize the linear regression model let’s go with the default parameters.</p><pre>from pyspark.ml.regression import LinearRegression</pre><pre>linearReg= LinearRegression(featuresCol= “scaled_features”, labelCol=”label”)</pre><pre>#fit the model to the the training data<br>model=linearReg.fit(train)</pre><pre>#make predictions on the test set<br>predictions= model.transform(test)</pre><pre># show the predicted values and the actual values<br>predictions.select(“prediction” ,“label”).show(10)</pre><p><strong><em>Output:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*3YLDvVfQ_IXXVdW_VQO-4w.png" /></figure><h4>Evaluating the model</h4><p>We can get to know how efficient the model is by looking at some performance metrics. To evaluate the performance of the linear regression model we’ll use the <em>RMSE</em> (root mean squared error) which gives the absolute measure of the error between the actual and the predicted values and <em>R2</em> score (R squared) that gives information about the goodness of fit of the model.</p><pre>#R2 score on test set<br>r2_test= model.evaluate(test).r2<br>print(“R2 score on test set: “, r2_test)</pre><pre>from pyspark.ml.evaluation import RegressionEvaluator</pre><pre>#RMSE on test set<br>evaluator = RegressionEvaluator(predictionCol=”prediction”, labelCol=”label”,metricName=”rmse”)</pre><pre>rmse_test = evaluator.evaluate(predictions)</pre><pre>print(“RMSE on test set: “, rmse_test)</pre><p><strong><em>Output:</em></strong></p><pre>R2 score on test set:  0.5687396999670697<br>RMSE on test set:  0.7590445544382896</pre><p>The performance of the model isn’t very great. But we can definitely improve the model performance by preprocessing the data even further like removing outliers, transforming the skewed features, feature extraction by principal component analysis etc. We can also play around with the hyperparameters of the model and tune them for a better performance.</p><p>Hopefully this is gives you a good start in machine learning in PySpark. While this is just a simple regression problem, you can also perform clustering and classification using various different supervised and unsupervised machine learning algorithms provided by Spark’s machine learning library. Now that you know how this works, you can try the PySpark implemention of some of the machine learning tasks you’ve already done using pandas and sklearn so that you’ll get a better understanding. Build simple machine learning models for a dataset of your choice and try to improve their performance.</p><p>As a bonus, here is a simple movie recommendation system in PySpark using Alternating Least Squares for collaborative filtering, a very popular algorithm for making recommendations. For this we will be using Spark’s machine learning library and the movielens 100k dataset (that we have already used in the previous PySpark RDD blog) to train the model for recommending ten movies for a given user ID. The PySpark implementation along with the dataset can be found <a href="https://github.com/Anveshrithaa/Apache-Spark-Projects/tree/master/movies-recommendation">here</a>.</p><p>In the <a href="https://medium.com/@anveshrithaas/end-to-end-machine-learning-pipeline-on-databricks-part-5-c10273e2cd88">next blog</a> in this series, we’ll build an end-to-end machine learning pipeline, not on our local machine but on a cloud-based unified analytics platform — Databricks, to get the real feel of working with Apache Spark for large-scale data processing, analytics and machine learning. You’ll also be introduced to AWS and much more to understand how data scientists and engineers deal with large amount of data in the real-world scenario. Get ready to learn something new and exciting. Don’t miss it! Check out the next blog <a href="https://medium.com/@anveshrithaas/end-to-end-machine-learning-pipeline-on-databricks-part-5-c10273e2cd88">here</a>.</p><p>Check out the other blogs in this series</p><p><a href="https://medium.com/@anveshrithaas/getting-started-with-apache-spark-part-1-91b379204ae0"><strong><em>Part 1— Getting started with Apache Spark</em></strong></a></p><p><a href="https://medium.com/@anveshrithaas/introduction-to-pyspark-part-2-6d6113e31592"><strong><em>Part 2 — Introduction to PySpark</em></strong></a></p><p><a href="https://medium.com/@anveshrithaas/understanding-spark-rdds-part-3-3b1b9331652a"><strong><em>Part 3 — Understanding Spark RDDs</em></strong></a></p><p><a href="https://medium.com/@anveshrithaas/end-to-end-machine-learning-pipeline-on-databricks-part-5-c10273e2cd88"><strong><em>Part 5 — End-to-end Machine Learning Pipeline on Databricks</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5813e831922f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/machine-learning-in-pyspark-part-4-5813e831922f">Machine Learning in PySpark — Part 4</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[Understanding Spark RDDs — Part 3]]></title>
            <link>https://medium.com/analytics-vidhya/understanding-spark-rdds-part-3-3b1b9331652a?source=rss-96b0fc955cbc------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b1b9331652a</guid>
            <category><![CDATA[spark-rdd]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[introduction-to-pyspark]]></category>
            <dc:creator><![CDATA[Anveshrithaa S]]></dc:creator>
            <pubDate>Fri, 10 Jul 2020 19:48:45 GMT</pubDate>
            <atom:updated>2020-07-23T12:05:02.869Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Spark RDDs — Part 3</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/0*RHAxHRD8HJOFAuwO.png" /><figcaption>Image source: Java Developer Zone</figcaption></figure><p>Welcome! The <a href="https://medium.com/@anveshrithaas/introduction-to-pyspark-part-2-6d6113e31592">previous blog</a> gave a brief overview of RDDs in Spark. In this article we’ll discuss the two important operations on Spark RDDs — <strong>transformations and actions</strong> along with examples. By the end of this blog, you’ll have a clear idea on RDDs and how to write PySpark programs using RDDs.</p><h4>Creating RDDs in PySpark</h4><p>Before we look into the operations that can be performed on RDDs, let’s learn how to create RDDs in PySpark. I hope you have already installed and configured PySpark in your computer. If not, refer <a href="https://medium.com/@anveshrithaas/introduction-to-pyspark-part-2-6d6113e31592">the previous blog</a> for a quick installation guide.</p><p>There are more than one way of creating RDDs. One simple method is by parallelizing an existing collection in the driver program by passing it to SparkContext’s <em>parallelize()</em> method. Here the elements of the collection are copied into an RDD and can be processed in parallel.</p><pre>data= [“Scala”, “Python”, “Java”, “R”]</pre><pre>myRDD= sc.parallelize(data)</pre><p><strong><em>Note: </em></strong><em>Do not forget to create the SparkContext sc (unless you are using PySpark shell which automatically creates sc). That’s the first thing you should do while writing any Spark program.</em></p><p>Here, the data in the parallelized collection is split into partitions and one task will be carried out on each partition of the cluster. By default, Spark sets the number of partitions depending on the cluster. It can also be set manually by passing the number of partitions as the second parameter to the <em>parallelize()</em> method.</p><pre>data= [“Scala”, “Python”, “Java”, “R”]</pre><pre>#data split into two partitions<br>myRDD= sc.parallelize(data,2) </pre><p>The other way of creating a Spark RDD is from other data sources like the local file system, Cassandra, HDFS etc. Here, the data is loaded from external datasets. To do this, we use the SparkContext’s <em>textFile</em> method that takes the URL of the file as its parameter.</p><pre>#text file to RDD<br>myRDD= sc.textFile(“/path_to_file/textdata.txt”)</pre><pre># CSV file to RDD<br>myRDD=sc.textFile(“/path_to_file/csvdata.csv”)</pre><p><strong><em>Note: </em></strong><em>Make sure that if you are using a file from your local filesystem, the file is accessible at the same path on the worker nodes as well.</em></p><p>Spark’s RDDs support two types of operations, namely transformations and actions. Once the RDDs are created we can perform transformations and actions on them.</p><h3>Transformations</h3><p>Transformations are operations on the RDDs that create a new RDD by making changes to the original RDD. Briefly, they are functions that take an existing RDD as input to give new RDDs as output, without making changes to the original RDD (Note that RDDs are immutable!) This process of transforming an RDD to a new one is done through operations such as filter, map, reduceByKey, sortBy etc. As seen in the previous blog, RDDs follow lazy evaluation. That is, transformations on RDDs will not be executed until it is triggered when needed. Thus, these operations can be carried out at any time just by calling an action on the data. The transformations on RDD can be categorized into two: Narrow and Wide.</p><ul><li>In <strong>narrow transformations</strong>, the result of the transformation is such that in the output RDD each of the partitions have records that are from the same partition in the parent RDD. Operations like Map, FlatMap, Filter, Sample come under narrow transformations.</li><li>Whereas in <strong>wide transformations</strong>, the data in each of the partitions of the resulting RDD comes from multiple different partitions in the parent RDD. Transformation functions like groupByKey(), reduceByKey() fall under the category of wide transformation.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6dYzs4GK3Q9nSPkMp-3w2w.png" /><figcaption>Source: Pinterest</figcaption></figure><p>Let’s see some of the transformations on RDD.</p><h4>map()</h4><p>The <em>map()</em> returns a new RDD by applying a function to each of the elements in the original RDD.</p><pre>data= [1, 2, 3, 4, 5]</pre><pre>myRDD= sc.parallelize(data)</pre><pre>#Returns a new RDD by multiplying all elements of parent RDD by 2<br>newRDD= myRDD.map(lambda x: x*2)</pre><pre>print(newRDD.collect())</pre><p><strong><em>Output:</em></strong></p><pre>[2, 4, 6, 8, 10]</pre><h4>flatMap()</h4><p><em>flatMap()</em> returns a new RDD by applying the function to every element of the parent RDD and then flattening the result. Let’s see an example to understand the difference between <em>map()</em> and <em>flatMap()</em>.</p><pre>data= [1, 2, 3]<br>myRDD= sc.parallelize(data)</pre><pre><strong>#map() returns [[1], [1, 2], [1, 2, 3]]</strong><br>mapRDD= myRDD.map(lambda x: range(1,x))</pre><pre><strong>#flatmap() returns [1, 1, 2, 1, 2, 3]</strong><br>flatMapRDD = myRDD.flatMap(lambda x: range(1,x))</pre><h4>filter()</h4><p><em>filter()</em> returns a new RDD containing only the elements in the parent RDD that satisfy the function inside filter.</p><pre>data= [1, 2, 3, 4, 5, 6]</pre><pre>myRDD= sc.parallelize(data)</pre><pre>#returns an RDD with only the elements that are divisible by 2<br>newRDD= myRDD.filter(lambda x: x%2 == 0)</pre><pre>print(newRDD.collect())</pre><p><strong><em>Output:</em></strong></p><pre>[2, 4, 6]</pre><h4>distinct()</h4><p><em>distinct()</em> returns a new RDD that contains only the distinct elements in the parent RDD</p><pre>data= [1, 2, 2, 3, 3, 3]</pre><pre>myRDD= sc.parallelize(data)</pre><pre>newRDD= myRDD.distinct()</pre><pre>print(newRDD.collect())</pre><p><strong><em>Output:</em></strong></p><pre>[1, 2, 3]</pre><h4>groupByKey()</h4><p><em>groupByKey()</em> groups the values for each key in the (key, value) pairs of the RDD into a single sequence. What we get is an object that allows us to iterate over the results.</p><pre>myRDD = sc.parallelize([(“a”, 1), (“a”, 2), (“a”, 3), (“b”, 1)])</pre><pre>#print result as list<br>resultList= myRDD.groupByKey().mapValues(list)</pre><pre>reultList.collect()</pre><p><strong><em>Output:</em></strong></p><pre>[(‘a’, [1, 2, 3]), (‘b’, [1])]</pre><h4>reduceByKey()</h4><p><em>reduceByKey()</em> when called on a dataset of (key, value) pairs, returns a new dataset in which the values for each of its key are aggregated.</p><pre>from operator import add</pre><pre>myRDD = sc.parallelize([(“a”, 1), (“a”, 2), (“a”, 3), (“b”, 1)])</pre><pre>#adds the values by keys<br>newRDD= myRDD.reduceByKey(add)</pre><pre>newRDD.collect()</pre><p><strong><em>Output:</em></strong></p><pre>[(‘a’, 6), (‘b’, 1)]</pre><p><strong><em>Note:</em></strong><em> groupByKey() and reduceByKey() might seem similar. The difference between them is that, when groupByKey is called on an RDD, the data in the partitions are shuffled over the network and only then they are grouped. This results in a lot of data being transferred over the network unnecessarily. Whereas, reduceByKey() combines the pairs based on the key on their respective partitions locally before shuffling the data making it more efficient. Thus, reduceByKey() is used for large datasets for better performance.</em></p><h4>sortByKey()</h4><p><em>sortByKey()</em> returns a new RDD with (key,value) pairs of parent RDD in sorted order according to the key.</p><pre>myRDD = sc.parallelize([(“c”, 1), (“d”, 2), (“a”, 3), (“b”, 4)])</pre><pre>#sort by key<br>newRDD= myRDD.sortByKey()</pre><pre>newRDD.collect()</pre><p><strong><em>Output:</em></strong></p><pre>[(‘a’, 3), (‘b’, 4), (‘c’, 1), (‘d’, 2)]</pre><h4>union()</h4><p><em>union()</em> returns a new RDD that is the union of the parent RDDs.</p><pre>myRDD1 = sc.parallelize([1, 2, 3, 4])</pre><pre>myRDD2 = sc.parallelize([ 3, 4, 5, 6, 7])</pre><pre>#union of myRDD1 and myRDD2<br>newRDD = myRDD1.union(myRDD2)</pre><pre>newRDD.collect()</pre><p><strong>Output:</strong></p><pre>[1, 2, 3, 4, 3, 4, 5, 6, 7]</pre><p>Similarly, we have intersection() that returns the intersection of two RDDs.</p><h3>Actions</h3><p>Actions are the operations on the RDD to carry out computations and return the final result back to the driver. It triggers the execution to carry out intermediate transformations after loading the data into the RDD and finally pass the result back. These actions are operations that result in non-RDD values. As we already saw, the transformations are executed only when an action requires a result to be returned. Collect, reduce, countByKey, count are some of the actions.</p><p>Let’s look into some of the actions on RDDs with examples.</p><h4>collect()</h4><p>Looking at the above examples, by now you will know what <em>collect()</em> does. It returns a list that contains all the elements of the RDD.</p><h4>count()</h4><p><em>count()</em> returns the number of elements in the RDD</p><pre>data= [“Scala”, “Python”, “Java”, “R”]</pre><pre>myRDD= sc.parallelize(data)</pre><pre>#Returns 4 as output<br>myRDD.count()</pre><h4>reduce()</h4><p><em>reduce()</em> aggregates the elements of the RDD using a function that takes two elements of the RDD as input and gives the result.</p><pre>data= [1, 2, 3, 4, 5]</pre><pre>myRDD= sc.parallelize(data)</pre><pre>#returns the product of all the elements<br>myRDD.reduce( lambda x, y: x * y)</pre><p><strong>Output:</strong></p><pre>120</pre><p>It can be used for strings also. In that case, the result will also be a string.</p><pre>data= [“Scala”, “Python”, “Java”, “R”]</pre><pre>myRDD= sc.parallelize(data)</pre><pre>#Concatenate the string elements<br>myRDD.reduce( lambda x, y: x + y)</pre><p><strong>Output:</strong></p><pre>‘ScalaPythonJavaR’</pre><h4>foreach()</h4><p>Applies a function to very element in the RDD</p><pre>def fun(x):<br>    print(x)</pre><pre>data= [“Scala”, “Python”, “Java”, “R”]</pre><pre>myRDD= sc.parallelize(data)</pre><pre>#function applied to all the elements<br>myRDD.foreach(fun)</pre><p><strong>Output:</strong></p><pre>Scala<br>Python<br>Java<br>R</pre><h4>countByValue()</h4><p>It returns the count of each unique value in the RDD as dictionary with (value, count) pairs.</p><pre>data= [“Python”, “Scala”, “Python”, “R”, “Python”, “Java”, “R”, ]</pre><pre>myRDD= sc.parallelize(data)</pre><pre>#items() returns a list with all the dictionary keys and values returned by countByValue()</pre><pre>myRDD.countByValue().items()</pre><p><strong>Output:</strong></p><pre>[(‘Python’, 3), (‘R’, 2), (‘Java’, 1), (‘Scala’, 1)]</pre><h4>countByKey()</h4><p>It counts the number of values for each unique key in the RDD and returns it as a dictionary.</p><pre>data= [(“a”, 1), (“b”, 1), (“c”, 1), (“a”, 1)]</pre><pre>myRDD = sc.parallelize(data)</pre><pre>myRDD.countByKey().items()</pre><p><strong>Output:</strong></p><pre>[(‘a’, 2), (‘b’, 1), (‘c’, 1)]</pre><h4>take(n)</h4><p><em>take(n)</em> returns the first n elements of RDD in the same order</p><pre>data= [2, 5, 3, 8, 4]</pre><pre>myRDD= sc.parallelize(data)</pre><pre>#return the first 2 elements<br>myRDD.take(3)</pre><p><strong>Output:</strong></p><pre>[2, 5, 3]</pre><h4>top(n)</h4><p>Returns the first n elements out of all the RDD elements arranged in the descending order.</p><pre>data= [2, 5, 3, 8, 4]</pre><pre>myRDD= sc.parallelize(data)</pre><pre>#return the first 2 elements<br>myRDD.take(3)</pre><p><strong>Output:</strong></p><pre>[8, 5, 4]</pre><h4>Let’s get hands-on!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/0*2jSujqlJ-QNP1XOP.jpg" /><figcaption>Image source: Freepik</figcaption></figure><p>Now that we are familiar with the basic transformations and actions on RDDs in PySpark, it’s time to get a holistic view of how these work in a complete Spark program. To demonstrate that, here are a few simple use cases of PySpark that will give a clear insight into how SparkContext, RDDs, transformations and actions are used in a Spark program. These are simple programs that you can try coding it yourself. So before taking a look at the code, do try coding it on your own.</p><p><strong><em>Note:</em></strong><em> To run the PySpark application, execute the following command in the command prompt</em></p><pre><strong>spark-submit filename.py</strong></pre><h4>Problem statement 1 — Popular Movies:</h4><p>Come up with a Spark program to find the most popular movies<strong> </strong>based on the number of views and display the name of the movie rather than the movie ID. The dataset to be used is the movielens dataset that contains 100k movie ratings. The movie IDs are stored in the u.data file and the corresponding movie names are stored in the u.item file. The dataset can be found <a href="https://github.com/Anveshrithaa/Apache-Spark-Projects/tree/master/popular-movies/ml-100k">here</a>.</p><p><strong><em>Note: </em></strong><em>For this, we will be using the broadcast variables that are used to save the copy of common data across all nodes. This variable is cached on all the worker nodes instead of sending the data explicitly along with its tasks for more efficiency.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c543381ab62ae14c2ee087bf58681c10/href">https://medium.com/media/c543381ab62ae14c2ee087bf58681c10/href</a></iframe><p><strong>Output:</strong></p><pre>(‘Star Wars (1977)’, 583)<br>(‘Contact (1997)’, 509)<br>(‘Fargo (1996)’, 508)<br>(‘Return of the Jedi (1983)’, 507)<br>(‘Liar Liar (1997)’, 485)<br>(‘English Patient, The (1996)’, 481)<br>(‘Scream (1996)’, 478)<br>(‘Toy Story (1995)’, 452)<br>(‘Air Force One (1997)’, 431)<br>(‘Independence Day (ID4) (1996)’, 429)</pre><h4>Problem statement 2 — Word count:</h4><p>Find all the unique words in a book and the number of occurrences of each of those words. The dataset to be used is book.txt and can be found <a href="https://github.com/Anveshrithaa/Apache-Spark-Projects/blob/master/word-count/Book.txt">here</a>.</p><p>List only the words by eliminating any punctuation marks or other things that are not part of a word. The words shouldn’t be case-sensitive while considering unique words. That is, for example, ‘Spark’ and ‘spark’ are considered as one unique word irrespective of the capitalization.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a24680fed7a36ed44c326ccd379e2955/href">https://medium.com/media/a24680fed7a36ed44c326ccd379e2955/href</a></iframe><p>If you find it interesting, go ahead and choose a problem statement of your choice and play around with it!</p><p>In this blog, we saw how to create RDDs and the more about operations on RDDs along with few examples. I hope this gave you a clear understanding of the basics of the Spark core. Now let’s move on to other components of Apache Spark. It’s time to get started with the most interesting part- Machine Learning with PySpark! Do check out the <a href="https://medium.com/@anveshrithaas/machine-learning-in-pyspark-part-4-5813e831922f">next article</a> for a hands-on session on the Machine Learning aspect of Spark using python. Looking forward to seeing you there!</p><p>Check out the other blogs in this series</p><p><a href="https://medium.com/@anveshrithaas/getting-started-with-apache-spark-part-1-91b379204ae0"><strong><em>Part 1 — Getting started with Apache Spark</em></strong></a></p><p><a href="https://medium.com/@anveshrithaas/introduction-to-pyspark-part-2-6d6113e31592"><strong><em>Part 2 — Introduction to PySpark</em></strong></a></p><p><a href="https://medium.com/@anveshrithaas/machine-learning-in-pyspark-part-4-5813e831922f"><strong><em>Part 4 — Machine Learning in PySpark</em></strong></a></p><p><a href="https://medium.com/@anveshrithaas/end-to-end-machine-learning-pipeline-on-databricks-part-5-c10273e2cd88"><strong><em>Part 5 — End-to-end Machine Learning Pipeline on Databricks</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b1b9331652a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/understanding-spark-rdds-part-3-3b1b9331652a">Understanding Spark RDDs — Part 3</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[Introduction to PySpark — Part 2]]></title>
            <link>https://medium.com/analytics-vidhya/introduction-to-pyspark-part-2-6d6113e31592?source=rss-96b0fc955cbc------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d6113e31592</guid>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[introduction-to-pyspark]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[apache-spark]]></category>
            <dc:creator><![CDATA[Anveshrithaa S]]></dc:creator>
            <pubDate>Fri, 10 Jul 2020 19:46:00 GMT</pubDate>
            <atom:updated>2020-07-22T13:53:22.795Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction to PySpark — Part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/0*2jYXsGugpWPUAndD.png" /></figure><p>In the <a href="https://medium.com/@anveshrithaas/getting-started-with-apache-spark-part-1-91b379204ae0">previous blog</a>, we started with the introduction to Apache Spark, why it is preferred, its features and advantages, architecture and working along with its industrial use cases. In this article we’ll get started with PySpark — Apache Spark using Python! By the end of this article, you’ll have a better understanding of what PySpark is, why we choose python for Spark, its features and advantages followed by a quick installation guide to set up PySpark in your own computer. Finally, this article will throw some light on some of the important concepts in Spark in order to proceed further.</p><h3>What is PySpark?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TwdqU3ATPwkJZLM9.png" /><figcaption>Source: Databricks</figcaption></figure><p>As we have already discussed, Apache Spark also supports Python along with other languages, to make it easier for developers who are more comfortable working with Python for Apache Spark. Python being a relatively easier programming language to learn and use as compared to Spark’s native language Scala, it is preferred by many to develop Spark applications. As we all know, Python is the de facto language for many data analytics workload. While Apache Spark is the most extensively used big data framework today, Python is one of the most widely used programming languages especially for data science. So why not integrate them? This is where PySpark — python for Spark comes in. In order to support Python with Apache Spark, PySpark was released. As many data scientists and analysts use python for its rich libraries, integrating it with Spark is having the best of both worlds. With a strong support by the open source community, PySpark was developed using the Py4j library, to interface with the RDDs in Apache Spark using Python. High speed data processing, powerful caching, real-time and in-memory computation and low latency are some of the features of PySpark that makes it better than other data processing frameworks.</p><h3>Why choose Python for Spark?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*D5-uKOxN43o7T7dd.png" /><figcaption>Source: becominghuman.ai</figcaption></figure><p>Python is easier to learn and use compared to other programming languages, thanks to its syntax and standard libraries. Python being a dynamically typed language, facilitates Spark’s RDDs to hold objects of multiple types. Moreover, Python has an extensive and rich set of libraries for a wide range of utilities like machine learning, natural language processing, visualization, local data transformations and many more.</p><p>While python has many libraries like Pandas, NumPy, SciPy for data analysis and manipulation, these libraries are memory dependent and depend on a single node system. Hence, these are not ideal for working with very large datasets in the order of terabytes and petabytes. With Pandas, scalability is an issue. In cases of real-time or near real-time flow of data, where large amount of data needs to be brought into an integrated space for transformation, processing and analysis, Pandas wouldn’t be an optimal choice. Instead, we need a framework to do the work faster and more efficiently by means of distributed and pipelined processing. This is where PySpark would come into action.</p><p><strong><em>Note:</em></strong><em> A Spark DataFrame can be converted to a Pandas DataFrame using the toPandas() function. But when the distributed Spark DataFrame is converted, all the data is brought into a single node driver memory. Hence, it is not efficient for large datasets.</em></p><h3><strong>PySpark Installation and Setup</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*iRtpDYbOnI49VBfnWrfCJA.jpeg" /></figure><p>Here are the steps to be followed in order to install and setup Spark in Windows.</p><h4>Installing Prerequisites</h4><ol><li><strong>Install Java</strong></li></ol><ul><li>Make sure that Java is already installed in your computer (version 7 or later)</li><li>Set the environment variables and add it to the PATH variable.</li></ul><p>If you haven’t installed Java, refer <a href="https://www.guru99.com/install-java.html">this installation guide</a> to get it done.</p><p><strong>2. Install Python</strong></p><ul><li>Make sure that you’ve Python installed (version 2.7 or later)</li></ul><p>To install Python for Windows, refer <a href="https://www.howtogeek.com/197947/how-to-install-python-on-windows/">this installation guide</a></p><p><strong>3. Install Spark</strong></p><ul><li>Go to the <a href="http://spark.apache.org/downloads.html">Apache Spark home page</a></li><li>Choose the latest stable Spark release and for the package type choose pre-built for Apache Hadoop</li><li>And download the .tgz file by clicking the link in step 3 (shown below)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*pDE3j3obymiTxMR-imW24Q.png" /></figure><ul><li>Extract the downloaded zip file to a folder in a chosen directory and name it as ‘spark’ (The path to my folder is C:\spark as I’ve stored it in the C drive)</li><li>Set the environment variable:</li></ul><pre>SPARK_HOME = C:\spark\spark-3.0.0-bin-hadoop2.7</pre><ul><li>Add the path to the PATH environment variable:</li></ul><pre>C:\spark\spark-3.0.0-bin-hadoop2.7\bin</pre><p><strong>4. Installing winutils.exe</strong></p><ul><li>Go to <a href="https://github.com/steveloughran/winutils">https://github.com/steveloughran/winutils </a>and download the winutils.exe for your Hadoop version (hadoop-2.7.1 in my case)</li><li>Move the winutils.exe file to the bin folder inside SPARK_HOME (In my case it is C:\spark\spark-3.0.0-bin-hadoop2.7\bin)</li><li>Set the environment variable (Same as SPARK_HOME):</li></ul><pre>HADOOP_HOME = C:\spark\spark-3.0.0-bin-hadoop2.7</pre><p><strong>5. Verifying PySpark installation</strong></p><ul><li>To verify if PySpark is installed successfully, open command prompt and type pyspark and execute it to enter the PySpark shell. If it is installed correctly, then you should see the output similar to the following</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*N5WG5UkO4q5-rqSdGlAFiQ.png" /></figure><p><strong><em>Note:</em></strong><em> To avoid future errors and fix some bugs after installing Spark follow the optional step (Step 4) in</em><a href="https://medium.com/big-data-engineering/how-to-install-apache-spark-2-x-in-your-pc-e2047246ffc3"><em> this article</em></a></p><p>PySpark is successfully installed and now we are good to go! But before we dive deeper into this, there are a few important concepts and terminologies in Spark that you have to understand before going any further.</p><h4>SparkContext, SparkConf and SparkSession</h4><p>SparkContext is the entry point of Spark functionality. The first thing that a Spark application should do is create a SparkContext object that defines how to access the cluster. When the Spark application is executed, the driver program starts and the SparkContext is initialized. The SparkContext generated by the Spark driver application allows the Spark application to access the Spark cluster using the Resource Manager.</p><p>Firstly, SparkConf which defines the configuration for a Spark application should be created in order to create the SparkContext. SparkConf is used for configuring Spark and it contains the various configuration parameters that are passed to the SparkContext by the driver application. Some of the commonly used parameters are the master parameter that gives the URL of the cluster it connects to and the appName parameter that gives the name of your job. The SparkConf and SparkContext are created as follows.</p><pre>#Creating SprarkConf object to configure Spark to run locally <br>conf = SparkConf().setMaster(&quot;local&quot;).setAppName(&quot;SparkBlog&quot;)</pre><pre>#Creating SparkContext<br>sc = SparkContext(conf)</pre><p>From Spark 2.0 onwards, SparkSession was introduced that serves as the unified entry point which eliminates the need to explicitly create SparkConf and SparkContext, as they are encapsulated withing the SparkSession. All the functionalities that were available with SparkContext are now available with SparkSession, thus replacing SparkContext and SparkConf. The SparkSession is created as follows.</p><pre>spark = SparkSession.builder().master(“local”)\<br>.appName(“example of SparkSession”)\<br>.config(“spark.some.config.option”, “config-value”)\<br>.getOrCreate()</pre><p><strong><em>Note:</em> </strong><em>If you are using the pyspark shell, SparkContext variable </em><strong><em>‘sc’</em></strong><em> and SparkSession variable </em><strong><em>‘spark’</em></strong><em> are created automatically. You need not create them explicitly.</em></p><h4>Resilient Distributed Datasets (RDDs)</h4><p>Resilient Distributed Datasets (RDDs) are the building blocks of PySpark. RDD is the fundamental data structure of Apache Spark. It is an immutable collection of objects that can be split across the cluster facilitating in-memory data storage thus making it more efficient. RDD being a schema-less data structure, can handle structured as well as unstructured data. While RDDs can be logically partitioned across various nodes in a cluster, operations on RDDs can also be split and executed in parallel, facilitating a faster and scalable parallel processing. RDD being a distributed memory abstraction, one of the salient features of it is that it is highly resilient. This is because of the fact that the data chunks are replicated across multiple nodes in the cluster and thus, they have the capability to recover quickly from any issue as the data will still be processed by other nodes even if one executor node fails, making it highly fault tolerant. Also, RDDs follow lazy evaluation, that is, the execution is not started right away, rather they are triggered only when needed. There are two basic and important operations that can be carried out on RDDs — Transformations and Actions about which we’ll discuss in the next blog.</p><p>To summarize, we started with an overview of PySpark, why it is used for Spark and in what ways it is better than some of the other python libraries out there. We saw how to install it in your computer and then ended it with an overview on SparkContext, SparkConf, SparkSession and finally the backbone of Spark — the RDDs! I hope now you’ve got an idea of what it really is. There is still more to learn which we’ll be covering in the subsequent articles in this series. Check out the <a href="https://medium.com/@anveshrithaas/understanding-spark-rdds-part-3-3b1b9331652a">next article</a> on operations on RDDs, where you’ll get a much clearer picture. Happy learning!</p><p>Check out the other blogs in this series</p><p><a href="https://medium.com/@anveshrithaas/getting-started-with-apache-spark-part-1-91b379204ae0"><strong><em>Part 1 — Getting started with Apache Spark</em></strong></a></p><p><a href="https://medium.com/@anveshrithaas/understanding-spark-rdds-part-3-3b1b9331652a"><strong><em>Part 3 — Understanding Spark RDDs</em></strong></a></p><p><a href="https://medium.com/@anveshrithaas/machine-learning-in-pyspark-part-4-5813e831922f"><strong><em>Part 4 — Machine Learning in PySpark</em></strong></a></p><p><a href="https://medium.com/@anveshrithaas/end-to-end-machine-learning-pipeline-on-databricks-part-5-c10273e2cd88"><strong><em>Part 5 — End-to-end Machine Learning Pipeline on Databricks</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d6113e31592" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/introduction-to-pyspark-part-2-6d6113e31592">Introduction to PySpark — Part 2</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[Getting started with Apache Spark — Part 1]]></title>
            <link>https://medium.com/analytics-vidhya/getting-started-with-apache-spark-part-1-91b379204ae0?source=rss-96b0fc955cbc------2</link>
            <guid isPermaLink="false">https://medium.com/p/91b379204ae0</guid>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[introduction-to-pyspark]]></category>
            <dc:creator><![CDATA[Anveshrithaa S]]></dc:creator>
            <pubDate>Fri, 10 Jul 2020 19:39:18 GMT</pubDate>
            <atom:updated>2020-07-23T12:04:45.078Z</atom:updated>
            <content:encoded><![CDATA[<h3>Getting started with Apache Spark — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q7O2UbY_baJYVtNhVrHqtw.png" /><figcaption>Source: Udemy</figcaption></figure><p>In this era of big data where mind-boggling amount of data are being created every minute, it is becoming increasingly important for businesses to analyze these data for quick insights. This has created a demand for faster and efficient data processing technologies. With “big data” and “data science” being the buzzwords in today’s world, it is no wonder why the industry is running behind big data engines like Apache Spark. Considering the demand for Apache Spark developers we can surely say Spark is the next gen big data tool and one of the most in-demand big data skills you should be knowing. If you are looking forward to getting started in this field, then this blog has something for you.</p><p>This blog is the first one in the series on Apache Spark<strong>,</strong> and in this<strong> </strong>we will see what is Apache Spark, why it is used, the industrial use cases of Spark and how it is used across a myriad of industries. We’ll also take a look into the Apache Spark ecosystem and its components. Following that, we’ll see why Spark is preferred and what features of it make it desirable and finally end it with the internal architecture of Spark and how it works.</p><h3>Apache Spark — What is it?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*UUGMDuAP6c_brkuMM0Yk6g.png" /><figcaption>Source: PNGkey</figcaption></figure><p>Apache Spark is data processing framework that can perform tasks on very large data sets in a very less time. Fast and flexible, originally developed at UC Berkeley, Spark went on to become the largest open source community in big data, being regarded as one of the best and most widely used big data processing frameworks in the world. Thereon, it was extensively adopted by major enterprises across various industries.</p><p>Apache Spark is a distributed data processing framework which can rapidly process large data by distributing the tasks across multiple nodes. Deploying Spark at a massive scale facilitates high speed processing of even petabytes of data on clusters of thousands of nodes! In fact, Spark can carry out large scale data processing 100 times faster than Hadoop. Spark can perform batch as well as stream processing which makes it a powerful engine that can process data in both real-time and batch mode. With its easy to use APIs, Spark makes the work associated with distributed computing and big data processing easier for its users.</p><p>Being built on Scala, Spark supports multiple languages by providing APIs for Scala, Java, Python and the latest one being R. This is a key feature of Spark which makes it flexible for developers to create and run applications in a language of their convenience.</p><h3>Apache Spark Use Cases</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/0*o4kGqUZEGsXfzk7P.png" /></figure><p>Today, almost every industry deals with big data. For many of these industries, Apache Spark is the top choice considering its amazing features and the numerous advantages that it provides. Spark is widely used by many companies ranging across almost every industry. And it is deployed at a massive scale, collectively processing multiple petabytes of data on clusters of over thousands of nodes. Here are some of the industries that use Spark for dealing with the three V’s of big data — Volume, Velocity and Variety.</p><ul><li>Today, the <strong>media and entertainment industry</strong> being one of the fastest growing industries, is moving towards online streaming. Leading industrial giants like Netflix use Apache Spark for real-time stream processing to process billions of events per day for the purpose of providing personalized online recommendations to its customers. Also, Yahoo uses Spark for machine learning to personalize web pages and news articles for its customers.</li><li>The<strong> finance sector</strong> is yet another industry where real-time processing plays a vital role. Apache Spark is used to analyze and gain quick insights into aspects like customer segmentation, target advertising, credit risk assessment, customer churn prediction, fraud detection in transactions etc for the right decision-making process in business. It is used to achieve top-notch results in the analysis of massive volume of transaction logs.</li><li>Another sector where Spark has a very important role is the <strong>healthcare industry</strong> where it is used to analyse large volumes of patient health records and clinical data to gain quick and useful insights.</li><li>Coming to the <strong>travel industry</strong>, leading travel websites and apps like TripAdvisor and OpenTable use Apache Spark to speed up customized recommendations to its users.</li><li>Last but not the least, an industry that is inseparable from data analysis and target advertising is the <strong>E-commerce and retail sector</strong>. The leaders in E-commerce like Alibaba and eBay use Spark to analyse petabytes of data. Some of such use cases of Spark are targeted advertising, personalized recommendations and offers etc.</li></ul><h3>The Spark Ecosystem and its Components</h3><p>Let’s take a brief look into the Apache Spark ecosystem and its components. Spark incorporates various in-built libraries and components namely the Spark core, Spark SQL, Spark Streaming, Spark MLlib and Spark GraphX.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*bZRKtlmT6gSkeli8mCsi0w.png" /><figcaption>The Spark ecosystem</figcaption></figure><ol><li><strong>Spark core</strong> — The basic functionalities of Spark are built upon the Spark Core. It incorporates Resilient Distributed Datasets (RDDs) which is one of Spark’s main abstractions. The Spark core is responsible for task scheduling, fault recovery, in-memory computation and memory management. It serves as the foundation for the processing of large datasets.</li><li><strong>Spark SQL</strong> — It is a module of Spark that provides SQL interface to Spark for working with structured and semi-structured data and executing SQL queries on them.</li><li><strong>Spark Streaming </strong>— It is a Spark component built upon the Spark core that is responsible for high- throughput, scalable and fault tolerant stream processing of continuously flowing data streams obtained from data streaming sources such as Apache Kafka, Apache Flume and Amazon Kinesis.</li><li><strong>Spark MLlib </strong>— It is a Spark library that facilitates the implementation of Machine Learning and Deep Learning algorithms and makes Machine Learning scalable. We will deal with this in detail in the upcoming blogs.</li><li><strong>Spark GraphX</strong> — It is a Spark API for manipulating and working with graphs and executing graph-parallel computations.</li></ol><h3>Why Spark?</h3><p>Starting from data collection followed by data cleaning and data engineering to advanced analytics through training, evaluation and validation of machine learning models for providing meaningful insights from the data, a unified framework like Apache Spark will provide an end-to-end solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/1*c9hXC7Tftw0ntHiYtVY1YQ.png" /></figure><p>The major steps involved in the process are collecting the data, analyzing the data, cleaning the data, feature engineering and exploring and generating insights from the data by building machine learning models. Spark has a role to play in each of these steps. That is the advantage of Spark because the kind of data that we are talking about here is in terms of terabytes and petabytes for which we’ll need pipelines that are highly scalable. While libraries like Pandas and NumPy work well on a single node system where the data can fit into the memory, they are not efficient in handling larger volumes of data for which we’ll need a unified framework that can distribute and handle it faster. Real-time analytics for real-time applications deals with huge amount of data that are generated in real-time such as business processes and transactions. In that case, Spark will be the go-to solution with its ability to support highly scalable data pipelines.</p><p>Spark supports data that can either be batch or real-time. Real-time data can come from various data sources either as a Kafka message or message queues or as real-time data from IoT devices that continuously stream millions of transactions and this streaming data can be handled by Spark using its Spark Streaming component. Also, Spark can read from and write into various systems such as MongoDB, Cassandra, HBase, Google Cloud, Amazon S3 etc. The ability to integrate Spark with many database systems and cloud infrastructures makes it a highly compatible and flexible big data framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/0*bdzHiY3-MUYUKixS.png" /><figcaption>Source: Databricks</figcaption></figure><h3>How Spark works</h3><p>In Spark, large amount of data is split into chunks and distributed across multiple systems to perform the task on the data rather than depending on a single node (as shown in the figure below).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*x9UgHo63dKQ6kxQ678ffNw.png" /></figure><p>The two fundamental components of a Spark application are the driver that converts the application code into multiple tasks that are distributed across the executors that run on the worker nodes and execute their assigned tasks. A cluster manager acts as a mediator between these two components. When client submits the Spark application code, the driver program starts and initializes the Spark context and it converts the transformations and actions into a logical Directed Acyclic Graph (DAG) that determines what tasks should be executed on each node and in what sequence (We’ll look into Spark context, transformations and actions in detail in the upcoming blogs). The driver also performs optimization on the DAG and distributes and schedules the work across the executors in the worker nodes. Then the cluster manager launches the executors in the worker nodes and sends the details of the task to be executed by each node. The executor executes the work and reports back to the driver.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*DJ4t3razJClvW-SswybLKg.jpeg" /></figure><p>To summarize, we started with what Spark is, why it is used, some features of Spark and its industrial use cases followed by the components of the Apache Spark ecosystem and finally the internal working and architecture of it.</p><p>Congratulations on getting started with Apache Spark and you are no more a newbie to Spark! But remember there’s still a long way to go. Check out the other articles in this series to continue your journey with Spark and learn more. In the <a href="https://medium.com/@anveshrithaas/introduction-to-pyspark-part-2-6d6113e31592">next blog</a> we’ll be looking into PySpark and and much more. Happy learning!</p><p>Check out the other blogs in this series</p><p><a href="https://medium.com/@anveshrithaas/introduction-to-pyspark-part-2-6d6113e31592"><strong><em>Part 2 — Introduction to PySpark</em></strong></a></p><p><a href="https://medium.com/@anveshrithaas/understanding-spark-rdds-part-3-3b1b9331652a"><strong><em>Part 3 — Understanding Spark RDDs</em></strong></a></p><p><a href="https://medium.com/@anveshrithaas/machine-learning-in-pyspark-part-4-5813e831922f"><strong><em>Part 4 — Machine Learning in PySpark</em></strong></a></p><p><a href="https://medium.com/@anveshrithaas/end-to-end-machine-learning-pipeline-on-databricks-part-5-c10273e2cd88"><strong><em>Part 5 — End-to-end Machine Learning Pipeline on Databricks</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91b379204ae0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/getting-started-with-apache-spark-part-1-91b379204ae0">Getting started with Apache Spark — Part 1</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>