<?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 John Medina on Medium]]></title>
        <description><![CDATA[Stories by John Medina on Medium]]></description>
        <link>https://medium.com/@i.johnmedina?source=rss-f0b2a152ff60------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7dAHY-L_p9gxbZIWSnD-2Q@2x.jpeg</url>
            <title>Stories by John Medina on Medium</title>
            <link>https://medium.com/@i.johnmedina?source=rss-f0b2a152ff60------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 19:24:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@i.johnmedina/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[Capping off data science bootcamp]]></title>
            <link>https://medium.com/@i.johnmedina/capping-off-data-science-bootcamp-52a655fff26e?source=rss-f0b2a152ff60------2</link>
            <guid isPermaLink="false">https://medium.com/p/52a655fff26e</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-science-training]]></category>
            <dc:creator><![CDATA[John Medina]]></dc:creator>
            <pubDate>Wed, 12 Oct 2022 09:02:57 GMT</pubDate>
            <atom:updated>2022-10-12T09:02:57.000Z</atom:updated>
            <content:encoded><![CDATA[<p>Capstone project, next steps, and more…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zd_BKGQAUACesCRo" /><figcaption>Photo by <a href="https://unsplash.com/@disruptxn?utm_source=medium&amp;utm_medium=referral">Desola Lanre-Ologun</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Capstone: part 1</h3><p>As the bootcamp comes to close, we have been working steadily on our final project of the year: the capstone.</p><p>My peers have many great ideas and I’m looking forward to their presentations. A large segment of them appear to be working on image classification, which I’ve found really cool.</p><p>When I was developing ideas for the capstone project, I had 3 of them:</p><ul><li>Using economic data to identify the current economic environment and to predict the next economic environment.</li><li>Developing an AI model that writes essays based on a prompt, deployed as a web app. This isn’t one of my 3 initial ideas—it just sort of evolved into this.</li><li>Developing a model that continues to get “smarter” as it recommends music, also deployed as a web app. It gets its feedback from a survey of the 5 recommendations shown to users.</li></ul><p>I chose the first idea. Now as I write this, that idea has involved into a related but somewhat different idea: a prediction model based on whether economic data influences the movement of the S&amp;P 500.</p><p>A Google search on something like “<em>stock market prediction lstm</em>” reveals that a number of tutorials to build a simple model are available are available on the web. Some examples that I have come across are</p><p><a href="https://www.datacamp.com/tutorial/tutorial-for-recurrent-neural-network">https://www.datacamp.com/tutorial/tutorial-for-recurrent-neural-network/</a></p><p><a href="https://www.datacamp.com/tutorial/lstm-python-stock-market">https://www.datacamp.com/tutorial/lstm-python-stock-market/</a></p><p><a href="https://bobrupakroy.medium.com/uni-variate-lstm-time-series-forecasting-e8ad1cda71aa">Uni-Variate LSTM Time Series Forecasting</a></p><p>These last 2 articles raise a great question: are stock market prices possible to predict?</p><ul><li><a href="https://towardsdatascience.com/is-it-possible-to-predict-stock-prices-with-a-neural-network-d750af3de50b">Is it possible to predict stock prices with a neural network?</a></li><li><a href="https://towardsdatascience.com/what-happened-when-i-tried-market-prediction-with-machine-learning-4108610b3422">What Happened When I Tried Market Prediction With Machine Learning</a></li></ul><p>While I don’t envision myself solving that puzzle anytime soon, I aim in this project to explore what happens when we include data that’s related but enough to be different.</p><p>Most (if not all) of the articles I’ve seen on the web</p><ul><li>deal with a single stock (usually a company like FB).</li><li>strictly use time-series forecasting.</li><li>maybe utilize a technical indicator like a moving average (EMA, for example) based price and/or volume.</li></ul><p>I’m doing things a little differently by</p><ul><li>dealing with a stock market index.</li><li>performing regression analysis along with time-series.</li><li>utilizing economic data, like commodities, interest rates, and volatility.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*O-wJ8Iq6L8KXL66D" /><figcaption>Photo by <a href="https://unsplash.com/@nampoh?utm_source=medium&amp;utm_medium=referral">Maxim Hopman</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Economic and financial data sources</h4><p>One thing I like about economic and financial data is that they are abundant. And the data don’t require lots of preprocessing as they are (fairly) clean from the start.</p><p>Here are some data providers that I have been using in this project:</p><ul><li><a href="https://www.alphavantage.co/">Free Stock APIs in JSON &amp; Excel | Alpha Vantage</a></li><li><a href="https://fred.stlouisfed.org/">FRED Economic Data</a></li><li><a href="https://data.nasdaq.com/">Nasdaq Data Link</a></li></ul><p>Their APIs happen to be the easiest way to extract the data. All of the above have more-than-adequate documentation.</p><h4>Plan for the rest of the capstone</h4><p>I plan to complete the main portion of this project over the weekend so I’ll be detailing the rest in future posts.</p><p>My general plan right now is to run the data through different algorithms. At this point I’ve applied to my data:</p><ul><li>Random forest regressor</li><li>KMeans</li><li>Support vector regressor</li><li>XGBoost</li><li>feed forward neural network</li></ul><p>With the exception of KMeans, they all did quite well. Going forward, I’ll be exploring how these algos do with the data:</p><ul><li>Long short-term memory neural network</li><li>Gated recurrent unit</li><li>Prophet (by Facebook)</li><li>LightGBM (by Microsoft)</li></ul><h3>The next step(s)</h3><p>After this bootcamp, aside from the usual position hunting, the next step is to develop ideas like the ones mentioned near the beginning into projects. Cleaning up my bootcamp projects are on the list too.</p><p>I also plan to strengthen my coding challenge skills via codewars and the like. I’ve found that I really enjoy data science oriented coding and modeling with machine learning. So in the workforce I would definitely feel at home working along those lines.</p><h3>Last reflections on General Assembly DSI</h3><p>The easiest part of the Data Science Intensive was getting caught up in exploring the kinds of things we could do with Python.</p><p>The hardest part was waking up extra early (due to time difference) and pulling a few all-nighters to complete projects. The combo began to affect me right near the end of the instructional portion. And the coding challenges without resources were on the difficult side too.</p><p>I’ll admit that at times I wasn’t even sure I would make it through this bootcamp, especially with certain circumstances on my end.</p><p>But I’m grateful for this 12-week / 500-hour experience where I learned so much, made new friends, and had lots of fun in the process.</p><p>Enjoyed this post? Go ahead a give me a follow <a href="https://medium.com/@i.johnmedina">@i.johnmedina</a>. Thanks so much for reading! 🙏</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52a655fff26e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to optimize data science packages in Python for Apple Silicon M1/M2]]></title>
            <link>https://medium.com/@i.johnmedina/how-to-optimize-data-science-packages-in-python-for-apple-silicon-m1-m2-d659d53ecea8?source=rss-f0b2a152ff60------2</link>
            <guid isPermaLink="false">https://medium.com/p/d659d53ecea8</guid>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[macbook-pro]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[John Medina]]></dc:creator>
            <pubDate>Wed, 28 Sep 2022 12:03:52 GMT</pubDate>
            <atom:updated>2022-09-29T16:58:54.025Z</atom:updated>
            <content:encoded><![CDATA[<p>Installing GPU-utilizing TensorFlow, speeding up Numpy, and more…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EttxW6lm52OMBWpj" /><figcaption>Photo by <a href="https://unsplash.com/@oneor0?utm_source=medium&amp;utm_medium=referral">Dmitry Chernyshov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The latest <a href="https://www.apple.com/macbook-pro/">MacBook Pro line</a> powered by Apple Silicon M1 and M2 is an amazing package of performance and virtually all-day battery life.</p><p>For doing data science, such a combination is like having a dream come true—especially when the package includes an 8-core GPU and a 16-core Neural Engine.</p><p>Thankfully, we data scientists working with Python can optimize some packages for the GPU.</p><p>Before I show how to optimize Python for Apple Silicon Macs, let me share the story that started it.</p><h3>Quick story time</h3><p>Last week we were introduced to neural networks via the Tensorflow-Keras module. Our preparation began with installing the tensorflow package.</p><p>Most Windows and Intel Mac users had little trouble installing any of the TensorFlow packages. But it wasn’t so easy for us with Apple Silicon machines.</p><p>There are two flavors of TensorFlow: the CPU-only package and the package that enables one to take advantage of the GPU. Because the M-series processors were only recently launched in late 2020, there’s a lot of software that as of yet doesn’t take full advantage of the hardware, including the GPU.</p><p>The process to get TensorFlow to work with the GPU has a number of steps, which increases the chance of something going wrong along the way. Unfortunately, most of the M1/M2 users found this out.</p><p>So here’s a guide that will (hopefully) help you to find success installing a working TensorFlow GPU package on your Apple Silicon Mac machine.</p><h3>Use Miniconda or Miniforge</h3><p>Of those who experienced TensorFlow installation problems on the M1/M2, the common denominator appeared to be that they were using Anaconda. I personally use Miniforge, but in this post I tested the installation in a fresh Miniconda environment.</p><p>Whichever environment you use, the instructions are the exact same.</p><p>First things first: <strong>always</strong> test the installation in a fresh virtual environment.</p><pre>conda create -n tf_test pip python<br>conda activate tf_test</pre><p>This creates a new conda environment tf_test and installs pip and python.</p><p>Let’s make sure to set conda-forge as our default and primary channel. This is primarily for miniconda users but miniforge users can run the following commands, on the chance event that the channels were somehow changed.</p><pre>conda config --add channels conda-forge<br>conda config --set channel_priority strict</pre><p>The commands tell conda to always install from conda-forge, which is the same channel and only channel by default that miniforge uses. If conda cannot find any packages in the conda-forge channel then it will look in any other specified channels.</p><p>Now let’s update conda to use the latest packages:</p><pre>conda update --all</pre><p>Next we want to follow Apple’s instructions on <a href="https://developer.apple.com/metal/tensorflow-plugin/">installing the three TensorFlow packages</a>. The instructions are comprehensive and cover the entire process, including installing miniforge. Other specific scenarios not covered in this post are also provided.</p><p>The order is important so if you find yourself running into any trouble consult Apple’s documentation.</p><p>The three packages are to be installed in this order:</p><ol><li>TensorFlow dependencies (from Apple’s channel via conda)</li><li>The base TensorFlow package (via pip)</li><li>The tensorflow-metal plugin (via pip)</li></ol><pre>conda install -c apple tensorflow-deps<br>python -m pip install tensorflow-macos<br>python -m pip install tensorflow-metal</pre><p>That’s really all there is to installing the TensorFlow GPU package on an Apple Silicon machine.</p><p>You can verify your TensorFlow GPU installation by running the following from a terminal:</p><pre>python<br>import tensorflow as tf<br>tf.version.VERSION<br>tf.config.list_physical_devices(&#39;GPU&#39;)<br>exit()</pre><p>My computer returned version 2.10.0 and /physical_device:GPU:0 which indicates it detected my M1 GPU:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FklpJmc0I81zL1jXcJzFrg.png" /><figcaption>Terminal screenshot by author</figcaption></figure><h3>Speeding up Numpy (and others—maybe)</h3><p>While searching for ways to optimize Python with Apple M1/M2, I came across some search results that suggest that Numpy and perhaps Scipy and/or Scikit-learn can take advantage of Apple’s Accelerate (vecLib) framework to improve speeds.</p><p>This <a href="https://stackoverflow.com/questions/69848969/how-to-build-numpy-from-source-linked-to-apple-accelerate-framework">Stack Overflow post</a> and this <a href="https://www.reddit.com/r/Python/comments/qog8x3/if_you_are_using_apples_m1_macs_compiling_numpy/">Reddit post</a> describe how to build Numpy to utilize vecLib. There are other methods, like the one described <a href="https://github.com/conda-forge/numpy-feedstock/issues/253">here</a>.</p><p>The easiest way to enable Accelerate/vecLib is to install the Acclerate builds of libblas, or to reinstall libblas with the Acclerate builds, as per the <a href="https://conda-forge.org/docs/maintainer/knowledge_base.html#switching-blas-implementation">conda-forge documentation</a>.</p><pre>conda install &quot;libblas=*=*accelerate&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t2FFtOPEzY5pyw-J6p4sFQ.png" /><figcaption>Ignore that bottom message. This is definitely NOT a downgrade!</figcaption></figure><p>Now we can pin this implementation of libblas so that conda doesn’t try to switch us to another implementation.</p><p>All we have to do is create a file called <em>pinned</em> that contains our implementation of libblas that we’d like to keep. This requires that we know where the conda-meta<em> </em>directory exists in our environment directory, which can usually be found with a quick system search.</p><p>This next command will add <em>pinned</em> to the directory if it doesn’t already exists. Or, if it does, the command will append our libblas version to it.</p><pre># uses my path; yours might be different</pre><pre>echo &quot;libblas=*=*accelerate&quot; &gt;&gt; ~/miniconda3/envs/tf_test/conda-meta/pinned</pre><p>Conda will now present to us only the libblas package with the Accelerate/vecLib implementation.</p><p>This <a href="https://stackoverflow.com/questions/70240506/why-python-native-on-m1-max-is-greatly-slower-than-python-on-old-intel-i5">discussion on Stack Overflow</a> has some code for benchmarking your Numpy performance. Additionally, it has some methods for enabling Numpy and Accelerate.</p><p>Using the first benchmarking code, my M1 turned out a mean of 1.20 seconds over 10 runs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PcPvt0BR8Gx832JsrXLIVg.png" /><figcaption>Results for Numpy benchmark on Apple M1 by author</figcaption></figure><p>Basically, any result in the ballpark of an average of 1 second indicates an accelerated Numpy.</p><h3>PyTorch and the M1/M2</h3><p>Lastly, I’ll just mention quickly that the folks at <a href="https://pytorch.org/blog/introducing-accelerated-pytorch-training-on-mac/">PyTorch announced</a> that PyTorch v1.12 would leverage the Apple Silicon GPU in its machine learning model training.</p><p>PyTorch is now on v1.12.1 and it certainly appears to be utilizing the M1/M2 framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KnhU9WgBzBgHKpCvMYvb6Q.png" /><figcaption>PyTorch v1.12 release notes @ <a href="https://github.com/pytorch/pytorch/releases/tag/v1.12.0">https://github.com/pytorch/pytorch/releases/tag/v1.12.0</a></figcaption></figure><p>Enjoyed this post? Go ahead a give me a follow <a href="https://medium.com/@i.johnmedina">@i.johnmedina</a>. Thanks so much for reading! 🙏</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d659d53ecea8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bring Your Own Data]]></title>
            <link>https://medium.com/@i.johnmedina/bring-your-own-data-aba3fe76a503?source=rss-f0b2a152ff60------2</link>
            <guid isPermaLink="false">https://medium.com/p/aba3fe76a503</guid>
            <category><![CDATA[data-scraping]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[John Medina]]></dc:creator>
            <pubDate>Wed, 14 Sep 2022 08:44:59 GMT</pubDate>
            <atom:updated>2022-09-14T08:44:59.605Z</atom:updated>
            <content:encoded><![CDATA[<p>BYOD: a Reddit scrape experience</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MPQvRwTaa0fhdLrI" /><figcaption>Photo by <a href="https://unsplash.com/@firmbee?utm_source=medium&amp;utm_medium=referral">Firmbee.com</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Tools utilized</h4><p>In this post, I’m covering the scraping stage of a recent project that I completed on the hottest Reddit threads. The goal was to determine the components of an interactive Reddit post using natural language processing (NL).</p><p>I set out to capture and explore the following data:</p><ul><li>Reddit thread titles</li><li>Subreddit of each thread</li><li>Number of comments on each thread</li><li>Time elapsed between posting and collection</li><li>At least 10,000 threads</li></ul><p>To do this, I needed to develop a way to obtain the data in a quick and efficient manner. Some options I came across were <a href="https://github.com/praw-dev/praw">PRAW</a> and <a href="https://pushshift.io/">pushshift.io</a>, along with a few lesser known methods.</p><p>I chose to extract the Reddit data using a combination of <a href="https://github.com/SeleniumHQ/Selenium">Selenium</a> and <a href="https://www.crummy.com/software/BeautifulSoup/">Beautiful Soup</a> to explore the html structure, and then Selenium to do the extraction itself—and fully automated. It took a few attempts to get it right, but I finally succeeded.</p><h4>The first attempt</h4><p>The first attempt was on the <a href="http://www.reddit.com/hot">www.reddit.com/hot</a> page. The structure itself wasn’t too complicated, with all the needed data nested in the usual containers and elements.</p><p>Here was the first version of the code:</p><pre># importing modules<br>import pandas as pd<br>from bs4 import BeautifulSoup<br>import requests<br>from time import sleep</pre><pre>from selenium import webdriver<br>from selenium.webdriver.firefox.service import Service<br>from selenium.webdriver.chrome.service import Service</pre><pre># launch the Selenium webdriver<br>ser = Service(&#39;webdrivers/chromedriver&#39;)<br>op = webdriver.ChromeOptions()<br>driver = webdriver.Chrome(service=ser, options=op)</pre><p>If all goes well then an empty instance of Chrome should appear.</p><pre># set the url<br>url = &#39;<a href="https://www.reddit.com/hot/&#39;">https://www.reddit.com/hot/&#39;</a></pre><pre># get url with selenium<br>driver=webdriver.Chrome(service=ser)<br>driver.get(url)</pre><pre># allow time for page to load completely<br>sleep(10)</pre><pre># execute javascript to emulate scrolling to bottom of page<br>driver.execute_script(&quot;&quot;&quot;window.scrollBy({ <br>  top: document.body.scrollHeight,<br>  left: 0, <br>  behavior: &#39;smooth&#39; <br>});&quot;&quot;&quot;)</pre><pre># allow time for page to load and to capture html<br>sleep(10)</pre><pre># assign page source of capture to variable<br>html = driver.page_source</pre><pre># close Chrome<br>driver.close()</pre><pre># parse page source with BS4 using the lxml parser<br># assign to parsed data to variable soup<br>soup = BeautifulSoup(html, &#39;lxml&#39;)</pre><p>The first run was a success. Now, the next step is to capture more than one pageful of html.</p><h4>The 2nd attempt</h4><p>My initial thought was to execute the javascript portion twice: the second run would happen after the second sleep command.</p><p>It would look like this:</p><pre>...<br># get url with selenium<br>driver=webdriver.Chrome(service=ser)<br>driver.get(url)</pre><pre># allow time for page to load completely<br>sleep(10)</pre><pre># emulate scrolling to bottom of page - 1st time<br>driver.execute_script(&quot;&quot;&quot;window.scrollBy({ <br>  top: document.body.scrollHeight,<br>  left: 0, <br>  behavior: &#39;smooth&#39; <br>});&quot;&quot;&quot;)</pre><pre># allow time for page to load and to capture html<br>sleep(10)</pre><pre># emulate scrolling to bottom of page - 2nd time<br>driver.execute_script(&quot;&quot;&quot;window.scrollBy({ <br>  top: document.body.scrollHeight,<br>  left: 0, <br>  behavior: &#39;smooth&#39; <br>});&quot;&quot;&quot;)</pre><pre># allow time for page to load and to capture html<br>sleep(10)<br>...</pre><p>The code worked as intended. But I was still left with a number of problems.</p><ol><li>How many times would I need to run driver.execute_script?</li><li>How much could the code reliably capture over anywhere from 10 to 50 pages at a time?</li><li>How long do I need to sit and oversee the operation and make sure that it goes smoothly?</li></ol><p>The answer to all 3 of those questions was <em>I don’t know</em>. But the answer had to do with what I found out trying to solve problem #2.</p><p>Whenever I captured a page or more, I’d then run the following code to check how successful the capture was:</p><pre># check length of capture<br>len(html)</pre><pre># display the first 1000 characters of the capture<br>html[:1000]</pre><p>The outputs looked something like this, in the order respectively to the code above:</p><pre># output to len(html)<br>1708067</pre><pre># output to html[:1000]<br>&#39;&lt;html lang=&quot;en-US&quot;&gt;&lt;head&gt;\n        &lt;script&gt;\n    var __SUPPORTS_TIMING_API = typeof performance === \&#39;object\&#39; &amp;&amp; !!performance.mark &amp;&amp; !! performance.measure &amp;&amp; !!performance.getEntriesByType;\n    function __perfMark(name) { __SUPPORTS_TIMING_API &amp;&amp; performance.mark(name); };\n    var __firstPostLoaded = false;\n    function __markFirstPostVisible() {\n      if (__firstPostLoaded) { return; }\n      __firstPostLoaded = true;\n      __perfMark(&quot;first_post_title_image_loaded&quot;);\n    }\n    var __firstCommentLoaded = false;\n    function __markFirstCommentVisible() {\n      if (__firstCommentLoaded) { return; }\n      __firstCommentLoaded = true;\n      __perfMark(&quot;first_comment_loaded&quot;);\n    }\n  &lt;/script&gt;\n        &lt;script&gt;__perfMark(\&#39;head_tag_start\&#39;);&lt;/script&gt;\n        &lt;meta charset=&quot;utf-8&quot;&gt;\n        &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;\n        &lt;meta name=&quot;referrer&quot; content=&quot;origin-when-cross-origin&quot;&gt;\n        &lt;style&gt;\n  /* <a href="http://meyerweb.com/eric/tools/css/reset//n">http://meyerweb.com/eric/tools/css/reset/\n</a>    v2.0 &#39;</pre><p>So far so good. Now of course the text that I needed would be intermingled with the html code, so the next step is to separate text from html and save into variables.</p><p>Time to grab thread titles:</p><pre># extract text of titles from html<br>titles = [t.text.split(&#39;,&#39;)[0] for t in soup.find_all(&#39;h3&#39;, {&#39;class&#39;: &#39;_eYtD2XCVieq6emjKBH3m&#39;}) if &#39;u/&#39; not in soup.find_all(&#39;div&#39;, {&#39;data-adclicklocation&#39;: &#39;top_bar&#39;})]</pre><p>Grabbing subreddits:</p><pre># extract text of subreddit names<br>subreddits = [s.text for s in soup.find_all(&#39;div&#39;, {&#39;class&#39;: &#39;_2mHuuvyV9doV3zwbZPtIPG&#39;}) if &#39;r/&#39; in s.text]</pre><p>Here are the number of comments for each thread:</p><pre># extract the number of comments<br>comments = [c.text.strip() for c in soup.find_all(&#39;span&#39;, {&#39;class&#39;: &#39;FHCV02u6Cp2zYL0fhQPsO&#39;})]</pre><p>Finally, amount of time between thread post and scrape:</p><pre># getting time (hours/minutes) ago<br>times = [t.text for t in soup.find_all(&#39;span&#39;, {&#39;data-testid&#39;: &#39;post_timestamp&#39;})]</pre><p>And as I displayed the results of the titles, subreddits, comments, and elapsed times, I felt a sense of satisfaction.</p><p>That is, until I ran this code:</p><pre># getting the quantities of each list<br>len(titles), len(subreddits), len(comments), len(times)</pre><p>To my horror, they were different lengths mostly!</p><h4>Making progress</h4><p>I began to search for ideas on improve my scraping technique.</p><p>Over at the <a href="https://page2api.hashnode.dev/how-to-scrape-reddit-data-posts-images-comments-and-more">Page2API Blog</a>, I discovered that the old Reddit format was still available.</p><p>The advantage here was that the html structure was uniform. And it used normal, readable attribute names for &lt;div&gt;, &lt;class&gt;, and everything else, not names appearing to be a randomized set of characters.</p><p>Another advantage to the old format was that it did not utilize infinite scrolling like the current Reddit website does. Instead, pages can be navigated using prev/next buttons at the bottom of the page.</p><p>So the first modification was to change the url:</p><pre># old url<br>url = &#39;https://www.reddit.com/hot&#39;</pre><pre># new url<br>url = &#39;https://old.reddit.com/hot&#39;</pre><p>The second idea was to create lists of titles, subreddits, comments, and elapsed time in real-time as scraping happened, and at the same time taking advantage of the benefits of the old format.</p><p>Thanks to the accepted answer to <a href="https://stackoverflow.com/questions/53955988/how-to-move-to-the-next-page-on-python-selenium">“How to move to the next page on Python Selenium?” at stackoverflow.com</a>, I was able to tackle the problems I faced in the beginning.</p><p>Implementing everything into one block:</p><pre># additional imports<br>from selenium.webdriver.common.by import By<br>from selenium.webdriver.support.ui import WebDriverWait<br>from selenium.webdriver.support import expected_conditions as EC<br>from selenium.common.exceptions import TimeoutException, WebDriverException<br>...</pre><pre>driver.get(url)</pre><pre>sleep(10)</pre><pre>headlines = []<br>subreddits = []<br>times = []<br>comments = []</pre><pre>while True:<br>    try:<br>        driver.execute_script(&quot;return \<br>        arguments[0].scrollIntoView(true);&quot;, \<br>        WebDriverWait(driver,20). \<br>        until(EC.element_to_be_clickable((By.XPATH, \<br>        &quot;//li[@class=&#39;arrow__right&#39;]/a&quot;)))) </pre><pre>        driver.find_element_by_xpath( \<br>        &quot;//li[@class=&#39;arrow__right&#39;]/a&quot;).click()</pre><pre>        print(&quot;Navigating to Next Page&quot;)<br>    except (TimeoutException, WebDriverException) as e:<br>        print(&quot;Last page reached&quot;)<br>        break</pre><pre>        html = driver.page_source<br>        souppy = BeautifulSoup(html, &#39;lxml&#39;)</pre><pre>        for lines in souppy.find_all(&#39;a&#39;, {&#39;class&#39;: &#39;title&#39;}):<br>            headlines.append(lines.text)<br>        for lines in souppy.find_all(&#39;a&#39;, {&#39;class&#39;: &#39;subreddit&#39;}):<br>            subreddits.append(lines.text)<br>        for lines in souppy.find_all(&#39;time&#39;, {&#39;class&#39;: &#39;live-timestamp&#39;}):<br>            times.append(lines.text)<br>        for lines in souppy.find_all(&#39;li&#39;, {&#39;class&#39;: &#39;first&#39;}):<br>            comments.append(lines.text)</pre><pre>        driver.find_element_by_xpath( \<br>        &quot;//li[@class=&#39;arrow__right&#39;]/a&quot;).click()<br>        print(&quot;Navigating to Next Page&quot;)<br>    except (TimeoutException, WebDriverException) as e:<br>        print(&quot;Last page reached&quot;)<br>        break</pre><pre>...</pre><p>Now that the bulk of the code that will do the heavy lifting was in place, there were just a few modifications and refinements to do.</p><h4>The final code</h4><p>The final workflow would look like this:</p><ul><li>call up old.reddit.com in Chrome</li><li>set sleep time between 2–5 seconds to allow time for page to load (<em>modified</em>)</li><li>utilize while/try/except loop to scrape data (<em>modified</em>)</li><li>browser scrolls entire page to capture entire html</li><li>sleep time between 5–10 seconds (<em>added</em>)</li><li>iterates through current page and pulls:</li><li>headlines</li><li>subreddits</li><li>comments</li><li>times</li><li>advances to next page (<em>modified</em>)</li><li>sleep time between 5–10 seconds (<em>added</em>)</li><li>repeat until timeout or last page</li><li>sleep time 2–5 seconds for any background processes to finish (<em>added</em>)</li><li>close/quit Chrome</li></ul><p>In its final form it looks like this:</p><pre># import libraries and modules</pre><pre>import pandas as pd<br>from bs4 import BeautifulSoup<br>import requests<br>from time import sleep</pre><pre>import random</pre><pre>from selenium import webdriver<br>from selenium.webdriver.chrome.service import Service</pre><pre>from selenium.webdriver.common.by import By<br>from selenium.webdriver.support.ui import WebDriverWait<br>from selenium.webdriver.support import expected_conditions as EC<br>from selenium.common.exceptions import TimeoutException, WebDriverException</pre><pre># set selenium options for Chrome</pre><pre>ser = Service(&#39;webdrivers/chromedriver&#39;)<br>op = webdriver.ChromeOptions()<br>op.add_argument(&quot;--headless&quot;)<br>op.add_argument(&quot;--window-size=1920x1080&quot;)</pre><pre># set url to old Reddit format</pre><pre>url = &#39;<a href="https://old.reddit.com/hot/&#39;">https://old.reddit.com/hot/&#39;</a></pre><pre># call Chrome to get url</pre><pre>driver=webdriver.Chrome(service=ser, options=op)<br>driver.get(url)</pre><pre># sleep between 2-5 seconds to allow time for page load</pre><pre>sleep(random.randint(2, 5))</pre><pre># create lists for data</pre><pre>headlines = []<br>subreddits = []<br>times = []<br>comments = []</pre><pre># while loop to automate scrape</pre><pre>while True:<br>    try:</pre><pre>        # javascript for page scroll left untouched</pre><pre>        driver.execute_script(&quot;&quot;&quot;window.scrollBy({ <br>        top: document.body.scrollHeight, left: 0,<br>        behavior: &#39;smooth&#39; });&quot;&quot;&quot;)</pre><pre>        # sleep between 5-10 seconds</pre><pre>        sleep(random.randint(5, 10))</pre><pre>        # assign extracted page source data to variable<br>        # assign Beautiful Soup parsing to variable</pre><pre>        html = driver.page_source<br>        souppy = BeautifulSoup(html, &#39;lxml&#39;)</pre><pre>        # extracted needed data - notice class names are normal!</pre><pre>        for lines in souppy.find_all(&#39;a&#39;, {&#39;class&#39;: &#39;title&#39;}):<br>            try:<br>                headlines.append(lines.text)<br>            except:<br>                headlines.append(&#39;&#39;)<br>        for lines in souppy.find_all(&#39;a&#39;, {&#39;class&#39;: &#39;subreddit&#39;}):<br>            try:<br>                subreddits.append(lines.text)<br>            except:<br>                subreddits.append(&#39;&#39;)<br>        for lines in souppy.find_all(&#39;time&#39;, {&#39;class&#39;: &#39;live-timestamp&#39;}):<br>            try:<br>                times.append(lines.text)<br>            except:<br>                times.append(None)<br>        for lines in souppy.find_all(&#39;li&#39;, {&#39;class&#39;: &#39;first&#39;}):<br>            try:<br>                comments.append(lines.text)<br>            except:<br>                comments.append(None)</pre><pre>        # utilize .click() method to advance to next page<br>        # inform page scrape is complete</pre><pre>        driver.find_element(By.CLASS_NAME, &#39;next-button&#39;).click()<br>        print(&#39;Navigating to Next Page&#39;)</pre><pre>        # sleep between 5-10 seconds</pre><pre>        sleep(random.randint(5, 10))</pre><pre>    # alert when scrape ends</pre><pre>    except (TimeoutException, WebDriverException) as e:<br>        print(&quot;Last page reached&quot;)<br>        break</pre><pre># sleep for 2-5 seconds</pre><pre>sleep(random.randint(2, 5))</pre><pre># close/quit Chrome</pre><pre>driver.close()</pre><p>Now when I ran len() on each list, they were completely even, with rare occasion that times would be missing a couple of values.</p><p>When all was said and done, I had scraped about 23k posts over 2–3 days.</p><p>Enjoyed this post? Go ahead a give me a follow <a href="https://medium.com/@i.johnmedina">@i.johnmedina</a>. Thanks so much for reading! 🙏</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aba3fe76a503" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Where I’m at now in my data science journey]]></title>
            <link>https://medium.com/@i.johnmedina/where-im-at-now-in-my-data-science-journey-4d0121674842?source=rss-f0b2a152ff60------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d0121674842</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science-training]]></category>
            <dc:creator><![CDATA[John Medina]]></dc:creator>
            <pubDate>Wed, 31 Aug 2022 04:42:18 GMT</pubDate>
            <atom:updated>2022-08-31T04:42:18.687Z</atom:updated>
            <content:encoded><![CDATA[<p>Sharings on the halfway point of General Assembly’s Data Science Intensive</p><figure><img alt="Visual of an audio file, representing a timeline in this post" src="https://cdn-images-1.medium.com/max/1024/0*OI_Ii8dJ_Lw_km6e" /><figcaption>Photo by <a href="https://unsplash.com/@peter_s?utm_source=medium&amp;utm_medium=referral">Peter Stumpf</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In a previous post, I wrote about <a href="https://medium.com/@i.johnmedina/a-journey-into-data-science-12047d84475c">my journey into data science</a> and analytics and how my journey led me to coding bootcamp at General Assembly.</p><p>Nearing the halfway point of the program, we have covered vast amount of territory. As of this writing, I have completed:</p><ul><li>38 class modules</li><li>13 labs (in-depth application of class material)</li><li>2 major projects</li><li>3rd major project in progress</li></ul><p>Thus far into the program, I’ve gained experience or added to it in</p><ul><li>base Python</li><li>git and GitHub</li><li>Markdown (somewhat)</li><li>LaTeX (somewhat)</li><li>Jupyter</li><li>probability and statistics</li><li>readying data for analysis</li><li>data exploration</li><li>data visualisation</li><li>data scraping</li><li>data modeling with machine learning</li><li>natural language processing</li></ul><p>It’s been loads of fun learning to use tools of the trade like:</p><ul><li>NumPy</li><li>pandas</li><li>Matplotlib</li><li>Beautiful Soup</li><li>scikit-learn</li><li>JupyterLab</li><li>conda / pip</li></ul><p>Needless to say, that’s a lot to cover in the span of weeks. But the constant engagement with the material, concepts, and code—along with the awesome instructors—has been nothing but challenging, pushing me to grow, meaningful, and humbling.</p><h3>What I’ve been learning</h3><p>Most of what I’ve learned has been in the form of the Python programming language. This makes sense because ideas, concepts, and reasoning must be translated into code.</p><p>The following is a cheat sheet of sorts of my most commonly used or favorite commands, operations, and/or code bits. These are what I’ve learned early on in the course and continue to use today.</p><h4>Base Python</h4><h4>Iterables, loops, and comprehensions</h4><p>One coding structure that is used with some regularity is operating on iterables (e.g., lists) with for loops and, if needed,if/elif/else statements. The structure looks like so:</p><pre># regular plain for loop<br>for item in iterable:<br>    do this</pre><pre># plain for loop with if/elif/else filtering<br>for item in iterable:<br>    if item == Something:<br>        do this<br>    else:<br>        this instead</pre><p>Let’s say that we had a list numbers consisting of 1–10. From this list, we want to create a list of odd numbers. We can use the basic loop with conditional filtering.</p><pre>numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]</pre><pre># create new list of odd numbers from list numbers</pre><pre>odd_numbers = []<br>for num in numbers:<br>    if num % 2 != 0:<br>        odd_numbers.append(num)</pre><pre>print(odd_numbers)</pre><p>The output is</p><pre>[1, 3, 5, 7, 9]</pre><p>Now this can be rewritten in a more concise way as a list comprehension. Here is the general form:</p><pre># list comprehension<br>[do_this for item in iterable]</pre><pre># list comprehension with filtering<br>[do_this for item in iterable if item == Something]</pre><pre># list comprehension with if/else<br>[do_this if item == Something else this_instead if item != Something for item in numbers]</pre><p>Now, to rewrite the odd_numbers list as a comprehension looks like this:</p><pre>numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]</pre><pre># create new list odd_numbers as a comprehension</pre><pre>odd_numbers = [num for num in numbers if num % 2 != 0]<br>print(odd_numbers)</pre><p>And we get the same output:</p><pre>[1, 3, 5, 7, 9]</pre><p>That’s essentially 1 line of code (not including print()) to get the same result. Talk about efficiency!</p><h4>Strings</h4><h4>Operations</h4><p>The strings data type has many operations that can be performed on it. My most used operations are</p><ul><li>str.lower() lowercases all characters in the string</li><li>str.strip() removes extra whitespace around the string</li><li>str.split(x) breaks string apart at x (punctuation, space, word, etc.) and returns a list with each element</li></ul><p>The str above represents the string, which is enclosed in quotation marks.</p><h4>Dictionaries</h4><h4>A speedy form of a list</h4><p>I’ve come to appreciate dictionary data type in Python. At first I couldn’t see the use for them because there was already the list data type.</p><p>The way I think of the dictionary is it’s like a map in the form of {key:value} pairs. The key is essentially a label for the value and is used to retrieve the value.</p><p>Using a dictionary also appears to be quicker than using a list, for reasons I have forgotten. I think of dictionary as being “hardcoded” because of the key, whereas Python usually has to iterate through the list to find the value.</p><p>My most used dictionary operations are</p><ul><li>dict.items() returns a list of pairs in the form [(key, value)]</li></ul><h4>Bonus</h4><p>In some development environment (usually abbreviated IDE) software, there’s a little trick to pull up all of the operations that can be performed on the current data type. In JupyterLab it looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JRkzhi-3YhJbgAe1M1K4KQ.png" /><figcaption>JupterLab with python lsp showing possible operations on a string</figcaption></figure><p>This is accessible in both JupyterLab and Notebook by putting a period (“.”) immediately after the data type and pressing the Tab key.</p><p>Other IDEs might have a similar function or capability, although some setup could be required. In VS Code, the <a href="https://marketplace.visualstudio.com/items?itemName=ms-python.vscode-pylance">Pylance extension</a> provides this feature. Sometimes this feature is referred to as a <em>python language server</em> (lsp).</p><p>Early in the bootcamp, I made heavy use of thelsp to avoid having to Google how-to guides and documentation. It was both a life- and time-saver!</p><h4>Non-technological learnings</h4><p>Aside from the coding, other areas that I’ve been or am being schooled in are</p><ul><li>time management</li><li>higher mathematics</li><li>how to function with less sleep</li></ul><p>Time management is, of course, super important, especially when there are obligations (a.k.a. life) outside of data science bootcamp. And because this is an intensive course, time management is even more crucial to meeting all obligations.</p><p>Higher mathematics has become more interesting to me because of this course. Math has always been a favorite subject of mine, even though it’s not my strongest area. In high school and college, I did pre-calculus but never went further so there are still gaps to fill in. In addition to math is a renewed interest in physics that I hope I can eventually learn on the side.</p><p>Functioning with less sleep is unfortunately not a sign of successful time management. It’s either sleeping late or getting up few hours before class—and sometimes both. I’ve tried to curb the late sleeping in favor of arising early, but sometimes the candle has burned on both ends.</p><p>Lastly, I’m learning about (or living) the saying <em>good enough is good enough</em>. I’ve been learning to simply gain a working knowledge of the material for the day and week, rather than attempting to gain an in-depth savviness. By staying engaged and putting in the work each day, I have the power of compounding at work for me.</p><h3>What’s in store for the next half</h3><p>So the next half of the course looks exciting. We’ll be moving into more advanced modeling tools, which I assume would be some of those words that I’ve heard thrown around already like <em>XGBoost</em> and <em>neural networks</em>. I even recall seeing <em>tensorflow</em> when I first read the course syllabus.</p><p>When I was surfing around earlier for “advanced machine learning,” I came across a few technical papers and journal articles. As I read bits here and there, I noticed how well I understood much of what I was reading.</p><p>Prior to this course, I would have had no idea really what I was reading in a published article on machine learning. But thanks to the quality education and super helpful support from instructors and teaching aides, I’m becoming fluent in the field of data science and analytics. Talk about the power of compounding!</p><p>I’m confident that at the end of the course, I’ll have the kind of knowledge and skills to be enter the field and help make a positive impact on the world.</p><h3>The plan post course</h3><p>The other appealing part of this program is the career coaching. At the most basic level, it’s like getting a peek into the minds of recruiters and hiring departments.</p><p>We are currently working on developing our brand statement, resumé, and LinkedIn profile. Right now it’s in skeleton form with all the essentials. In coming weeks, we’ll be fleshing out everything.</p><p>Post course completion, first on my agenda is to get an entry-level data scientist/analyst/engineer with a great company and team. I’m aiming for around $100k, give or take a few thousand.</p><p>I love coding and working with data, so ideally I’d be exploring data, readying it for analysis, and analysing.</p><p>During the position search, I’ll be focusing on coding challenges on platforms like <a href="https://www.codewars.com/">Codewars</a>, <a href="https://www.hackerrank.com/">HackerRank</a>, and<a href="https://leetcode.com/"> Leetcode</a>.</p><p>Enjoyed this post? Go ahead a give me a follow <a href="https://medium.com/@i.johnmedina">@i.johnmedina</a>. Thanks so much for reading! 🙏</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d0121674842" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What’s the deal with data cleaning?]]></title>
            <link>https://medium.com/@i.johnmedina/whats-the-deal-with-data-cleaning-141688974024?source=rss-f0b2a152ff60------2</link>
            <guid isPermaLink="false">https://medium.com/p/141688974024</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[data-cleaning]]></category>
            <dc:creator><![CDATA[John Medina]]></dc:creator>
            <pubDate>Wed, 17 Aug 2022 06:38:54 GMT</pubDate>
            <atom:updated>2022-09-28T20:59:32.242Z</atom:updated>
            <content:encoded><![CDATA[<h4>My quick data cleaning process</h4><p>In the world of data science and analytics, data is everything (no surprise there!). But not all data is created equal. There is the raw data itself, and then there is the quality of data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-ZNznEKo6S2XDDdi" /><figcaption>Photo by <a href="https://unsplash.com/@z734923105?utm_source=medium&amp;utm_medium=referral">Jerry Zhang</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Raw data comes to us generally unfiltered. It might help to think of raw data as water coming from the mountains. In the spring time and into the summer, the snow melts, and as it does the amount of melted snow becomes enough to flow as a stream or even a river.</p><p>The water sourced from the snow is unfiltered. It might be clean from the start or it might contain impurities. Similarly, raw data might be clean from the start or it might contain impurities in the form of messed up values.</p><p>As the snow journeys down from the mountains, it flows over different kinds of terrain: soil, plants, rocks, etc. All these terrains serve to filter the water as it flows over and through them. In general, as the melted snow water flows longer distances over many terrain types, its impurities get left behind, filtered by terrain, and the water becomes cleaner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*toc8kI0z6rd-0PO80XAvAg.jpeg" /></figure><p>Finally, some of the water continues on where it eventually makes its way to the ocean. And some of the water makes it to a reservoir where it gets stored until it goes through the final processing to make sure it is drinkable. Aside from finding its way to a reservoir, the water might also path straight to a water treatment facility.</p><p>The treatment facility cleans the water using a variety of methods, and then stores it for use by a municipality that the facility serves.</p><p>Clean, high-quality data goes through a journey not unlike water from the mountains. The data begins raw and unfiltered. It then comes to the data scientist who begins to clean it and improve its quality.</p><p>The process is called cleaning the data.</p><h3>Data Cleaning Process</h3><p>There are probably as many ways to clean data as there are data scientists. Everybody has their favorite tools that they use to clean up the data. Despite the varied methods and personal preferences, common among them are principles that guide the process.</p><p>From a high level view, the common process looks something like this:</p><ol><li><strong>Standardize column names/headers.</strong></li><li><strong>Discover the data types of each column.</strong></li><li><strong>Look for null/empty values and decide how to handle them.</strong></li><li><strong>Look for columns where the data types differ from expectations and convert the data types.</strong></li><li><strong>Convert columns with binary entries (e.g., yes/no, male/female, etc.) into numerical values (0s/1s).</strong></li><li><strong>Check summary statistics for values that appear odd or unusual.</strong></li><li><strong>Visualize the data.</strong></li></ol><p>Below is a quick run through using the <a href="https://www.kaggle.com/competitions/titanic/data?select=test.csv">titanic dataset</a> from <a href="https://www.kaggle.com/">Kaggle.com</a>. You will need to sign up for an account in order to downline the csv file.</p><p>First things first: load up packages and modules.</p><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt</pre><p>Now time to import the dataset as a pandas data frame. I have it stored in my current directory. The imported data is assigned to variable df.</p><pre>df = pd.read_csv(‘test.csv’)</pre><p>Let’s get a snapshot of what the data looks like with the .head() method. As an alternative or even in conjunction, we can use .tail() to examine the last 5 rows of the set.</p><pre>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X0K16zipxY8xuj6Ae5m9lQ.png" /><figcaption>`df.head()` output by author</figcaption></figure><h4>1. Standardize columns</h4><p>Just to be sure that we see all the columns displayed are the only columns, let’s ask for a list of column names:</p><pre>df.columns</pre><p>Output:</p><pre>Index([&#39;PassengerId&#39;, &#39;Pclass&#39;, &#39;Name&#39;, &#39;Sex&#39;, &#39;Age&#39;, &#39;SibSp&#39;, &#39;Parch&#39;, &#39;Ticket&#39;, &#39;Fare&#39;, &#39;Cabin&#39;, &#39;Embarked&#39;], dtype=&#39;object&#39;)</pre><p>That looks right so now let’s standardize the columns. Here I’m only lowercasing all column names. We’ll use a list comprehension.</p><pre>df.columns = [col.lower() for col in df.columns]</pre><p>Output:</p><pre>[&#39;passengerid&#39;,<br> &#39;pclass&#39;,<br> &#39;name&#39;,<br> &#39;sex&#39;,<br> &#39;age&#39;,<br> &#39;sibsp&#39;,<br> &#39;parch&#39;,<br> &#39;ticket&#39;,<br> &#39;fare&#39;,<br> &#39;cabin&#39;,<br> &#39;embarked&#39;]</pre><p>Perfect, they’re all lowercase.</p><h4>2. Discover column datatypes &amp; 4. Check for datatype-expectation mismatch</h4><p>Let’s get the shape of the dataframe.</p><pre>df.shape</pre><p>Output:</p><pre>(418, 11)</pre><p>So this data frame consists of 418 rows and 11 columns. Speaking of columns, let’s get the datatypes.</p><pre>df.dtypes</pre><p>Output:</p><pre>PassengerId      int64<br>Pclass           int64<br>Name            object<br>Sex             object<br>Age            float64<br>SibSp            int64<br>Parch            int64<br>Ticket          object<br>Fare           float64<br>Cabin           object<br>Embarked        object<br>dtype: object</pre><p>It looks as expected to me. I find that age is a float rather than an int. On the Kaggle data page it has an interesting note:</p><blockquote>age: Age is fractional if less than 1. If the age is estimated, is it in the form of xx.5 (<a href="https://www.kaggle.com/competitions/titanic/data?select=test.csv">source</a>)</blockquote><p>Also, a hat-tip to LS in my cohort for alerting us to this note!</p><p>So the presence of the decimal makes the Age column entries floats.</p><h4>3. Check for null/empty values</h4><p>Here we will check for any null/empty values. I’m using .isnum() here but .isna() will accomplish the same thing.</p><pre>df.isnull().sum()</pre><p>Output:</p><pre>passengerid      0<br>pclass           0<br>name             0<br>sex              0<br>age             86<br>sibsp            0<br>parch            0<br>ticket           0<br>fare             1<br>cabin          327<br>embarked         0<br>dtype: int64</pre><p>Earlier we had already seen that cabin contained values appearing as NaN so we should have expected it to contain null values. We can view the null values for age now.</p><pre>df[df.age.isnull()]</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CAu_oEoRw2iaSwDUeHWVSA.png" /><figcaption>`df[df.age.isnull()]` output by author</figcaption></figure><p>So at a glance we can see that null values in age are also marked as NaN.</p><p>Normally, I would have a deeper thinking process about how to handle the nulls. But in the interest of saving both your time and mine I’m going to fill all the null values with -1 then recheck with .isna().</p><pre>df.fillna(-1, inplace=True)<br>df.isna().sum()</pre><p>Output:</p><pre>passengerid    0<br>pclass         0<br>name           0<br>sex            0<br>age            0<br>sibsp          0<br>parch          0<br>ticket         0<br>fare           0<br>cabin          0<br>embarked       0<br>dtype: int64</pre><h4>5. Convert binary columns to numeric</h4><p>The only column that is strictly binary is sex. The columns pclass and embarked could be considered trinary cases because their values respectively are [1,2,3] and [‘S’,’Q’,’C’]. But again in the interest of time let’s just do our binary entries.</p><pre>df = pd.get_dummies(df, columns=[‘sex’], drop_first=True)</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KCG7tIFcTiyDq81Uq8HjQw.png" /><figcaption>new column `sex_male`</figcaption></figure><p>The sex column consisting of Yes/ No has been replaced by a new column sex_male as the end of the dataframe. Every 1 signals that the passenger is male and 0 signals a female passenger.</p><h4>6. Summary statistics</h4><p>Now we will pull up some summary statistics of the columns with numerical values by using the .describe() method.</p><pre>df.describe()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TrJeqVCSPPbYWVz5gUznDw.png" /><figcaption>`.describe()` output by author</figcaption></figure><p>Here we get a snapshot of various statistics such as count, mean, std, min &amp; max, and the numbers divided into quartiles. It’s good to note that since we introduced a -1 to fill all the NaNs, we should consider that the mean and std for age and fare will most likely be skewed.</p><p>The fact that a -1 appears in the fare column sends me an alert that there were some ninja null values hiding in the dataset. If were doing this in depth, I would go back and examine fare more closely.</p><p>The max values of sibsp and parch seem somewhat high so I’m thinking those values, as well as max of fare are outliers.</p><h4>7. Visualize data</h4><p>Now let’s visualize the data to get a quick way to confirm those outliers or not.</p><pre>df.fare.plot(kind=’hist’, bins=20, color=’navy’)<br>plt.title(‘Distribution of Fares’,size=20)<br>plt.ylabel(‘Frequency’,size=14)<br>plt.xlabel(‘Fare’, size=14);</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*QumU15hmJDzDuOVSX-QYRA.png" /></figure><p>Here we can easily see that fares in the area of 500 are definitely outliers.</p><p>Now visualizing sibsp and parch, we get:</p><pre>df.sibsp.plot(kind=’hist’, bins=15, color=’dodgerblue’)<br>plt.title(‘Distribution of # Siblings/Spouses Aboard’,size=20)<br>plt.ylabel(‘Frequency’,size=14)<br>plt.xlabel(‘Siblings/Spouses’, size=14);</pre><pre>df.parch.plot(kind=’hist’, bins=20, color=’darkorange’)<br>plt.title(‘Distribution of # Parents/Children Aboard’,size=20)<br>plt.ylabel(‘Frequency’,size=14)<br>plt.xlabel(‘Siblings/Spuses’, size=14);</pre><p>Outputs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*jOB8356C-YQkbcgV-CVp4Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*eIA6igIM6_yqR0I5xVYuGA.png" /></figure><p>Again, we can confirm from the histograms that the max values for these the sibsp and parch categories are outliers.</p><h4>8. Bonus cleaning step</h4><p>There is one category that probably is most irrelevant here: ticket. Because the purpose of this dataset is to predict who survived, I would drop ticket from my analysis entirely as I don’t see it being related.</p><h3>Final thoughts</h3><p>So even though we covered a lot of ground on this particular dataset, the data cleaning and analysis doesn’t stop.</p><p>Recall that after water has been treated for drinking and consumption, it eventually gets returned to the treatment facility to be cleaned again and released back into nature where it becomes part of the ecocycle.</p><p>The data cleaning process works in a similar way: Data gets cleaned. Data gets analyzed. Data gets cleaned again. Data gets analyzed.</p><p><em>If you do data science what goes into your data cleaning process?</em></p><p>Enjoyed this post? Go ahead a give me a follow <a href="https://medium.com/@i.johnmedina">@i.johnmedina</a>. Thanks so much for reading! 🙏</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=141688974024" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Journey into Data Science]]></title>
            <link>https://medium.com/@i.johnmedina/a-journey-into-data-science-12047d84475c?source=rss-f0b2a152ff60------2</link>
            <guid isPermaLink="false">https://medium.com/p/12047d84475c</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[codingbootcamp]]></category>
            <category><![CDATA[data-science-training]]></category>
            <dc:creator><![CDATA[John Medina]]></dc:creator>
            <pubDate>Wed, 03 Aug 2022 06:59:36 GMT</pubDate>
            <atom:updated>2022-08-04T13:47:25.906Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wd_24phGz6IGMikutlpVKg.jpeg" /><figcaption>Photo by Pixabay: <a href="https://www.pexels.com/photo/view-of-airport-247791/">https://www.pexels.com/photo/view-of-airport-247791/</a></figcaption></figure><h4>A Fascination Begins: Reminiscing on Progress</h4><p>My fascination with all things computers and technology began in the late 1980s. It was mainly for one reason: computer games. All of my friends in the neighborhood had their gaming computers, which at the time were Commodore 64s (C-64 had really cool commercials). One even had an Amiga 2000, the premium line. I remember my excitement when my parents bought me my first PC. It was a Commodore Colt with an 8086 processor and 640K of RAM and I hated it because it didn’t have any games or a hard drive—or even a 3.5-in. floppy for that matter!</p><p>Anyway I slowly began to use the Colt and get acquainted with it. I remember booting up MS-DOS, seeing in the manual some instructions to create a text file, and following the instructions. I made my first file, complete with actual text, and got the computer to print it on the monitor in its entirety! That was my first taste of my journey into technology and I loved it. I put that old Colt through its paces over its lifetime as I learned to use the command line, as well as programs like Lotus 1–2–3, WordPerfect, and PKZIP. Eventually I even got some games to play on that Colt.</p><p>Over the years my tech fascination continued as I upgraded to computers with 386 DX, 486, and then Pentium processors. Desktops, towers, laptops, PDAs, Blackberries, netbooks, iPhones, Galaxies, and Pixels. I was amazed at how quickly technology was moving, and how much more compact and portable it was becoming.</p><p>I remember the internet as it progressed from dial-up AOL, DSL, and cable. From those bulky 9600 baud modems to cable modems, switches, and routers. Just when you think internet speeds couldn’t get any faster, they doubled then tripled. Speeds today are still going faster and faster. Web browsers are becoming more sophisticated, especially in the privacy department.</p><h4>Knocking Out Some Projects</h4><p>One of my recent projects the past couple of years was to create a fast and reliable network that spanned the entirety of my parents’ home. The house is quite spacious, so with only one router there were many dead spots. I found that I could extend the network to other rooms with a couple of MoCA adapters and then run routers off them. To get around a lot of limitations imposed by the manufacturers, I had to replace the routers’ firmware with custom software, namely OpenWRT and FreshTomato. All the routing is handled by a central router running pfSense. I loved every moment of that project, and I still work on network tweaks and optimizations from time to time.</p><p>Prior to that, one of my major projects had to do with my master’s thesis. A classmate of mine mentioned he was using a program called LaTeX to typeset his thesis. I really didn’t think much of it at the time. But then I began to run into problems with right-to-left (R-to-L) languages in Microsoft Word. As I searched for solutions, I landed upon LaTeX as a program that handled R-to-L languages elegantly. The only problem was that LaTeX was no word processor. The entire process required configuring every aspect of the document—from line spacing, to fonts, to margins, to indentations, to small capitals, to footnotes, to title page, to bibliography, and everything in between. And the configuration had to be written in its own code language! But when I finished I was so proud of not just the content but the aesthetics.</p><h4>Those FAANGs</h4><p>It’s not like I really intended to keep up with technology. It just so happened that way because technology has become so ubiquitous that it is now a significant part of people’s lives. All thanks to FAANG!</p><p>FAANG is shorthand that, as far as I can tell, originated in the financial world. It stands for Facebook, Apple, Amazon, Netflix, and Google. Over the past decade, these companies have been watched closely by the financial world for their business performance and future business prospects. The past 10 years, financial markets have basically been marked by the performance of these companies’ stocks.</p><p>When I first started in finance I had little idea about data, algorithms, and machine learning. I read a few comments here and there about hedge funds utilizing these tools to their success. Hedge funds like Renaissance and Bridgewater, helmed at that time by James Simons and Ray Dalio. So I knew that data science and analysis was being applied to the financial markets.</p><h4>This Data Analytics Thing is Everywhere</h4><p>As I learned more about businesses at a deeper level, I started to realize just how big of a role data and technology played in their operations. Various documentaries have reported on the extent of how valuable data is to companies like Facebook and Google and the technologies they use to predict user behavior. It’s not just tech companies either that rely on data science. Companies use data science and analysis to inform their creativity, products, sales, and advertising.</p><p>When I began to understand this better, I began to look into machine learning. After all, our smart devices utilize machine learning extensively. I noticed my smartphone becoming increasingly more accurate about predicting my routines and sending me well-timed notifications. As I became more curious about data science, I would search for people blogging on data science and I would try to follow some of their small projects on my own computer. The experience was like my first foray into MS-DOS that I described above. Since data science has its own flavor and is a much bigger field than an 1980s operating system, I was quite limited in understanding as well as time.</p><h4>A Deepening Interest</h4><p>My entire profession has been in sales. My dabbling into data science got me thinking about questions like what if I could analyze some of the best salespersons or advertisements and discover if there are any particular words or phrases that factor into their success. Or even if I could add clarity around the question of why people buy. There were many possible ways to apply data analytics and data science.</p><p>What did pique my interest as to a career in data science was when my wife mentioned that many of her coworkers were leaving their jobs to become coders. She didn’t mention what area of coding they were going into (and I’m not even sure she knew), but it was at that point that I realized, particularly with all the emphasis on data analysis that I was seeing around me, that data science is the future.</p><h4>Equipping with a GA Bootcamp for a Career Change</h4><p>So when I decided to get serious about data science as a career, I looked into various programs. With young kids and a wife that just switched to a new job, I was looking particularly at remote programs. Reputation of course was high on my list. One program that I heard mentioned in some videos made by those who were hired in tech was General Assembly (GA). I also read some good reviews on the data science program. All the coding bootcamp reviews had high regard for the GA programs. I decided to give the application a go.</p><p>Thankfully I was accepted and I have been enjoying my journey so far. I plan to made a difference in this world through data science. Whether that’s through collaborating with other intelligent peers at an awesome company, or going as a solo coder and analyst at a startup, or teaching computer science and coding—or maybe all three.</p><p>If you liked my story and want to follow my continuing journey, go ahead a give me a follow @i.johnmedina. Thanks so much for reading! 🙏</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12047d84475c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>