<?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 Khadija Mahanga on Medium]]></title>
        <description><![CDATA[Stories by Khadija Mahanga on Medium]]></description>
        <link>https://medium.com/@khadijamahanga?source=rss-a12e1b23fdb7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Uu4KRZblszWq2mmFpjj7Cg.jpeg</url>
            <title>Stories by Khadija Mahanga on Medium</title>
            <link>https://medium.com/@khadijamahanga?source=rss-a12e1b23fdb7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 07:53:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@khadijamahanga/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[Extracting Satellite Images from Google Earth Engine (GEE)]]></title>
            <link>https://medium.com/@khadijamahanga/extracting-satellite-images-from-google-earth-engine-gee-193557edab16?source=rss-a12e1b23fdb7------2</link>
            <guid isPermaLink="false">https://medium.com/p/193557edab16</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[gis]]></category>
            <category><![CDATA[google-earth-engine]]></category>
            <category><![CDATA[sentinel-2-imagery]]></category>
            <dc:creator><![CDATA[Khadija Mahanga]]></dc:creator>
            <pubDate>Sat, 26 Apr 2025 16:00:20 GMT</pubDate>
            <atom:updated>2025-04-26T16:00:20.959Z</atom:updated>
            <content:encoded><![CDATA[<p>Looking for satellite imagery like Landsat, Sentinel, or other datasets? Google Earth Engine (GEE) is powerful platform that you can use to access and analyze geospatial data. It hosts almost every free satellite imagery available. In this article, I will guide you step-by-step on how to extract satellite images from GEE for academic or non-commercial use.</p><p><strong>Prerequisite</strong>: You’ll need a google account, if you don’t have one, you can create it <a href="https://accounts.google.com/">here</a>.</p><h3><strong>Get Started- Accessing Google Earth Engine</strong></h3><ol><li>Visit <a href="https://code.earthengine.google.com/">google earth engine</a>. If you’re a new user, you will see a prompt to register a new project.</li><li>Click “<strong><em>I want to register a new project</em></strong>”. This will redirect you to <a href="https://console.cloud.google.com/">console</a> where you will be required to finish configuration.</li><li>Select “<strong><em>Get Started</em></strong>” to register for non-commercial use. Fill in the required fields, then click Register.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*4Wj2KXuBQL_zISj5LidRZw.png" /></figure><p>4. When prompted, make sure you enable <strong>Google Earth Engine API </strong>to get you full access to the platform.</p><p>5. Click continue, and then click connect using code editor to launch the editor</p><h3>Finding and Filtering Satellite Imagery</h3><p>Now that you’ve accessed the <strong>Code Editor</strong>, let’s walk through how to find and filter satellite imagery for your area of interest (AOI). <em>(If you haven’t explored the interface yet, take a quick tour under </em><strong><em>Help &gt; Interactive Tutorials</em></strong><em> to familiarize yourself with the layout.)</em></p><h4>Step 1: Define Your Area of Interest (AOI)</h4><p>To begin, you’ll need a boundary layer for your study area. There are two ways to do this:</p><ol><li><strong>Draw a geometry manually</strong> using the drawing tools (rectangle, polygon, etc.).</li><li><strong>Search for administrative boundaries</strong> (recommended for accuracy):</li></ol><ul><li>Use the <strong>search bar</strong> at the top of the Code Editor.</li><li>Type <em>“FAO”</em> to see a list of global administrative datasets (e.g., country, state, or district boundaries).</li><li>Select <strong>“FAO GAUL 500m Simplified: Global Administrative Unit Layers 2015, Second-Level Administrative Units”</strong> (or another relevant layer).</li><li>Click <strong>Import</strong> to add it to your script.</li></ul><p><em>Note: The imported layer will appear under the </em><strong><em>“Imports”</em></strong><em> section at the top of your script. The variable given is table as seen in the image below.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AAvkYMSN50Rh90wSq8RKXQ.png" /></figure><ul><li><strong>Add your boundary layer to the map</strong> by typing in your script on your editor Map.addLayer(table)</li><li>Then click <strong>“Run”</strong> to display the layer (as shown in the image above)</li></ul><p><strong>Create a point marker</strong> for your specific area of interest:</p><ul><li>Click the <strong>marker icon</strong> in the top-right corner of the map.</li><li>Click on your desired location to create a new variable called geometry.</li><li><strong>Filter your boundary</strong> to focus on your region using the following lines.</li></ul><pre>var myRegion = table.filterBounds(geometry)<br>Map.addLayer(myRegion)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*E-ZyMKezZZ--sHSmeSxIZQ.gif" /><figcaption>filtering bounds</figcaption></figure><h4>Alternative: Define ROI Using Coordinates</h4><p>If you already know your area’s coordinates, you can directly create a geometry:</p><pre>// Region of interest.<br>var ROI = ee.Geometry.Point(-119.9087, 37.4159);<br><br>//For a polygon, use:<br>var ROI = ee.Geometry.Polygon([[[x1,y1], [x2,y2], [x3,y3], [x4,y4]]]);</pre><h4>Step 2: Filter and Export Sentinel-2 Imagery</h4><p>Google Earth Engine hosts multiple datasets <a href="https://developers.google.com/earth-engine/datasets">available datasets</a>. Here’s how to work with Sentinel-2:</p><ol><li><strong>Filter the Sentinel-2 collection</strong> by location, date, and cloud cover:</li></ol><pre>// Filter the Sentinel-2 image collection<br>var sentinel2 = ee.ImageCollection(&#39;COPERNICUS/S2_SR_HARMONIZED&#39;)<br>                .filterBounds(geometry)  // Filter by the bounding box<br>                .filterDate(&#39;2023-01-01&#39;, &#39;2023-12-31&#39;)  // Filter by date range<br>                .filter(ee.Filter.lt(&#39;CLOUDY_PIXEL_PERCENTAGE&#39;, 20));  // Filter by cloud coverage (&lt; 20%)</pre><p>2. <strong>Create a median composite. </strong>When working with time-series imagery (e.g., Sentinel-2 or Landsat), <strong>median composites</strong> (median()) help:</p><ul><li><strong>Reduce Cloud Cover </strong>by taking the median pixel value across multiple images, transient features (like clouds) are often excluded.</li><li><strong>Minimize Noise</strong>: Outliers (e.g., sensor errors, aerosols) are statistically filtered out.</li><li><strong>Preserve Land Features</strong>: Stable surfaces (e.g., water, vegetation) remain consistent.</li></ul><p>But if you are looking at temporal details, time-series imagery then you may use mean for specified range instead. As median() function may smooth-en out.</p><pre>// Take the median image of the filtered collection (to reduce cloud impact)<br>var medianImage = sentinel2.median();<br></pre><p>3. <strong>Visualize the rgb image </strong>using visible bands:</p><pre>// Visualization parameters for the RGB image (Red, Green, Blue bands)<br>var visParams = {<br>  bands: [&#39;B4&#39;, &#39;B3&#39;, &#39;B2&#39;],  // Red, Green, Blue bands<br>  min: 0, <br>  max: 3000<br>};<br></pre><p>4. Export to Google Drive</p><pre>// Add the median image to the map<br>Map.addLayer(medianImage, visParams, &#39;Sentinel-2 RGB Median&#39;);<br><br>// Export the image to your Google Drive<br>Export.image.toDrive({<br>  image: medianImage,<br>  description: &#39;Sentinel2_Extracted_Image&#39;,  // Name of the exported image<br>  scale: 10,  // Sentinel-2 has a 10m resolution for the visible bands<br>  region: geometry,  // Define the region to export (bounding box)<br>  fileFormat: &#39;GeoTIFF&#39;,  // The file format for the exported image<br>  maxPixels: 1e8  // Increase this value if the image is very large<br>});For more detailed tutorial on GEE API, visit this YouTube tutorial that I found really helpful for complete beginners.</pre><h3>Step 3: Check status on Tasks bar</h3><p>After running Export.image.toDrive(), follow these steps:</p><ol><li><strong>Locate the Tasks tab</strong>:</li></ol><ul><li>In the <strong>Code Editor</strong>, find the <strong>“Tasks” tab</strong> (upper-right panel, next to “Scripts”).</li><li>Your export will appear as a pending task (e.g., Sentinel2_Extracted_Image).</li></ul><p><strong>2. Start or Monitor the Export</strong>:</p><ul><li>Click <strong>“Run”</strong> next to the task to begin processing.</li><li>Status updates will appear (e.g., “Running,” “Completed,” or “Failed”).</li></ul><p><em>Note: Large exports may take hours. Check back later or monitor the </em><a href="https://console.cloud.google.com/home/activity"><em>Google Cloud Activity Dashboard</em></a><em> for detailed logs.</em></p><p><strong>3. Access Exported Files</strong>:</p><ul><li>Once completed, the file will appear in your <strong>Google Drive</strong> under the folder google engine.</li></ul><h3>Wrapping Up &amp; Next Steps</h3><p>Congratulations! You’ve now learned how to access and filter satellite imagery in Google Earth Engine. To deepen your knowledge, explore these resources:</p><ul><li><a href="https://www.youtube.com/watch?v=K5GTY9sGe5Y&amp;list=PLLW-qoCMKQsx62nKon2-0PMtGzkxlwN7k">Intro to Earth Engine in Javascript | Geo for Good</a></li><li><a href="https://www.youtube.com/@amirhosseinahrarigee">Google Earth Engine Tutorial with Amirhossein Ahrari</a></li><li>You may also navigate to the <strong>“Scripts” tab</strong> in the left sidebar, there are example scripts that you can also practice or refer to.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=193557edab16" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unstructured PDF Text Extraction]]></title>
            <link>https://medium.com/khadija-mahanga/unstructured-pdf-extraction-series-a8ba04da767f?source=rss-a12e1b23fdb7------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8ba04da767f</guid>
            <category><![CDATA[unstructured-data]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pdf-extraction]]></category>
            <category><![CDATA[text-extraction]]></category>
            <dc:creator><![CDATA[Khadija Mahanga]]></dc:creator>
            <pubDate>Thu, 18 Apr 2024 13:11:08 GMT</pubDate>
            <atom:updated>2025-09-03T06:01:39.803Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever encountered a daunting task of extracting content from unstructured PDF files, only to find that existing Python packages fall short of meeting your requirements? By unstructured, I mean PDFs with multiple elements and varying page layouts. Picture a file containing a table on one page, two tables on another, or perhaps none at all. Imagine encountering single-column layouts on one page, and two or three-column layouts on another, with tables nestled within those columns. This was precisely the challenge I faced.</p><p>I experimented with various packages like <a href="https://pypi.org/project/tabula-py/">tabula</a>, among others. However, each had its strengths and weaknesses. While tabula excelled at extracting tables, it struggled with extracting merged cells information from tables and is not for text extraction. I discovered that <a href="https://github.com/pdfminer/pdfminer.six">pdfminer</a> was excellent for extracting text from pages with multiple columns, while <a href="https://github.com/jsvine/pdfplumber">pdfplumber</a> shone when it came to extracting tables with merged cells. I even found a package called <a href="https://github.com/Unstructured-IO/unstructured">unstructured</a>, which was a step in the right direction, meeting about 80% of my needs. Although it performed well in extracting some tables, it often missed others entirely. This issue was common among extraction packages utilizing Optical Character Recognition (OCR), where not all tables could be accurately extracted from PDF files, sometimes even omitting the last row or column of a table.</p><p>So, I devised a solution that successfully handled the majority of my sample PDFs. However, I’ll address the few exceptions later.</p><p>My approach involved combining pdfminer, pdfplumber, and fitz from pymupdf to extract text, table information, and images while preserving their layout and flow.</p><h3>Extracting text and tables</h3><p>To extract both text and tables in an organised manner, I used pdfplumber package function to identify and extract tables from a page. Subsequently, I utilized a pdfminer function to extract text elements sequentially from the page, excluding those within the boundaries of identified tables. When printing the output string, I ensured to preserve the reading flow and the position of tables.</p><p>Let us dive straight into the function without dwelling on packages installation:</p><p>In the initial phase of my function, I instantiated objects from each package to process a single PDF file comprehensively. Thereafter, I iterated through each page, prioritizing the identification of table objects that exist in a page using the pdfplumber’s find_tables function as seen in the code below.</p><pre>def pdf_process(path):<br>    plumberObj = pdfplumber.open(path)<br>    minerPages = extract_pages(path)<br>    fitzDoc = fitz.open(path)<br>    ...<br>    for i in enumerate(minerPages):<br>        tables = plumberPage.find_tables(table_settings={&quot;text_vertical_ttb&quot;: False})<br>        page_text = miner_extract_page(page_layout, tables)</pre><p>Once I had the table objects, I moved to pdfminer. While pdfminer isn&#39;t flawless in table extraction, it excels in handling different page layouts in a PDF. And note my sample PDF files had inconsistent layouts throughout its pages. Therefore, for each page layout, I ensured to crop out all table objects from that page using the helper check function is_obj_in_bbox</p><blockquote>Note, that table object includes a property for it’s boundary box called _<a href="https://github.com/jsvine/pdfplumber/blob/stable/pdfplumber/table.py#L378">bbox</a>. We use that boundary in the helper function.</blockquote><pre>def is_obj_in_bbox(obj, _bbox, page_height):<br>    &quot;&quot;&quot;<br>    checks if an element boundary box is within another boundary<br>    &quot;&quot;&quot;<br>    objx0, y0, objx1, y1 = obj<br>    x0, top, x1, bottom = _bbox<br>    return (objx0 &gt;= x0) and (objx1 &lt;= x1) and (page_height - y1 &gt;= top) and (page_height - y0 &lt;= bottom)</pre><p>You will notice here that I am employing page_height in the check function and this is due to differences in boundary dimensions between pdfplumber package and pdfminer package. <a href="https://github.com/jsvine/pdfplumber/issues/198">Read more about the bbox inversion between this two packages from this issues.</a></p><p>Now, let’s examine the miner_extract_page function:</p><pre>def miner_extract_page(page_layout, tables):<br>    &quot;&quot;&quot;<br>    this function extract texts, tables, images from a single page layout<br>    Paremeter:<br>      page_layout -&gt; A pdfminer page object<br>      tables -&gt; An array of pdfplumber table objects<br>    Returns:<br>      <br>    &quot;&quot;&quot;<br>    page_height = page_layout.height<br>    extractedTables = []<br>    page_output_str = &quot;&quot;<br>    <br>    for element in page_layout:<br>        if isinstance(element, LTTextContainer):<br>            tabBox = []<br>            # if current element exists in any of the tables, <br>            # append the t to tabBox<br>            for t in tables:<br>                is_obj_n_box = is_obj_in_bbox(element.bbox, t.bbox, page_height)<br>                if is_obj_n_box:<br>                    tabBox.append(t)<br>            # if tabBox is empty, extract the element with get_text() function<br>            if not len(tabBox):<br>                if isinstance(element, LTTextContainer):<br>                    elementText = element.get_text()<br>                    page_output_str += elementText<br>                else:<br>                    # check for figures layout at this point<br>                    # check for part 2 when I talk about images/figures<br>            # else, element exist in a certain table<br>            # therefore, we extract the found table <br>            # using pdfplumber table extract function and <br>            # concatenate to our end results<br>            else:<br>                if not tabBox[0] in extractedTables:<br>                    table_str = tabulate(tabBox[0].extract(**({&quot;vertical_ttb&quot;: False})), tablefmt=&quot;grid&quot;)<br>                    page_output_str += table_str<br>                    page_output_str += &quot;\n&quot;<br>                    # to avoid repetition we used extractedTables to <br>                    # filter already extracted tables. <br>                    extractedTables.append(tabBox[0])<br>    return page_out_str</pre><p>In the above function, I am using tabulate package for printing purposes on the final string. Otherwise it is not necessary. And in case you’re extracting a PDF for LLM models, its better to avoid it as it adds more characters to your final output. But also make sure you employ some sort of an organised way to print it to avoid confusion as the output of a table extraction is 2 dimensional array.</p><h3>Extracting Images</h3><p>This task also involved identifying certain pictograms/images with the PDF files. I had about 10 different pictograms that I was supposed to check if any of them existed in the file or not. My solution was to first extract all images on the PDF page, and utilize image hashing or other template comparison methods (<em>matchTemplate from cv2 package</em>) to determine if the extracted images for the PDF file matched any of the pictograms I had.</p><p>One effective package for extracting images is PyMuPDF (fitz), which I chose to utilize. However, I encountered a challenge where not all images were being properly identified or extracted. I speculated whether this was due to the types of images used during the PDF compilation process, such as PNGs or SVGs, but I couldn’t confirm this definitively.</p><p>For the image extraction process, I implemented a function called check_for_image:</p><pre>def check_for_image(pdf_path):<br>    &quot;&quot;&quot;<br>    Function that get images from pdf pages and save them to local drive<br>    Parameters:<br>    pdf_path -&gt; Path of the PDF file<br>    &quot;&quot;&quot;<br>    pdf_document = fitz.open(pdf_path)<br>    xreflist = []<br>    page_num = 0<br>    il = pdf_document.get_page_images(page_num)<br>    logger.info(f&quot;Found {len(il)} images&quot;)<br><br>    for img in il:<br>        xref = img[0]<br>        if xref in xreflist:<br>            continue<br>        width = img[2]<br>        height = img[3]<br>        <br>        #skip tiny images<br>        if min(width, height) &lt;= 5:<br>            continue<br>        imgdata = img[&quot;image&quot;]<br>        imgfile = os.path.join(f&quot;drawing-img-{xref}-{page_num + 1}.{img[&#39;ext&#39;]}&quot;)<br>        fout = open(imgfile, &quot;wb&quot;)<br>        fout.write(imgdata)<br>        fout.close()<br>        xreflist.append(xref)<br>    pdf_document.close()</pre><p>But because of the image challenge mentioned, I also implemented an extra function in addition to checking normal images. The function was to check for drawings. For drawing can be anything from a lines to more complex shapes (you may read more on the function <a href="https://pymupdf.readthedocs.io/en/latest/page.html#Page.get_drawings">get_drawings</a>), I employed various steps such as enlarging the rectangle size by a certain number, applying filters for anything smaller or any drawing within a bigger drawings, before getting apixmap of the enlarged area of page that include a drawing in it. I would subsequently compare the pixmap generated to the pictograms I have to make a decision.</p><pre>def check_for_drawings(pdf_path):<br>    &quot;&quot;&quot;<br>    Function that finds drawings from pdf pages and save pixmap of <br>    on enlarged drawing&#39;s rectangle to local drive<br><br>    Parameters:<br>    pdf_path -&gt; Path of the PDF file<br>    &quot;&quot;&quot;<br>    pdf_document = fitz.open(pdf_path)<br>    for page_num in range(pdf_document.page_count):<br>        page = pdf_document[page_num]<br>        d = page.get_drawings()<br>        new_rects = []<br>        for p in d:<br>            # filter emplty rectangle<br>            if p[&quot;rect&quot;].is_empty:<br>                continue<br>            w = p[&quot;width&quot;]<br>            if w:<br>                r = p[&quot;rect&quot;] + (-w, -w, w, w)  # enlarge each rectangle by width value<br>                for i in range(len(new_rects)):<br>                    if abs(r &amp; new_rects[i]) &gt; 0:  # touching one of the new rects?<br>                        new_rects[i] |= r  # enlarge it<br>                        break<br>                <br>                # now look if contained in one of the new rects<br>                remainder = [s for s in new_rects if r in s]<br>                if remainder == []:  # no ==&gt; add this rect to new rects<br>                    new_rects.append(r)<br>        <br>        new_rects = list(set(new_rects))  # remove any duplicates<br>        new_rects.sort(key=lambda r: abs(r), reverse=True)<br>        remove = []<br>        for j in range(len(new_rects)):<br>            for i in range(len(new_rects)):<br>                if new_rects[j] in new_rects[i] and i != j:<br>                    remove.append(j)<br>        remove = list(set(remove))<br>        for i in reversed(remove):<br>            del new_rects[i]<br>        new_rects.sort(key=lambda r: (r.tl.y, r.tl.x))  # sort by location<br><br>        mat = fitz.Matrix(5, 5)  # high resolution matrix<br>        for i, r in enumerate(new_rects):<br>            if r.width is None or r.height &lt;= 15 or r.width &lt;= 15:<br>                continue  # skip lines and empty rects<br>            pix = page.get_pixmap(matrix=mat, clip=r)<br>            hayPath = f&quot;drawing-rect{page_num}-{i}.png&quot;<br>            if pix.n - pix.alpha &gt;= 4:      # can be saved as PNG<br>                pix = fitz.Pixmap(fitz.csRGB, pix)<br>            pix.save(hayPath)<br>            pix = None                     # free Pixmap resources<br><br>   pdf_document.close()</pre><p>This comprehensive approach allowed me to successfully extract information from nearly all of the sample PDFs I encountered.</p><p>In reflecting on the limitations or edge cases of my solution, one challenge I faced was extracting tables that are border-less. Despite extensive efforts, I haven’t yet found a straightforward way to achieve this especially if you’re dealing with large set of PDF files that needs to be extracted. However, it’s worth noting that there are issues and discussions on pdfplumber github pages on the case of table borders. You may find all them using the following search query link <a href="https://github.com/jsvine/pdfplumber/issues?q=border">https://github.com/jsvine/pdfplumber/issues?q=border</a></p><p>In the meantime, I encourage exploration of open-source projects that may provide valuable insights and potential solutions to this particular challenge.</p><p><em>Anyone interested in the code, you may find it </em><a href="https://github.com/KhadijaMahanga/textract"><em>here</em></a><em> </em><a href="https://github.com/KhadijaMahanga/textract">https://github.com/KhadijaMahanga/textract</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8ba04da767f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/khadija-mahanga/unstructured-pdf-extraction-series-a8ba04da767f">Unstructured PDF Text Extraction</a> was originally published in <a href="https://medium.com/khadija-mahanga">Khadija Mahanga</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Reinforcement Learning with AWS DeepRacer]]></title>
            <link>https://medium.com/@khadijamahanga/introduction-to-reinforcement-learning-with-aws-deepracer-930ee7b5caf9?source=rss-a12e1b23fdb7------2</link>
            <guid isPermaLink="false">https://medium.com/p/930ee7b5caf9</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[women-in-data-science]]></category>
            <category><![CDATA[udacity]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[women-in-tech]]></category>
            <dc:creator><![CDATA[Khadija Mahanga]]></dc:creator>
            <pubDate>Sat, 19 Oct 2019 14:24:17 GMT</pubDate>
            <atom:updated>2019-10-19T14:24:17.651Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently enrolled myself into the <a href="https://classroom.udacity.com/courses/ud012">AWS DeepRacer</a> course in Udacity, a course that guides student on how to use reinforcement learning and AWS platform to train and deploy an autonomous racer. I enrolled to the course to strengthen my skills in machine learning and to take part in a scholarship challenge organised by Udacity and AWS, where successful students who participate in the autonomous racing league earn a full scholarship to the Machine Learning Engineer Nano-degree program. Yeeeyy!</p><p>The program will run through October 31st, 2019. So if you’re reading this before the 31st and are interested, you can go ahead and join <a href="https://www.udacity.com/aws-deepracer-scholarship">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*Go4iUKuUou88BLn3ZjsYtQ.png" /></figure><p>In this post, I am sharing some of the introductory lessons that I have learnt.</p><h4>What is an AWS DeepRacer &amp; AWS DeepRacer League?</h4><p>AWS DeepRacer is a tiny toy-like car<a href="https://youtu.be/jD0Z9D9Y0Sc"> launched by AWS</a> with sole purpose of helping developers get rolling with reinforcement learning. Its size as described is 1/8th of a real race car. It comes with all sensors and software tools necessary. This toy-kind racing car can be ordered on Amazon.</p><p>AWS DeepRacer Leagues are free for anyone. They are world’s first racing leagues of <strong>autonomous</strong> <strong>cars</strong>. Entrant, mostly developers, race for prizes and prestige and of course a chance to advance to championship cup. If you want to join the league and do not have a physical racing car, you can still train your model on AWS console and race on virtual leagues.</p><h4>How Reinforcement Learning differs from Supervised and Unsupervised machine learning.</h4><p>Behind the scene of AWS Deepracer and AWS Deepracer league, is a powerful machine learning mechanism known as reinforcement learning. You might be wondering..another type of machine learning!? Well, exactly that. We most are familiar with the two types of machine learning, supervised and unsupervised machine learning.</p><p>Supervised learning is when you train your model based on labels (features) provided in each input. In this type of machine learning, labels provide the model with ground knowledge (i.e. labels act like a teacher).</p><p>In unsupervised learning there is no teacher. Also known as self-organize learning, models identify patterns on their own from input data that have no corresponding output.</p><p>Unlike the two most known types of machine learning, reinforcement learning trains its model continuously by mining feedback from previous iteration. In this type, you have an agent that learns through ‘trial and error’ from its environment, inferring solution from the consequences of its approach (i.e. learning from its mistake).</p><h4>Aspects of Reinforcement Learning models</h4><p>You might have catch the words ‘agent’, ‘environment’, ‘consequences’ from the above brief. These are some of aspects of machine learning. Other two that make up five are state and action. These five components are vital in optimizing model and enhancing model performance in reinforcement learning.</p><ol><li><strong>Agent</strong>: Is an entity that exhibits a certain behavior based on experience of interacting with the environment around it. In our scenario, an AWS deepracer car is an agent.</li><li><strong>Environment</strong>: This is where the agent operates. For AWS deepracing, the route/track is the environment of our deepracer car.</li><li><strong>Action</strong>: Agent perform several actions at a certain point in an environment. For AWS car, actions can be speeding up, standing still, moving towards a certain direction, slowing down, and et cetera.</li><li><strong>State</strong>: A condition in which an agent exist in the environment. State is never constant, it keeps on changing with each action the agent takes. To understand a state, you can try to answer a question that asks “What is going at a given time in the environment”. For AWS car, a state at given time can be identified by answering these: <em>what speed is the car moving at?</em>, <em>how far the car from the center of the track</em>, <em>are all wheels on the track</em>?, <em>what is position of the car</em>?, <em>what is the steering angle? </em>and so on.</li><li><strong>Reward:</strong> Is a mechanism that used by environment to let the agent know what it is doing. A “teacher-like component that assign models with a reward for wanted/correct behavior and a penalty for unwanted behaviors. In AWS Deepracer, reward component is crucial in learning what ideal action to perform in an environment given a particular state, hence improving it performance around the track.</li></ol><h4>Other use cases of reinforcement learning</h4><p>Beyond AWS DeepRacer, Reinforcement Learning is mostly used in the game industry and robotics industry while its application is being researched in many other sectors. Examples are in <a href="https://sustainability.google/projects/machine-learning/">industrial automation</a>, <a href="http://web.eecs.utk.edu/~ielhanan/Papers/IET_ITS_2010.pdf">Traffic light control</a> to solve congestion, in <a href="https://pubs.acs.org/doi/full/10.1021/acscentsci.7b00492">chemistry</a> to optimize chemical reactions, in <a href="https://dl.acm.org/citation.cfm?id=1016912">media and advertising industry</a> and more.</p><p><em>Reinforcement Learning is a game-changer and after reading this introduction I hope you’re looking forward to get hands-on RL as I am, which I will write about it here too. Stay tuned, and thank you!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=930ee7b5caf9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning Data Preparation with Kaggle]]></title>
            <link>https://medium.com/@khadijamahanga/learning-data-preparation-with-kaggle-65f32594b645?source=rss-a12e1b23fdb7------2</link>
            <guid isPermaLink="false">https://medium.com/p/65f32594b645</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-exploration]]></category>
            <category><![CDATA[women-in-tech]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[female-developer]]></category>
            <dc:creator><![CDATA[Khadija Mahanga]]></dc:creator>
            <pubDate>Sun, 22 Sep 2019 11:55:20 GMT</pubDate>
            <atom:updated>2019-09-22T12:00:56.580Z</atom:updated>
            <content:encoded><![CDATA[<p>In a previous <a href="https://medium.com/@khadija_11147/want-to-write-something-on-tech-93acad6dd1c9">story</a>, I mentioned how Kaggle platform was intimidating for a beginner. There are a lot of competitions going on that might leave an amateur like me overwhelmed. But I have decided to embrace Kaggle platform and take it in, step by step. Here’s a little tale of my exploration.</p><p>I became aware, latterly, of Kaggle’s <a href="https://www.kaggle.com/learn/overview">learning track</a>, which offers short and hands-on courses on data science. The courses available are on Python, Machine learning, Pandas, Data Visualisation, SQL, R, and Deep Learning. As I am experienced in Python (most active programming languages in my career at the moment), I skipped to Machine Learning Course, a 4 hours high level course instructed by Dan Becker.</p><p>The course jumps to Data exploration after introducing how models work, and followed by four more topics plus an exercise. The course&#39;s practice, however, was minimal (obvious..as it is a high level course) and I went AWOL. A week passed by not knowing where I could find a comprehensive practice, I end up navigating to House Prices competition which had a tutorial tab. In it, I found a link to a <a href="https://www.kaggle.com/pmarcelino/comprehensive-data-exploration-with-python">thorough tutorial </a>on data exploration by <a href="https://www.kaggle.com/pmarcelino">Pedro Marcelino</a>.</p><p>Not all competitions have tutorials tab, and are certainly not easy to navigate to. I suggest the platform have a section that house all tutorials such as this for more visibility.</p><p>Next in this blog is my week’s practice, where I learnt data exploration by following Pedro’s tutorial on how to explore and understand dataset. I randomly picked Credit Card Fraud Detection dataset from kaggle’s <a href="https://www.kaggle.com/mlg-ulb/creditcardfraud">dataset pool</a> for the practice.</p><h4>Data Preparation</h4><p>Analytic tools often require data to be in a form different from how data are provided naturally, making data preparation a necessary process in the field. It is reckoned that quality of models rests on how well one understands and craft their data. Typical process may involve the following</p><ul><li>Converting data to tabular format,</li><li>Removing or Inferring missing values,</li><li>Converting data to different types (i.e. some techniques are designed for symbolical/categorical data while others are for numerical).</li><li>Normalizing numerical values for better comparisons and others</li></ul><h4>Getting hands dirty</h4><p>I started a new notebook, imported all necessary libraries and loaded data source file as follows:</p><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>import numpy as np<br>from scipy.stats import norm<br>from sklearn.preprocessing import StandardScaler<br>from scipy import stats<br>import warnings<br>warnings.filterwarnings(&#39;ignore&#39;)<br>%matplotlib inline</pre><pre>data_file = &#39;./creditcard.csv&#39;<br>creditcard_df = pd.read_csv(data_file)</pre><p>The chosen dataset did not have description on its features due to confidentiality issues (I realized it was not a perfect choice of dataset, but do you really ever get a perfect data?!). Apart from <strong>Time</strong> and <strong>Amount</strong> column in the dataset,<strong> </strong>the rest of the variables were scaled. The <strong>Class</strong> column was our target variable with either 1 or 0 (Binary Classification). I proceeded to identify variables type and understand their relevance.</p><pre>creditcard_df.info()</pre><p>All variables were of the type float, and no missing data.</p><pre>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 284807 entries, 0 to 284806<br>Data columns (total 31 columns):<br>Time      284807 non-null float64<br>V1        284807 non-null float64<br>V2        284807 non-null float64<br>V3        284807 non-null float64<br>V4        284807 non-null float64<br>V5        284807 non-null float64<br>V6        284807 non-null float64<br>V7        284807 non-null float64<br>V8        284807 non-null float64<br>V9        284807 non-null float64<br>V10       284807 non-null float64<br>V11       284807 non-null float64<br>V12       284807 non-null float64<br>V13       284807 non-null float64<br>V14       284807 non-null float64<br>V15       284807 non-null float64<br>V16       284807 non-null float64<br>V17       284807 non-null float64<br>V18       284807 non-null float64<br>V19       284807 non-null float64<br>V20       284807 non-null float64<br>V21       284807 non-null float64<br>V22       284807 non-null float64<br>V23       284807 non-null float64<br>V24       284807 non-null float64<br>V25       284807 non-null float64<br>V26       284807 non-null float64<br>V27       284807 non-null float64<br>V28       284807 non-null float64<br>Amount    284807 non-null float64<br>Class     284807 non-null int64<br>dtypes: float64(30), int64(1)<br>memory usage: 67.4 MB</pre><p>The dataset however was highly biased, 99.8% of the dataset indicated no fraud — had the value 0 in the Class column. A skewed dataset as this might lead to over-fitting because our model could find “higher chance of occurrence of a one class in the data” as a pattern. We do not want this, we want our model to predict from feature labels and not chances of occurrences. Therefore I created a subset from the dataset with 50–50 distribution to proceed with the practice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*PenfeDvwHhZDqarjNfc37g.png" /><figcaption>Count distribution of original dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*ZTkGoUrlbrrU1_jihQzVPA.png" /><figcaption>Count distribution of sample subset</figcaption></figure><h4>Correlation Matrix</h4><p>Part of understanding your data, is the need to acknowledge that not all features in your dataset will be useful in building your model. And one way to find out is by examining correlation between variables. Variables with high correlation are more linearly dependent and will certainly have similar effect to the target variable. In such case, we can drop one of the variables.</p><p>I generated a correlation matrix using pandas’ convenient one-line method corr() and used heatmap for visualizing.</p><pre>#correlation matrix<br>corrmat = new_df.corr()<br>f, ax = plt.subplots(figsize=(15, 10))<br>sns.heatmap(corrmat,cmap=sns.color_palette(&quot;BrBG&quot;, 256), square=True</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*o_c20r0Kqe-iSB5pdk1Emw.png" /><figcaption>Correlation Matrix</figcaption></figure><p>V2, V4, V11, V19 have positive correlation to Class variable, V3, V9, V10, V12, V14, V16 have high negative correlation, while V8, V22, V25, V26 have neutral correlation.</p><p>There are variables that show significant correlation between them, V1 and V7, V4 and V11, V12 and V14, V16 and V17, V18 and V17. We could conclude that they give us the information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*KAtGwAHz2uh3a1BqK2XndA.png" /><figcaption>Zoomed heatmap — positive correlation to Class variable</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*eUJi7gSz_Dx4RGGf-ouSFg.png" /><figcaption>Zoomed heatmap — negative correlation to Class variables</figcaption></figure><p><em>NB: In the figure above, last Column and last Row represent the Class Variable</em></p><p>Now that we have a sense of what features have high correlation. We proceed to perform anomaly detection.</p><h4>Anomaly Detection</h4><p>In this phase, we are interested in detecting and managing any anomaly that could compromise statistical power of our model. Examples are missing values and outliers. In our dataset we do not have missing values, so we proceed to check for outliers. Outliers are data points lying abnormally/far away from overall pattern of feature distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*UEU8TgRHjvHIArYDpFwjjg.png" /><figcaption>Boxplots</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E8qG83KUIAI7AkmdEjkFkA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lpxLEi3z-Uv_kS6fhJI2Aw.png" /></figure><p>“<em>There are basically three methods for treating outliers in a data set. One method is to remove outliers as a means of trimming the data set. Another method involves replacing the values of outliers or reducing the influence of outliers through outlier weight adjustments. The third method is used to estimate the values of outliers using robust techniques.</em>” <a href="https://pdfs.semanticscholar.org/c34f/1b306d225bcf57bef83525da6e568f6381c1.pdf">Kwak &amp; Kim, 2017</a></p><p>In the second part of this blog, I will go through the approach I took to treat the outliers in the data set. Stay tuned!</p><p>You can find the notebook of this practice in my <a href="https://github.com/KhadijaMahanga/dataexploration_notebook">gitub repository</a>.</p><h4>Resources</h4><p><a href="https://www.kaggle.com/pmarcelino/comprehensive-data-exploration-with-python#COMPREHENSIVE-DATA-EXPLORATION-WITH-PYTHON">Comprehensive Data exploration in Python by Pedro Marcelino</a></p><p><a href="https://pdfs.semanticscholar.org/c34f/1b306d225bcf57bef83525da6e568f6381c1.pdf">Statistical Data Preparation by Kwak, Kim, 2017</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65f32594b645" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Latitude and Longitude data in my machine learning problem.]]></title>
            <link>https://medium.com/@khadijamahanga/using-latitude-and-longitude-data-in-my-machine-learning-problem-541e2651e08c?source=rss-a12e1b23fdb7------2</link>
            <guid isPermaLink="false">https://medium.com/p/541e2651e08c</guid>
            <category><![CDATA[women-in-tech]]></category>
            <category><![CDATA[data-scientist]]></category>
            <category><![CDATA[women-in-africa]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[geospatial-data]]></category>
            <dc:creator><![CDATA[Khadija Mahanga]]></dc:creator>
            <pubDate>Wed, 27 Mar 2019 11:52:05 GMT</pubDate>
            <atom:updated>2025-02-16T07:44:07.090Z</atom:updated>
            <content:encoded><![CDATA[<p>Early this week, I faced a machine learning problem that had Geographic data in form of coordinates (Latitude and Longitude). I could not drop those columns because I was confident that the geographical location was a good feature for my model. So I needed an approach on how I could use these data such that it won’t complicate my model. As an armature, this was my first time using geo-spatial data and I had not mastered let alone use any basic techniques working with such data.</p><p>On this short blog, I outline the different approaches I considered from different online resources and which one I ended up using.</p><ol><li><em>Choosing a model that would not require you to normalize such features</em>. You can use non-scaled features in some models such as Decision Tree, but it is very likely for the same model to improve its accuracy with scaled/normalized features. So we might as well perform feature transformation</li><li><em>Performing Reverse Geocoding. </em>You can use libraries such as <a href="https://github.com/geopy/geopy">geopy</a> and <a href="https://pypi.org/project/reverse_geocoder/">reverse_geocoder</a> to recover address from geographical location. However, Arseny writes on his medium post that the con of receiving information via HTTP, that it is not always fast and that you may reach API limits if you are working with large data. Furthermore, addresses (city, country names) may contain typos which necessitates further cleaning of your transformed data.</li><li><em>Converting geolocation data into zones. </em>You can use clustering algorithm like k-means or density based clustering algorithm to group your geo-location data (using a small number of potential clusters) and assign each cluster or a group a unique id. These unique id can then replace your latitude and longitude column.</li></ol><p>I ended up using the last the approach as it is was simpler and ideal for my problem scenario. You could also use mapping of coordinates to find distances between two coordinates and replace the geo-location columns with distance values. This of course will depend on your problem case.</p><p>Resources:</p><ol><li><a href="https://medium.com/open-machine-learning-course/open-machine-learning-course-topic-6-feature-engineering-and-feature-selection-8b94f870706a">https://medium.com/open-machine-learning-course/open-machine-learning-course-topic-6-feature-engineering-and-feature-selection-8b94f870706a</a></li><li><a href="https://stats.stackexchange.com/questions/330800/how-to-normalize-gps-coordinates-for-deep-learning">https://stats.stackexchange.com/questions/330800/how-to-normalize-gps-coordinates-for-deep-learning</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=541e2651e08c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Want to write something on tech!]]></title>
            <link>https://medium.com/@khadijamahanga/want-to-write-something-on-tech-93acad6dd1c9?source=rss-a12e1b23fdb7------2</link>
            <guid isPermaLink="false">https://medium.com/p/93acad6dd1c9</guid>
            <category><![CDATA[software-developer]]></category>
            <category><![CDATA[tanzania]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[data-scientist]]></category>
            <category><![CDATA[data-scientist-enthusiast]]></category>
            <dc:creator><![CDATA[Khadija Mahanga]]></dc:creator>
            <pubDate>Fri, 21 Sep 2018 10:45:28 GMT</pubDate>
            <atom:updated>2018-09-21T10:50:44.486Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3wESbuolUU7VWrq4MAthew.jpeg" /><figcaption>Photo by <a href="http://www.k15.photos/">K15.photos</a></figcaption></figure><p>I am a software developer, currently working as a Technologist at Code for Africa’s Dar-es-salaam lab and I have decided to write. And here is why…</p><p>I have been in the software developing space for four (4) years to date. I have participated in development of several applications (web &amp; mobile) and been exposed to different programming languages and tools. Not so long, I found deep interest in machine learning and advance data analytics and I am now keen to kick start a career as a data scientist.</p><p>I started this journey from mid last year. Customarily, I first did research on how to get there. I read plenty of articles, blogs and comments which had great information. Some wrote on skills and tools needed, some on how to learn, what to learn, where to learn, how to practice and get real life experience and so on.</p><p>“Getting a master degree” was what stood out for me initially, it was an obvious and seemed like a clean slate route. However, this step hasn’t been very easy personally. Not many institutions close to me where offering this degree and that meant searching for abroad universities. Except that fees are too high and scholarship opportunities are very competitive.</p><p>So I caved in to self learning and effective use of freely available learning platforms. I enrolled to and completed some basic online courses in the field from Udemy and Coursera such as <a href="https://www.udemy.com/certificate/UC-ABYK1636/">Big Data and Hadoop for Beginners</a>, <a href="https://www.udemy.com/certificate/UC-Y62JV0ZW/">Want to be a Data Scientist</a> and others. And I am currently doing Machine Learning course offered by Stanford University at Coursera.</p><p>I am reading one of the most recommend book in the field named “Data Science for Business: <em>What You Need to Know about Data Mining and Data-Analytic Thinking</em>” By <a href="http://www.oreillynet.com/pub/au/5828">Foster Provost</a>, <a href="http://www.oreillynet.com/pub/au/5829">Tom Fawcett</a>. It is an insightful book and I personally recommend it to other data science enthusiasts. I had signed up on Kaggle.com, a platform for data science community but I found the platform very intimidating for a beginner like me. So sadly, I haven’t been doing much there.</p><p>It has already been a year, and I honestly have made very little progress in this journey. I make excuses that there is no enough time because of my full time job. Well, they won’t be any growth if I keep up with such, and it is time to stop with excuses :) A few days ago I read a <a href="https://medium.freecodecamp.org/every-developer-should-have-a-blog-heres-why-and-how-to-stick-with-it-5fd55a247fbf?gi=f61901b64bae">medium article</a>, encouraging developers to blog. The writer was able to kick start a career through blogging, you learn faster when you journal he mentions. This moved me and sprung my decision to be here, to blog on tech!</p><p>I will blog stories on this publication that are solely data science related, sharing what I learn in the field, and how I practice with data science real life projects. I am hoping this will boost my progress in becoming a data scientist.</p><p>Watch this space!</p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93acad6dd1c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>