<?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 Lukasz Przychodzien on Medium]]></title>
        <description><![CDATA[Stories by Lukasz Przychodzien on Medium]]></description>
        <link>https://medium.com/@lpprzychodzien_23366?source=rss-81045d4a276d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Lukasz Przychodzien on Medium</title>
            <link>https://medium.com/@lpprzychodzien_23366?source=rss-81045d4a276d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 01:38:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lpprzychodzien_23366/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[Predicting Titanic Survival Using PySpark in an AWS EMR]]></title>
            <link>https://medium.com/@lpprzychodzien_23366/predicting-titanic-survival-using-pyspark-in-an-aws-emr-8f308a09739d?source=rss-81045d4a276d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f308a09739d</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[random-forest]]></category>
            <category><![CDATA[aws-emr]]></category>
            <category><![CDATA[pyspark]]></category>
            <dc:creator><![CDATA[Lukasz Przychodzien]]></dc:creator>
            <pubDate>Tue, 12 Mar 2019 01:27:24 GMT</pubDate>
            <atom:updated>2019-03-12T01:27:24.810Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t-DEKilyY0qdhx2Yvv-qCw.jpeg" /></figure><h4>Learning PySpark is challenging, even when coming from Python, so I am sharing my insights gathered with this project.</h4><h3>Notes</h3><ul><li><em>Warning</em>: AWS use incurs monetary charges which you are responsible for.</li><li><em>Versions</em>: Spark 2.4.0, Zeppelin 0.8.0</li></ul><h3>AWS EMR Cluster</h3><p>I will not be providing detailed instructions on how to set up AWS as they have excellent documentation. I launched a new AWS EMR Cluster with Spark and Zepplin.</p><h3>Loading Data into EMR Cluster through S3</h3><p>We will first download the Titanic data set from: <a href="http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic.txt">http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic.txt</a></p><pre>curl -o titanic.txt  <a href="http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic.txt">http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic.txt</a></pre><p>Send the data to S3 storage via the terminal:</p><pre>aws s3 cp file.txt s3://my-bucket/</pre><p>Log into the EMR via your terminal:</p><pre>ssh -i /keypair.pem hadoop@***.compute.amazonaws.com</pre><p>You can view the current files on your Hadoop EMR with:</p><pre>hadoop fs -ls /</pre><p>I created a new folder on hadoop to store the data called “data”:</p><pre>hadoop fs -mkdir /data</pre><p>Now we can copy the data from your S3 bucket using DistCp (remember to define source first, then destination)</p><pre>hadoop distcp s3://my-bucket/file.csv /data</pre><p>Alternatively, you can import your data directly from your S3 bucket into Zepplin Notebook with:</p><pre>titanic = spark.read.csv(&#39;s3a://bucket-name/titanic.csv&#39;,header=True,inferSchema=True)</pre><h4>Zepplin Notebook</h4><p>To access the Zeppelin web interface, we need to set up an SSH tunnel to the master node (host the user interface) and a proxy connection. This is done by viewing cluster details and editing the “Security groups for Master”.</p><p>Create a new SSH rule with the source being your IP address. This will allow us to access the EMR through our terminal.</p><p>Create a custom TCP rule to an open inbound 88## port with the source being your IP on your master node security group. This will allow us to use Zepplin notebook to conduct our analysis.</p><h3>Loading Data into PySpark</h3><p>Initiate a new Spark Zepplin Notebook and initiate PySpark with:</p><pre>%pyspark</pre><p>Bring the Titanic data into a DataFrame:</p><pre>titanic = spark.read.csv(&#39;/data/titanic.csv&#39;,header=True,inferSchema=True)</pre><p>View your DataFrame schema with .printSchema() or the top 5 rows of your data using .show():</p><pre>titanic.printSchema()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*fyvz0AZS4ECF6hjxa9sUoQ.png" /></figure><pre>titanic.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*CwdCUqdIPE2C8lv-3kVlPg.png" /></figure><p>Look at the shape of your DataFrame (rows, columns) and it should be (1313, 11):</p><pre>print((titanic.count(), len(titanic.columns)))</pre><p>Clean up the column names by renaming them:</p><pre>titanic = titanic.withColumnRenamed(&quot;home.dest&quot;,&quot;homedest&quot;)<br>titanic = titanic.withColumnRenamed(&quot;row.names&quot;,&quot;rownames&quot;)</pre><p>Before we continue, import the module that contains the functions we will need:</p><pre>import pyspark.sql.functions as f</pre><h3>Impute Missing Values</h3><p>Imputing the missing values means not dropping observations, but replacing them. Therefore, any time you impute data you should add a new column to your data that shows a 1 or 0 according to whether a row was imputed or not.</p><p>First, we need to change the age column from a string type to an integer in order to use it in our machine learning algorithms:</p><pre>from pyspark.sql.types import IntegerType</pre><pre>titanic = titanic.withColumn(&quot;age&quot;, titanic[&quot;age&quot;].cast(IntegerType()))</pre><p>Find missing values by looping through all the columns and counting the number of Null values in each:</p><pre>for i in titanic.columns:<br>    print(i,titanic.where(f.col(i).isNull()).count())</pre><p>The data from columns room, ticket, and boat are largely missing so we will drop them from our data:</p><pre>titanic = titanic.drop(&#39;room&#39;,&#39;ticket&#39;,&#39;boat&#39;)</pre><h4>Impute Age Data</h4><p>Add a column called “ageImputed” where age data to be changed= 1:</p><pre>titanic = titanic.withColumn(&quot;ageImputed&quot;,f.when(f.col(&quot;age&quot;).isNull(),1).otherwise(0))</pre><p>We replace the missing age data with the mean age. This is one of many replacement options that we can use. First, we find the mean age of the ship’s passengers and then replace the Null values with it:</p><p>Note: collect() returns a python 2-dimensional list so we need [0][0] to get the value.</p><pre>meanage = titanic.select(f.mean(f.col(&#39;age&#39;))).collect()[0][0]</pre><pre>titanic = titanic.withColumn(&#39;age&#39;,f.when(f.col(&#39;age&#39;).isNull(),meanage).otherwise(titanic[&#39;age&#39;]))</pre><h4>Impute Embarked and Homedest Data</h4><p>We perform similar actions to impute the rest of the columns of interest, embarked and homedest, with the most common occurrence:</p><pre>titanic.groupby(&#39;homedest&#39;).count().sort(f.col(&quot;count&quot;).desc()).show()</pre><pre>titanic.groupby(&#39;embarked&#39;).count().sort(f.col(&quot;count&quot;).desc()).show()</pre><p>First, we create our impute tracking columns:</p><pre>titanic = titanic.withColumn(&quot;embarkedImputed&quot;,f.when(f.col(&quot;embarked&quot;).isNull(),1).otherwise(0))</pre><pre>titanic = titanic.withColumn(&quot;homedestImputed&quot;,f.when(f.col(&quot;homedest&quot;).isNull(),1).otherwise(0))</pre><p>The most common values are (embarked: Southampton, homedest: New York, NY), which we now use as missing value replacements:</p><pre>titanic = titanic.withColumn(&#39;embarked&#39;,f.when(f.col(&#39;embarked&#39;).isNull(),&#39;Southampton&#39;).otherwise(titanic[&#39;embarked&#39;]))</pre><pre>titanic = titanic.withColumn(&#39;homedest&#39;,f.when(f.col(&#39;homedest&#39;).isNull(),&#39;New York, NY&#39;).otherwise(titanic[&#39;homedest&#39;]))</pre><p>To use our feature, we convert it to an integer:</p><pre>from pyspark.ml.feature import StringIndexer</pre><pre>titanic = StringIndexer(inputCol=&#39;embarked&#39;,outputCol=&#39;embarked_index&#39;).fit(titanic).transform(titanic)</pre><pre>titanic = StringIndexer(inputCol=&#39;homedest&#39;,outputCol=&#39;homedest_index&#39;).fit(titanic).transform(titanic)</pre><p>Multiple unique values in our new index columns require us to separate them into binary columns with OneHotEncoder:</p><pre>from pyspark.ml.feature import OneHotEncoder</pre><pre>titanic = OneHotEncoder(inputCol=&quot;embarked_index&quot;, outputCol=&quot;embarkedVec&quot;).transform(titanic)</pre><pre>titanic = OneHotEncoder(inputCol=&quot;homedest_index&quot;, outputCol=&quot;homedestVec&quot;).transform(titanic)</pre><h3>Map Categorical Data</h3><h4>Mapping Pclass Data</h4><p>Convert the three classes of passengers to three binary columns:</p><pre>titanic = StringIndexer(inputCol=&#39;pclass&#39;,outputCol=&#39;pclass_index&#39;).fit(titanic).transform(titanic)</pre><pre>titanic = OneHotEncoder(inputCol=&quot;pclass_index&quot;, outputCol=&quot;pclassVec&quot;).transform(titanic)</pre><h4>Mapping Sex Data</h4><p>Use the StringIndexer again to change the sex data from “male” and “female” to a binary classifier :</p><pre>titanic = StringIndexer(inputCol=&#39;sex&#39;,outputCol=&#39;sex_index&#39;).fit(titanic).transform(titanic)</pre><h3>Random Forest Classifier</h3><p>In order to use our data in any machine learning algorithm, combine all input features into a single vector called ‘features’:</p><pre>from pyspark.ml.feature import VectorAssembler</pre><pre>df_assembler = VectorAssembler(inputCols=[&#39;pclassVec&#39;,&#39;age&#39;,&#39;ageImputed&#39;,&#39;embarkedVec&#39;,&#39;homedestVec&#39;,&#39;embarkedImputed&#39;,&#39;homedestImputed&#39;,&#39;sex_index&#39;], outputCol=&#39;features&#39;)</pre><pre>titanic = df_assembler.transform(titanic)</pre><pre>titanic.printSchema()</pre><p>Select only the new ‘features’ and ‘survived’ columns to create our final dataset to be modeled:</p><pre>model_titanic = titanic.select([&#39;features&#39;,&#39;survived&#39;])</pre><p>Split the database into training and testing datasets, which will allow us to evaluate the performance of our models:</p><pre>train_df,test_df = model_titanic.randomSplit([0.75,0.25])</pre><p>View our train_df and test_df to see if we have a close to fair split between people that did and did not survive:</p><pre>test_df.groupby(&#39;survived&#39;).count().show()</pre><p>Build and train a random forest model with the default parameters:</p><pre>from pyspark.ml.classification import RandomForestClassifier</pre><pre>rf_classifier=RandomForestClassifier(labelCol=&#39;survived&#39;).fit(train_df)</pre><p>Fit the test dataset to the trained model with:</p><pre>rf_predictions=rf_classifier.transform(test_df)</pre><p>Evaluate our model’s accuracy (close to the true value) and precision (close to each other):</p><pre>from pyspark.ml.evaluation import MulticlassClassificationEvaluator</pre><pre>print(&#39;Accuracy: &#39;, MulticlassClassificationEvaluator(labelCol=&#39;survived&#39;,metricName=&#39;accuracy&#39;).evaluate(rf_predictions))</pre><pre>print(&#39;Precision: &#39;,MulticlassClassificationEvaluator(labelCol=&#39;survived&#39;,metricName=&#39;weightedPrecision&#39;).evaluate(rf_predictions))</pre><p>The reported accuracy and precision are 0.745 and 0.774, respectively.</p><h4>Hyperparameter Tuning</h4><p>To find a better model, we perform hyperparameter tuning. Use a ParamGridBuilder to construct a grid of parameters to search over, which TrainValidationSplit will try all combinations of specified values and determine the best model using the evaluator. Definitions of the parameters can be found: <a href="https://spark.apache.org/docs/2.1.0/mllib-decision-tree.html">https://spark.apache.org/docs/2.1.0/mllib-decision-tree.html</a></p><pre>from pyspark.ml.tuning import ParamGridBuilder, TrainValidationSplit</pre><pre>rf_classifier2=RandomForestClassifier(labelCol=&#39;survived&#39;)</pre><pre>paramGrid = ParamGridBuilder()\<br>    .addGrid(rf_classifier2.maxDepth, [5, 10, 20]) \<br>    .addGrid(rf_classifier2.maxBins, [20, 32, 50]) \<br>    .addGrid(rf_classifier2.numTrees, [20, 50, 75]) \<br>    .addGrid(rf_classifier2.impurity, [&quot;gini&quot;, &quot;entropy&quot;]) \<br>    .addGrid(rf_classifier2.minInstancesPerNode, [1, 5, 10]) \<br>    .build()</pre><p>TrainValidationSplit requires an estimator, a set of estimator ParamMaps, and an evaluator. We set the validation ratio at 80% with 20%:</p><pre>tvs = TrainValidationSplit(estimator=rf_classifier2, estimatorParamMaps=paramGrid,evaluator=MulticlassClassificationEvaluator(labelCol=&#39;survived&#39;),trainRatio=0.8)</pre><pre>model2 = tvs.fit(train_df)<br>model2_predictions= model2.transform(test_df)</pre><p>Reassess how the new best-selected model performs:</p><pre>print(&#39;Accuracy: &#39;, MulticlassClassificationEvaluator(labelCol=&#39;survived&#39;,metricName=&#39;accuracy&#39;).evaluate(model2_predictions))</pre><pre>print(&#39;Precision: &#39;,MulticlassClassificationEvaluator(labelCol=&#39;survived&#39;,metricName=&#39;weightedPrecision&#39;).evaluate(model2_predictions))</pre><p>The best variant achieved accuracy and precision of 0.815 and 0.818, respectively. The best parameters were:</p><pre>model2.getEstimator().extractParamMap()</pre><pre>maxDepth = 5<br>maxBins = 32<br>numTrees = 20<br>impurity = gini <br>minInstancesPerNode = 1</pre><h3>Gradient Boosted Tree Classifier</h3><p>Work towards improving the random forest predictions using a gradient boosted tree classifier on the train/test split data:</p><pre>from pyspark.ml.classification import GBTClassifier</pre><pre>gbt_classifier = GBTClassifier(labelCol=&quot;survived&quot;, maxIter=10).fit(train_df)</pre><pre>gbt_predictions=gbt_classifier.transform(test_df)</pre><pre>print(&#39;Accuracy: &#39;, MulticlassClassificationEvaluator(labelCol=&#39;survived&#39;,metricName=&#39;accuracy&#39;).evaluate(gbt_predictions))</pre><pre>print(&#39;Precision: &#39;,MulticlassClassificationEvaluator(labelCol=&#39;survived&#39;,metricName=&#39;weightedPrecision&#39;).evaluate(gbt_predictions))</pre><p>The reported accuracy and precision are 0.854 and 0.852, respectively. This is already better than the previous random forest. We again perform some hyperparameter tuning to determine a better model:</p><pre>gbt_classifier2 = GBTClassifier(labelCol=&quot;survived&quot;)</pre><pre>paramGrid = ParamGridBuilder()\<br>    .addGrid(gbt_classifier2.maxDepth, [5, 10, 20]) \<br>    .addGrid(gbt_classifier2.maxBins, [20, 32, 50]) \<br>    .addGrid(gbt_classifier2.maxIter, [10, 20, 30]) \<br>    .addGrid(gbt_classifier2.minInstancesPerNode, [1, 5, 10]) \<br>    .build()<br>    <br>tvs = TrainValidationSplit(estimator=gbt_classifier2, estimatorParamMaps=paramGrid,evaluator=MulticlassClassificationEvaluator(labelCol=&#39;survived&#39;),trainRatio=0.8)</pre><pre>model2 = tvs.fit(train_df)<br>model2_predictions= model2.transform(test_df)</pre><pre>print(&#39;Accuracy: &#39;, MulticlassClassificationEvaluator(labelCol=&#39;survived&#39;,metricName=&#39;accuracy&#39;).evaluate(model2_predictions))</pre><pre>print(&#39;Precision: &#39;,MulticlassClassificationEvaluator(labelCol=&#39;survived&#39;,metricName=&#39;weightedPrecision&#39;).evaluate(model2_predictions))</pre><p>Even though it through ~21,000 model permutations, it was worse than our original model with the best accuracy and prediction of 0.854 and 0.850, respectively. The best parameters of the original model were:</p><pre>maxDepth:5<br>maxBins: 32<br>maxIter: 10 (the second model had this picked at 20)<br>minInstancesPerNode: 1</pre><p>Maximum predictive accuracy for the Titanic dataset is outside of the scope of this article. However, the Titanic dataset is well studied with better models available for review.</p><h3>Summary</h3><p>PySpark, with some practice, is fairly portable from a python background. Combine it with AWS EMR to make a powerful and easy way to manage your big data. I hope this document effectively introduced you to some of the data processing and analytics in PySpark that you were already familiar with in python.</p><p>Github: <a href="https://github.com/lprzychodzien/titanic-pyspark">https://github.com/lprzychodzien/titanic-pyspark</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f308a09739d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>