<?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 Muhammad Muhaimin on Medium]]></title>
        <description><![CDATA[Stories by Muhammad Muhaimin on Medium]]></description>
        <link>https://medium.com/@rumman1988?source=rss-c5f31c355f23------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*XYVHF0kS7npsHzuI.</url>
            <title>Stories by Muhammad Muhaimin on Medium</title>
            <link>https://medium.com/@rumman1988?source=rss-c5f31c355f23------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 15:54:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rumman1988/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[Orchestrating Daily Spark Jobs with EMR in Airflow using AWS Wrangler]]></title>
            <link>https://medium.com/@rumman1988/orchestrating-daily-spark-jobs-from-airflow-using-aws-wrangler-5520f139aa3b?source=rss-c5f31c355f23------2</link>
            <guid isPermaLink="false">https://medium.com/p/5520f139aa3b</guid>
            <category><![CDATA[aws-wrangler]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[aws-emr]]></category>
            <category><![CDATA[big-data-pipeline]]></category>
            <dc:creator><![CDATA[Muhammad Muhaimin]]></dc:creator>
            <pubDate>Sat, 21 May 2022 22:26:45 GMT</pubDate>
            <atom:updated>2022-05-21T22:29:50.343Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xrmCEOaB5VCncye7" /><figcaption>Photo by <a href="https://unsplash.com/@mbaumi?utm_source=medium&amp;utm_medium=referral">Mika Baumeister</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://github.com/awslabs/aws-data-wrangler">AWS Wrangler</a> is a great open-source tool for using various AWS services programmatically. It allows various EMR operations and integrates nicely with Apache Airflow using a Python operator. In this tutorial we wrap all the dependencies of the spark script in a docker container, upload the script to S3 and finally run it using AWS EMR. This tutorial requires you have an understanding of</p><ul><li>Airflow</li><li>AWS EMR and S3</li><li>Docker</li></ul><h3>Dockerizing the dependencies:</h3><p>In this step, we will create a docker file and put all our libraries and additional dependencies inside the docker file.</p><p>In the first step, lets put all our dependencies and helper file inside a folder called spark_libs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*loJ2XuH61mZxiaD8Uvgj4w.png" /></figure><p>Now we need to create a file named <em>spark-pyproject.toml </em>which will be used to pack it as a project dependency. The contents for the <em>spark-pyproject.toml </em>would be following</p><pre>[tool.poetry]<br>name = &quot;spark_libs&quot;<br>version = &quot;0.1.0&quot;<br>description = &quot;&quot;<br>authors = [&quot;Muhammad Muhaimin &lt;muhammad.r.muhaimin@gmail.com&gt;&quot;]<br>include = [&quot;spark_libs&quot;]</pre><p>and finally we need a docker file; we can name it <em>Spark-Dockerfile</em>. Our docker would be like this</p><pre>FROM amazoncorretto:8<br>RUN yum -y update<br>RUN yum -y install yum-utils<br>RUN yum -y groupinstall development<br>RUN yum list python3*<br>RUN yum -y install python3 python3-dev python3-pip python3-virtualenv</pre><pre>COPY spark_libs /spark/spark_libs<br>COPY spark-pyproject.toml /spark/pyproject.toml</pre><pre>ENV PYSPARK_DRIVER_PYTHON python3<br>ENV PYSPARK_PYTHON python3</pre><pre>RUN pip3 install --upgrade pip<br>RUN pip3 install pendulum==1.4.4 <strong>\<br></strong>pyarrow==1.0.1</pre><pre>RUN pip3 install /spark</pre><p>In the next steps we need to build the docker file and push it to ecr</p><pre>aws ecr get-login-password --region us-west-2 | docker login --username AWS --password-stdin &lt;<strong><em>AWS-account-id</em></strong>&gt;.dkr.ecr.us-west-2.amazonaws.com/&lt;<strong><em>repo-name&gt;</em></strong></pre><pre>docker build -t &#39;local/emr-wrangler&#39; -f Spark-Dockerfile <strong>.</strong> --no-cache</pre><pre>docker tag local/emr-wrangler &lt;<strong><em>AWS-account-id</em></strong>&gt;.dkr.ecr.us-west-2.amazonaws.com/&lt;<strong><em>repo-name&gt;</em></strong>:<strong><em>&lt;image-tag&gt;</em></strong></pre><pre>docker push &lt;<strong><em>AWS-account-id</em></strong>&gt;.dkr.ecr.us-west-2.amazonaws.com/&lt;<strong><em>repo-name&gt;</em></strong>:<strong><em>&lt;image-tag&gt;</em></strong></pre><p>Now we have our docker image ready with all of our spark dependencies which we can use to run a spark job.</p><h3>Orchestrating Spark Jobs:</h3><p>Let’s create a python function to orchestrate Spark jobs. This function can be called using the Airflow Python operator. In this python function, we would</p><ul><li>Upload our python script containing Spark code to S3</li><li>Create an EMR cluster</li><li>Authenticate the EMR cluster to pull the docker image from the ECR repo</li><li>Run our Spark workflow in the EMR cluster inside the docker container we created earlier</li></ul><h3>Upload our python Spark script to S3:</h3><p>The first step is to upload the Python script containing spark code to S3. Let’s define a function for that</p><pre>import <strong>awswrangler</strong> as <strong>wr</strong></pre><pre><strong>def upload_file_to_s3(</strong>local_file_path:str<strong>, </strong>s3_path: str<strong>) -&gt; None:<br>    wr</strong>.<strong>s3</strong>.<strong>upload</strong>(<br>        local_file_path=&quot;./sample.py&quot;,<br>        s3_path=&quot;s3://demo/emr/script/sample.py&quot;,<br>    )</pre><h3>Create an EMR Cluster:</h3><p>We can create an EMR cluster using AWS Wrangler, the parameter we need</p><ul><li><strong>subnet_id: </strong>It can be both public and private VPC subnets, we do not need internet connectivity to run the EMR cluster. However, we may need to configure network address translation (NAT) and VPN gateways to access services or resources located outside of the VPC</li><li><strong>cluster_name: </strong>Name of the EMR cluster</li><li><strong>logging_s3_path:</strong> The S3 path where the EMR logs will be stored</li><li><strong>emr_release</strong>: AWS <a href="https://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-release-components.html">EMR releases</a> to be used</li><li><strong>instance types: </strong>instance_type_master, instance_type_core, instance_type_task params needs to be configured to select different instance types to be used for core, master and task nodes. Here are the <a href="https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-supported-instance-types.html">supported instance types for AWS EMR</a>. Here is also a <a href="https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-master-core-task-nodes.html">document from AWS </a>to understand the master, core and task nodes.</li><li><strong>number of instance types: </strong>Number of instance types can be setup using instance_num_on_demand_master, instance_num_on_demand_core and instance_num_on_demand_task parameters. The number of instance_num_on_demand_master can be <a href="https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-plan-ha.html">either one or three.</a> For choosing the number of core and task nodes please <a href="https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-plan-instances-guidelines.html">refer to the AWS guidelines</a></li><li><strong>docker: </strong>This should be true as we are planning to package all our dependencies in the docker container</li><li><strong>spark_defaults: </strong><a href="https://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-spark-configure.html">EMR spark defaults settings</a> such as driver memory, and executor memory can be configured using the spark defaults params. This takes the params as a dictionary for example if we want to set up spark driver memory as 2 GB we can set up it as a dictionary {&quot;spark.driver.memory&quot;: &quot;2g&quot;}</li><li><strong>custom_classfications: </strong>This will allow us to use extra classifications. Here for our context, we will use the following custom classification. This will allow us to write to S3 directly without writing to disks</li></ul><pre>{<br>    &quot;Classification&quot;: “core-site”, <br>    &quot;Properties&quot;: {<br>        &quot;fs.s3a.fast.upload.buffer&quot;: &quot;bytebuffer&quot;<br>     }<br>}</pre><ul><li><strong>maximize_resource_allocation:</strong> Configure spark to use <a href="https://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-spark-configure.html#emr-spark-maximizeresourceallocation">maximum resource allocation.</a></li><li><strong>keep_cluster_alive_when_no_steps: </strong>Terminate the cluster after finishing workflow</li></ul><pre>cluster_id = wr.emr.create_cluster(<br>   subnet_id=&quot;subnet-b46032ec<em>&quot;</em>,<br>   cluster_name=&quot;demo-cluster&quot;,<br>   logging_s3_path=&quot;s3://demo/emr/logs/&quot;,<br>   emr_release=&quot;emr-6.0.0&quot;,<br>   instance_type_master=&quot;m5.2xlarge&quot;,<br>   instance_type_core=&quot;r5.2xlarge&quot;,<br>   instance_type_task=&quot;r5.xlarge&quot;,<br>   instance_num_on_demand_core=4,<br>   instance_num_on_demand_task=16,<br>   docker=True,<br>   spark_defaults={&quot;spark.driver.memory&quot;: &quot;2g&quot;},<br>   custom_classifications={<br>        &quot;Classification&quot;: “core-site”, <br>        &quot;Properties&quot;: {<br>            &quot;fs.s3a.fast.upload.buffer&quot;: &quot;bytebuffer&quot;<br>         }<br>   },<br>   maximize_resource_allocation=True,<br>   keep_cluster_alive_when_no_steps=False,<br>)</pre><p>Running this successfully will return a <strong>cluster id</strong> for us which we are going to use in subsequent steps.</p><h3><strong>Authenticate EMR to access ECR:</strong></h3><p>The next step is to authenticate the EMR cluster to get access to ECR. We can use the following command.</p><pre>wr.emr.submit_ecr_credentials_refresh(<br>    cluster_id,<br>    path=&quot;s3://demo/emr/credentials/&quot;,<br>    action_on_failure=&quot;TERMINATE_JOB_FLOW&quot;<br>)</pre><p>This will stage the script ecr_credentials_refresh.py at the S3 path and also halt the job flow if authentication failed.</p><h3>Run the Spark Job:</h3><p>Finally, we can run the spark job using the command</p><pre><strong>step_id = wr</strong>.<strong>emr</strong>.<strong>submit_spark_step</strong>(<br>    cluster_id,<br>    &quot;s3://demo/emr/script/sample.py --sample_args arg_value&quot;,<br>    deploy_mode=&quot;cluster&quot;,<br>    docker_image=&quot;&lt;<strong><em>AWS-account-id</em></strong>&gt;.dkr.ecr.us-west-2.amazonaws.com/&lt;<strong><em>repo-name&gt;</em></strong>:<strong><em>&lt;image-tag&gt;&quot;</em></strong>,<br>    name=&quot;demo-spark-transformation&quot;,<br>)</pre><p>This will allow us to run the spark file we uploaded earlier to be run in the EMR cluster we just created. We can also pass additional arguments and parse them using arg parse in the python file. For the deploy mode, it is <strong>important</strong> we use cluster not client. Because currently client mode is not supported with to be run with docker. Then we need to point out to our uploaded docker image. Also we can add a name to our spark transformation job. Running this will return a <strong>step id.</strong> We can<a href="https://airflow.apache.org/docs/apache-airflow/stable/_api/airflow/models/taskinstance/index.html?highlight=xcom_push#airflow.models.taskinstance.TaskInstance.xcom_push"> push both the <strong>step id and cluster id</strong> to the Airflow XCom.</a> Which we can use in subsequent steps to check job status.</p><h3><strong>Checking the job status:</strong></h3><p>For checking the job status we can pull the cluster id and step id from the airflow XCom. Then we can check the job status using the code wr<strong>.</strong>emr<strong>.</strong>get_step_state<strong>(</strong>cluster_id<strong>,</strong> step_id<strong>) </strong>This will return us the job state which is going to be either of ‘PENDING’, ‘CANCEL_PENDING’, ‘RUNNING’, ‘COMPLETED’, ‘CANCELLED’, ‘FAILED’, ‘INTERRUPTED’</p><h3>Next Steps:</h3><p>The above steps will allow us to run a spark job in AWS using AWS wrangler. Ideally we would like to store the resultant transformed data in S3. I will share how to access the resultant data using AWS Glue table and athena in a future tutorial</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5520f139aa3b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clustering categorical and numerical datatype Using Gower Distance]]></title>
            <link>https://medium.com/@rumman1988/clustering-categorical-and-numerical-datatype-using-gower-distance-ab89b3aa90d9?source=rss-c5f31c355f23------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab89b3aa90d9</guid>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Muhammad Muhaimin]]></dc:creator>
            <pubDate>Tue, 07 Aug 2018 05:41:13 GMT</pubDate>
            <atom:updated>2019-06-28T08:46:48.020Z</atom:updated>
            <content:encoded><![CDATA[<p>Data comes in various forms and shapes. Sometimes we have continuous numerical data and sometimes we have discrete categorical data. In real-world scenario many times we have data that are mixed which has both numerical and categorical attributes. To get meaningful insight from data, cluster analysis or clustering is a very useful technique. In the following section, we are going to discuss certain approach we can follow for clustering mixed data type, where we have both numerical and categorical data.</p><h3>Gower Distance</h3><p>Gower Distance is a distance measure that can be used to calculate distance between two entity whose attribute has a mixed of categorical and numerical values. Details of Gower distance is out of scope of this post and I would not discuss it here but if you are interested you can read <a href="https://cran.r-project.org/web/packages/gower/vignettes/intro.html"><em>Introduction to the gower package</em></a> to know details also you can read the original paper Gower (1971) <a href="https://www.jstor.org/stable/2528823">A general coefficient of similarity and some of its properties.</a> <em>Biometrics</em> <strong>27</strong> 857–874.</p><p><strong>First step</strong> is to analyze dissimilarity between observations in the data set using Gower distance. One way to express that, is using <a href="https://en.wikibooks.org/wiki/Data_Mining_Algorithms_In_R/Clustering/Dissimilarity_Matrix_Calculation">dissimilarity matrix</a>. By using <a href="https://www.rdocumentation.org/packages/cluster/versions/2.0.7-1/topics/daisy">daisy</a> function from package <a href="https://www.rdocumentation.org/packages/cluster/versions/2.0.7-1">cluster</a> we can easily calculate the dissimilarity matrix using Gower distance. Lets create a sample dataframe for our operation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8c5ea934e05847f33ba1d020d4ec240/href">https://medium.com/media/e8c5ea934e05847f33ba1d020d4ec240/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*SNdWcC3zpyEyWrc1qZRyyw.png" /><figcaption>Created Dataframe</figcaption></figure><p><strong>In the second step</strong> fromthe dataframe we can create the dissimilarity matrix from it using the daisy package.</p><pre>library(cluster)</pre><pre>gower.dissimilarity.mtrx &lt;- daisy(sample.data, metric = c(&quot;gower&quot;))</pre><p>This will give us dissimilarity matrix as follows</p><pre>Dissimilarities :<br>          1         2         3         4         5         6         7<br>2 0.3590238                                                            <br>3 0.6707398 0.6964303                                                  <br>4 0.3178742 0.3138769 0.6552807                                        <br>5 0.1687281 0.5236290 0.6728013 0.4824794                              <br>6 0.5262298 0.2006472 0.6969697 0.4810829 0.3575017                    <br>7 0.5969786 0.5472028 0.7404280 0.7481861 0.4323733 0.3478501          <br>8 0.4777876 0.6539635 0.8151941 0.3433228 0.3121036 0.4878362 0.5747661</pre><p>Lets save it in a csv file to use for later use.</p><pre>dissimilarity.mtrx.csv.content = as.matrix(gower.dissimilarity.mtrx)<br>write.table(dissimilarity.mtrx.csv.content,<br>            &#39;dissimilarity.mtrx.csv&#39;, <br>            row.names=FALSE, <br>            col.names=FALSE, <br>            sep=&quot;,&quot;)</pre><p><strong>Finally</strong> we have a dissimilarity matrix from gower distance that we can use in our next step.</p><p>Now as we have the dissimilarity matrix lets do clustering from it, for clustering we will use R’s <a href="https://en.wikipedia.org/wiki/K-medoids#Demonstration_of_PAM">PAM</a> (Partition Around Medoids) algorithm. And we define the size of the cluster by doing <a href="https://en.wikipedia.org/wiki/Silhouette_(clustering)">Silhouette analysis</a>.</p><pre>dist &lt;- gower.dissimilarity.mtrx<br>pamx &lt;- pam(dist, 3)<br>sil = silhouette (pamx$clustering, dist)<br>plot(sil)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JZ5nGSNJmajGCwjVheS7Iw.png" /><figcaption>Silhouette Analysis</figcaption></figure><pre>dist &lt;- gower.dissimilarity.mtrx<br>pamx &lt;- pam(dist, 4)<br>sil = silhouette (pamx$clustering, dist)<br>plot(sil)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oG5NGi_UUKUmagjg5SLdeQ.png" /></figure><p>Based on that we can choose 3 cluster as our cluster size.</p><p>Inspired from :</p><p><a href="https://medium.com/@anastasia.reusova/hierarchical-clustering-on-categorical-data-in-r-a27e578f2995">https://medium.com/@anastasia.reusova/hierarchical-clustering-on-categorical-data-in-r-a27e578f2995</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab89b3aa90d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>