<?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 Wahyu Ramadhan on Medium]]></title>
        <description><![CDATA[Stories by Wahyu Ramadhan on Medium]]></description>
        <link>https://medium.com/@wahyu-ramadhan?source=rss-f79aaab49237------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GYXafk5UZH54y7RLB0gofQ.jpeg</url>
            <title>Stories by Wahyu Ramadhan on Medium</title>
            <link>https://medium.com/@wahyu-ramadhan?source=rss-f79aaab49237------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 19:36:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@wahyu-ramadhan/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[Trust the Process]]></title>
            <link>https://wahyu-ramadhan.medium.com/trust-the-process-88ff9eafe5f8?source=rss-f79aaab49237------2</link>
            <guid isPermaLink="false">https://medium.com/p/88ff9eafe5f8</guid>
            <category><![CDATA[motivation]]></category>
            <category><![CDATA[personal-growth]]></category>
            <category><![CDATA[education]]></category>
            <category><![CDATA[career-development]]></category>
            <category><![CDATA[scholarship]]></category>
            <dc:creator><![CDATA[Wahyu Ramadhan]]></dc:creator>
            <pubDate>Sat, 13 Jun 2026 10:01:02 GMT</pubDate>
            <atom:updated>2026-06-13T10:01:02.963Z</atom:updated>
            <content:encoded><![CDATA[<h4>The Chain of Failures That Ended Up Saving Me</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xPqgmpqHf2oUEuGpKp6PjQ.png" /></figure><p><em>This article was originally written in Indonesian. You can read the original version </em><a href="https://wahyu-ramadhan.medium.com/jangan-protes-pada-proses-a6f6444b21"><strong><em>here</em></strong></a><em>.</em></p><p>Halo semuanya,</p><p>A few years ago, I made a commitment to step back, keep my distance, and choose a quieter path. I became more selective about sharing personal matters publicly. Consider this article an exception, perhaps even a celebration.</p><p>There is a lot to be grateful for this year. One of the highlights is officially becoming an awardee of a scholarship program that attracts plenty of attention every year, both praise and criticism alike. To be honest, I am still not entirely comfortable calling myself an awardee. For some reason, the word still feels a little cringe.</p><p>Do not assume that I succeeded on my first attempt. This was the result of multiple applications and countless lessons learned along the way. People often say that hard work always pays off, but there was a time when I struggled to believe that. Pursuing scholarships required an enormous amount of time, energy, and persistence, which made every rejection feel like a heavy blow. Looking back, however, each failure forced me to rethink my approach and ultimately taught me something valuable.</p><p>In this article, I would like to share a few lessons that helped me throughout the scholarship journey. These reflections may not cover every aspect of the process, but they are grounded in my own experience.</p><h3>Strengthening Your Why</h3><p>People choose to pursue further education for many different reasons. Some follow the path taken by their friends, others need an advanced degree for career progression, while certain professions, such as academia or research, may require higher qualifications. None of these reasons are inherently wrong. However, if the motivation is simply, “I do not know what to do after finishing my bachelor’s degree, so I might as well continue studying,” then higher education may only serve to postpone uncertainty rather than resolve it.</p><p>My own decision to pursue further studies was largely driven by the realities of a rapidly changing world. Trends evolve quickly, industries transform constantly, and the skills that are valuable today may become outdated tomorrow. To remain relevant, we must continue adapting. For me, further education is one way to stay relevant by deepening my knowledge and developing expertise in a field that genuinely interests me.</p><p>Bootcamps and similar programs can certainly provide practical skills. However, they do not always offer the theoretical foundation necessary to fully understand core concepts and apply them across different contexts. In addition, the quality and credibility of bootcamps can vary significantly depending on the provider and instructors. For those reasons, I chose to continue my education through a formal academic program.</p><p>Imagine that I work as an investment manager responsible for analyzing financial instruments and developing portfolio strategies. Through that work, I may have access to demographic information such as age, income, occupation, and geographic location. Those insights could reveal, for example, that many people still lack awareness of the importance of investing.</p><p>The challenge is not identifying the problem. The challenge is knowing how to solve it. That is where further education becomes valuable. By strengthening my expertise, I can better understand the problem, design more effective solutions for clients, and help improve financial literacy among the broader public. Whether that knowledge is later applied as an academic or a practitioner is ultimately a matter of personal preference.</p><h3>Relevance Is the Key</h3><p>Most scholarship programs require applicants to submit an essay or motivation letter as one of the core application documents. This is your opportunity to showcase your strengths and explain the problem you hope to address through further education. It may be connected to your future plans, career aspirations, or a challenge you genuinely care about. Ultimately, the scholarship provider needs to be convinced that you are a worthy candidate.</p><p>Trust me, you will never run out of topics to write about. However, after experiencing multiple rejections, there is one piece of advice I would give: do not force yourself to think exclusively in grand, national-scale narratives. You do not need to position yourself as someone who will single-handedly transform the country. Instead, focus on problems that are closely related to your daily work, experiences, or areas of expertise. In my experience, this makes your story more authentic and much easier to elaborate on during interviews, where many questions are often drawn directly from your motivation letter.</p><p>The interview stage can be particularly challenging because interviewers are skilled at asking difficult and sometimes unexpected questions. This was the biggest obstacle in several of my applications. Even after participating in numerous mock interviews, I still struggled. Ironically, I only started succeeding after changing my approach. When you speak about something you genuinely work on and understand, your answers come more naturally. The experience stays with you, making it easier to respond with confidence and clarity during the interview.</p><h3>The Journey and Patience</h3><p>Preparing a scholarship application is rarely a straightforward process. At times, it can feel like you are holding scattered pieces of information without knowing where to begin. Then come the doubts: “Am I really capable of this?” Some days you feel highly motivated and confident. On others, uncertainty takes over. In many ways, the process resembles putting together a puzzle. Every piece matters, even when its importance is not immediately obvious.</p><p>Pursuing a scholarship is not about perfection. It is about persistence. Moving slowly does not mean you are falling behind, and moving quickly does not necessarily mean you are ahead. Everyone reaches the finish line at the right time.</p><p>One of the first things I did was learn everything I could about the scholarship itself, including the timeline, requirements, and overall objectives. This basic understanding helped me set priorities and plan my preparation accordingly. Requirements such as TOEFL or IELTS scores, as well as recommendation letters, are rarely things that can be completed within a week or two. In my opinion, a realistic scholarship preparation period is at least six to seven months. Giving yourself enough time allows for thorough preparation, while rushing the process often increases the likelihood of failure.</p><h3>Growing Through Community</h3><p>It is incredibly difficult to navigate such an uncertain journey alone. At some point, we all need guidance from people who have already gone through the process. Fortunately, there are now many scholarship communities, and perhaps even organizations, dedicated to helping applicants. Some are completely free, while others operate as paid programs. Many of them offer mentoring as part of their support. My personal recommendation is to start with the free communities, as they already provide tremendous value. Unless, of course, you have the budget and prefer additional services.</p><p>Mentoring is about much more than simply receiving advice. Most mentors are scholarship awardees themselves, which means they understand the challenges applicants face at each stage of the selection process. For me, this support was invaluable because some aspects of preparation are difficult to tackle alone. Mock interviews are a good example. Practicing interview questions is far more effective when there is another person challenging your answers and providing feedback.</p><p>I have great respect for people who dedicate their time to mentoring programs. Now that I occasionally find myself in a similar position, I realize how much effort it requires. Personally, I was fortunate to have a close friend who became an incredibly reliable partner throughout my preparation. In particular, we conducted mock interviews over and over again. And when I say over and over, I mean dozens of times, to the point where even I became tired of hearing my own answers.</p><p>Speaking of scholarship communities founded by awardees, I have mixed feelings about programs that heavily monetize the experience. This is simply my personal view. If someone uses their experience to educate and inspire others, that is perfectly reasonable. However, I believe there should be a balance between contribution and commercialization, especially when the opportunity itself was made possible through public funding. That is why I usually encourage applicants to explore free communities first before considering paid alternatives.</p><h3>Risk Mitigation</h3><p>As I mentioned earlier, uncertainty is one of the greatest challenges in the scholarship application process. We never truly know whether we will be selected, nor do we fully understand the criteria that matter most to the selection committee. The most practical strategy is to focus on what we can control: our preparation, effort, and personal growth, rather than outcomes that are ultimately beyond our control.</p><p>It is also important to think about how you will respond if things do not go as planned. I say this as someone who has experienced the feeling of being so close, yet so far, more than once. Mentors can be one of your most valuable resources, so make the most of them. After a rejection, especially during the interview stage, take the time to discuss your performance and evaluate what could be improved. Sometimes a different perspective is all it takes to uncover something you may have overlooked.</p><p>Feeling sad or disappointed after a rejection is completely normal. What matters is how we respond to those emotions. Learn to embrace failure as part of the process. As the saying goes, it is just a bad day, not a bad life. Every setback offers an opportunity to learn, become more resilient, and recognize areas where we can still improve. More importantly, it gives us the chance to come back stronger, whether that means applying to a different scholarship program or trying again in the next cycle of the same one.</p><h3>Stubborn or Consistent?</h3><p>There are times when we become a little too confident in ourselves. We complete all the administrative requirements, polish what we believe is the perfect motivation letter, and find mentors we trust. I have been there myself, perhaps more than once. I became convinced that all the preparation I had done would inevitably lead to success. But reality had other plans. I failed.</p><p>Failure was what taught me the importance of managing expectations, staying humble, and being willing to accept criticism. It was also when I learned the difference between consistency and stubbornness. Consistency means continuing to move forward while adapting and improving your approach. Stubbornness means insisting on methods that no longer work and repeating the same mistakes over and over again. Understanding that distinction makes us more adaptable, more self-aware, and better equipped to recognize our own limits.</p><h3>Conquering Yourself</h3><p>Throughout my scholarship journey, I attended numerous sharing sessions organized by scholarship communities and awardees. While they provided a wealth of useful information, they also had an unintended side effect: they made me question my own achievements. Many of the people I met had accomplishments that extended far beyond regional or national recognition. Some had built impressive international portfolios. It is hard not to feel intimidated when surrounded by people like that.</p><p>Remember the uncertainty I mentioned earlier? Believe it or not, I once came across an education influencer who was not selected for a scholarship despite having completed their undergraduate degree abroad on a scholarship and possessing an extraordinary list of achievements. Experiences like that reinforced a simple reality: none of us truly knows what selection committees are looking for.</p><p>I only fully understood this after becoming an awardee myself and meeting many other recipients during an orientation program. We all came from different backgrounds. Some were fresh graduates, others were full-time professionals like me, and some had even resigned from their jobs to focus entirely on scholarship applications. In other words, each of us started from a different place. That is why comparing ourselves to others rarely makes sense. No matter how modest our achievements may seem or how simple our plans appear on paper, they may carry far more value than we realize.</p><h3>Trust the Process</h3><p>I have always pushed myself to maintain a fast pace, and my scholarship journey was no exception. With targets to achieve and deadlines to meet, I became overly serious and spent a long time living under pressure, much of which I had created for myself. In the process, I neglected something equally important: happiness and balance. I overlooked parts of life that mattered, including friendships, personal interests, and moments of simple enjoyment.</p><blockquote>Sometimes the best advice is surprisingly simple: take it easy.</blockquote><p>It sounds insignificant, perhaps even obvious, yet it is one of the things we forget most often and struggle the most to practice. Every now and then, we need to give ourselves permission to pause, catch our breath, and step back for a moment. I believe this is closely connected to managing expectations and learning to enjoy the journey itself. When we take care of our emotional well-being, it naturally shows in the way we carry ourselves, including during interviews. Positive energy is difficult to fake, and people tend to notice it.</p><p>This is not about taking the process lightly. Rather, it is about recognizing that scholarship success or failure should never be treated as the ultimate goal. They are outcomes, not destinations. They are simply the consequences of the actions we take throughout the journey. Besides, a scholarship is only one of countless possibilities that life may offer.</p><p>So do not rush yourself. Trust the process and continue giving your best. Progress may be slow, but meaningful growth rarely happens overnight. If we remain committed to the process, positive outcomes have a way of following.</p><p><em>Note: This article is based entirely on my personal experience. Every individual’s journey is different, and others may hold different perspectives. My intention is neither to offend nor diminish anyone’s experience. I simply hope these reflections offer useful insights for those navigating a similar path.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88ff9eafe5f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Avoiding Dependency Hell with Collaborative Geospatial Workflows in Google Colab]]></title>
            <link>https://medium.com/design-bootcamp/avoiding-dependency-hell-with-collaborative-geospatial-workflows-in-google-colab-3b0b0d17e6f0?source=rss-f79aaab49237------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b0b0d17e6f0</guid>
            <category><![CDATA[gis]]></category>
            <category><![CDATA[google-colab]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[remote-sensing]]></category>
            <dc:creator><![CDATA[Wahyu Ramadhan]]></dc:creator>
            <pubDate>Sat, 06 Jun 2026 10:01:07 GMT</pubDate>
            <atom:updated>2026-06-06T12:10:34.288Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>How to choose the right collaboration tools based on your needs and project complexity</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8vfdvDzgqjiaiWpikJhIxA.png" /><figcaption>Created with Your <a href="https://science.nasa.gov/specials/your-name-in-landsat/">Name In Landsat</a></figcaption></figure><p>Halo semuanya,</p><p>Google Earth Engine (GEE) was my gateway into the world of geospatial data science. Over time, however, I found that the closed sandbox nature of the GEE Code Editor limited my flexibility. For example, when a specific function or algorithm is not available in the GEE library, the only option is often to implement it from scratch. This is quite different from Python’s open-source ecosystem, where a vast range of libraries can be easily imported and integrated into your workflow.</p><p>One downside of Python’s flexibility is the need for some initial setup, such as installing an IDE (e.g., VS Code with the Jupyter extension) and the required libraries. Another option is to use Anaconda, which comes bundled with Python and a wide range of commonly used packages. Of course, this only applies when working on a local machine. Is there a less cumbersome alternative? Absolutely. One of the most popular options is a cloud-based environment such as Google Colaboratory.</p><p>Today, Google Colaboratory (Colab) has become a popular choice for people who prefer working in the cloud. One of its biggest advantages is that it removes much of the hassle associated with environment setup, particularly dependency hell and package conflicts, which have long been a source of frustration for Python users. Still, I have always been curious about one thing: beyond serving as an IDE, how well does Colab support collaborative workflows?</p><h3>Background</h3><h4>What is Google Colaboratory?</h4><p>In short, Colab is a cloud-based Jupyter Notebook environment provided by Google. It allows users to write and run Python code directly in a web browser without the need for local installation. Colab also supports other programming languages such as R and Julia. Each session runs on a virtual machine hosted on Google’s infrastructure, with optional access to CPUs, GPUs, and TPUs for more demanding workloads such as machine learning and deep learning.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F5sgJsCah9bs%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D5sgJsCah9bs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F5sgJsCah9bs%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/af4b7cae7bf44b808e0109f65701ace9/href">https://medium.com/media/af4b7cae7bf44b808e0109f65701ace9/href</a></iframe><h4>Its Role in Geospatial Data Science</h4><p>For those of us working in the geospatial domain, Colab helps address at least two common challenges in our daily workflow: computing resources and environment setup. Similar to GEE, computations are performed in the cloud, although the free tier comes with certain limitations. On the environment side, Colab includes several pre-installed Python libraries such as pandas and NumPy, while additional packages for geospatial analysis can be easily installed using pip.</p><figure><img alt="A variety of Python libraries covering different aspects of geospatial analysis, including vector and raster processing, map visualization, and GeoAI. An equally important aspect not shown here is integration with cloud-based data sources such as Google Earth Engine (ee) and Google BigQuery, which enables querying massive spatial SQL databases." src="https://cdn-images-1.medium.com/max/800/0*pjCFOYIyREb38kEs" /><figcaption>Python libraries for Geospasial Analysis (<a href="https://www.linkedin.com/posts/geospatial-python-remotesensing-share-7342843310606073857-dHrb/?utm_source=share&amp;utm_medium=member_desktop&amp;rcm=ACoAACf9bGUBUx60MaYSnMXtERvs-uqeawu_LSo">source</a>)</figcaption></figure><p>Another advantage is its seamless integration with the Google ecosystem. Colab can be connected to Google Drive, allowing users to access stored data much like they would on a local machine. Sharing is also straightforward. Simply send a link, and others can access the same environment, scripts, and workflow without any additional setup.</p><h3>Strengths and Limitations</h3><h4>Strengths</h4><ul><li><strong>GPU and TPU support:</strong> This is a major advantage, especially for deep learning applications involving imagery, as it can significantly accelerate iterative and parallel processing tasks.</li><li><strong>Zero setup:</strong> Anyone can open and run a notebook directly from a web browser, regardless of the device they are using.</li><li><strong>Real-time co-editing:</strong> Similar to Google Docs, multiple users can view, comment on, and edit the same notebook simultaneously.</li><li><strong>Easy sharing:</strong> Notebooks can be shared through a simple link with configurable permissions, including view, comment, and edit access.</li></ul><h4>Limitations</h4><ul><li><strong>Session timeout:</strong> On the free tier, the runtime is disconnected after approximately 90 minutes of inactivity. This means users must start a new session and re-run any pip install commands to restore the required Python libraries in the environment.</li><li><strong>The downside of real-time co-editing:</strong> Unlike Git, simultaneous edits to the same cell by multiple users can lead to unpredictable results. There is no built-in version conflict resolution mechanism comparable to what Git provides.</li><li><strong>No enforced cell execution order:</strong> Users can execute cells in any order, which may lead to inconsistencies and make debugging more difficult. That said, this is a common challenge in Jupyter-based workflows rather than a limitation specific to Colab.</li></ul><h3>Collaboration Options for Geospatial Workflows</h3><p>This is the core of the article: exploring several approaches to collaboration in Colab. I will start with the simplest options and gradually move toward more production-grade solutions. Each approach is discussed in the context of geospatial workflows.</p><h4>Google Drive with Shared Folders or File IDs</h4><p>This is arguably the most accessible approach. By mounting Google Drive in Colab, users can access shared datasets stored in team folders. Data can also be accessed directly using file or folder IDs obtained from Drive links shared by team members.</p><pre># Mount Drive<br>from google.colab import drive<br>drive.mount(&#39;/content/drive&#39;)<br><br>import geopandas as gpd<br>gdf = gpd.read_file(&#39;/content/drive/Shareddrives/1aBcDeFgHiJkLmNoPqRsTuVwXyZ123456/area.geojson&#39;)</pre><p>If you need to access a specific file without specifying the full folder path, you can use gdown and retrieve the file directly using its ID.</p><pre>import gdown<br><br>file_id = &quot;1xYzAbCdEfGhIjKlMnOpQrStUvWx789012&quot;<br>gdown.download(f&quot;https://drive.google.com/uc?id={file_id}&quot;, &quot;area.geojson&quot;)<br><br>gdf = gpd.read_file(&quot;area.geojson&quot;)</pre><p>gdown can also be used for batch processing. The difference is that, instead of a file ID, you use a folder ID together with the download_folder function.</p><pre>folder_id = &quot;1aBcDeFgHiJkLmNoPqRsTuVwXyZ123456&quot;<br>gdown.download_folder(f&quot;https://drive.google.com/drive/folders/{folder_id}&quot;, output=&quot;/content/geo_data/&quot;)</pre><p>Keep in mind that files downloaded via gdown are stored in Colab&#39;s temporary directory (/content/) rather than in Google Drive. As a result, those files will be lost once the session ends. To preserve them, be sure to export the outputs to your mounted Drive before the session expires.</p><figure><img alt="The red-highlighted area represents Colab’s temporary directory. Any files or folders downloaded during a session are stored there and will be removed once the session ends or is reset. In contrast, the drive directory refers to Google Drive that has been mounted to the Colab session." src="https://cdn-images-1.medium.com/max/418/1*q7OFJ8t85Jy70YmIHnNnlw.png" /><figcaption>Temporary directory in Colab</figcaption></figure><p>In most cases, setting General Access to <strong>Viewer</strong> with a restricted link is sufficient, whether for a folder or an individual file. Change the permission to <strong>Editor</strong> only when someone needs to upload files or export outputs back to the shared folder.</p><figure><img alt="Google Drive General Access dropdown menu showing options for Restricted, but you can change into Viewer, Commenter, and Editor permissions." src="https://cdn-images-1.medium.com/max/499/1*Eq9NDmBJ_Pw2kDP4-KO98A.png" /><figcaption>General Access in settings Google Drive</figcaption></figure><h4>GitHub for Code and Small Datasets</h4><p>GitHub is a common choice for individuals and teams who want more efficient version tracking for their notebooks and scripts. A repository can be cloned directly into a Colab session for development and analysis.</p><pre>!git clone https://github.com/your-org/geo-project.git<br>%cd geo-project</pre><p>In my experience, small vector and raster datasets can still be stored alongside scripts in the repository. For larger files, however, it is usually better to store them elsewhere, such as Google Drive. Using GitHub also enables code reviews through pull requests, which can be particularly useful when multiple people are working on the same pipeline. Be sure to include a requirements.txt file that specifies the required libraries and their versions.</p><pre># Install requirements to ensure everyone runs the exact same package versions<br># Regardless of when they start their session<br>!pip install -r requirements.txt</pre><h3>Google Earth Engine API and Assets</h3><p>The Python module for accessing Google Earth Engine, ee, comes pre-installed in Colab. Simply import the package and authenticate using your own Google account.</p><pre>import ee<br><br>ee.Authenticate()<br>ee.Initialize(project=&#39;your-project-id&#39;)<br><br>image = ee.ImageCollection(&#39;COPERNICUS/S2_SR&#39;) \<br>    .filterDate(&#39;2026-01-01&#39;, &#39;2026-06-01&#39;) \<br>    .filterBounds(ee.Geometry.Point([112.6, -7.9]))  # East Java for example</pre><p>The collaboration workflow typically looks like this:</p><ol><li>One team member creates a GEE Cloud Project.</li><li>Team members are invited through Google Cloud Console by adding their Google accounts to the project.</li><li>Each member authenticates using ee.Authenticate() and initializes the same project with ee.Initialize(project=&#39;your-project-id&#39;).</li><li>Team members do not need to use the same Google account. Once access is granted, all project assets and exported outputs can be accessed by everyone within the project.</li></ol><p>As shown in the code example below, exports can be saved either as GEE Assets or to a shared folder in Google Drive.</p><pre># Export to shared project assets<br>task = ee.batch.Export.image.toAsset(<br>    image=image,<br>    description=&#39;s2_export&#39;,<br>    assetId=&#39;projects/your-project-id/assets/s2_result&#39;<br>)<br>task.start()<br><br># Fallback: export to shared Google Drive folder<br>task = ee.batch.Export.image.toDrive(<br>    image=image,<br>    description=&#39;s2_export&#39;,<br>    folder=&#39;shared_folder&#39;,<br>    fileNamePrefix=&#39;s2_result&#39;,<br>    scale=10,<br>    region=geometry<br>)<br>task.start()</pre><h4>Cloud Storage (Google Cloud Storage or AWS S3)</h4><p>This approach becomes more relevant when working with larger teams or when the workflow is intended for production environments. Some of the key advantages include:</p><ol><li><strong>Scalability:</strong> Cloud storage can accommodate datasets at the petabyte scale, unlike Google Drive, which comes with storage limitations.</li><li><strong>Cost efficiency:</strong> Services typically follow a pay-as-you-go model, meaning you only pay for the resources you actually use.</li><li><strong>Automation support:</strong> Cloud storage integrates well with event-driven pipelines. For example, the arrival of a new dataset can automatically trigger a processing workflow without manual intervention.</li><li><strong>Enhanced security:</strong> Access can be managed through Identity and Access Management (IAM). For instance, a user can be granted permission to upload data while being restricted from deleting it. This provides much finer control than the typical viewer/editor permissions available in Google Drive.</li><li><strong>Durability and performance:</strong> Data is automatically replicated across multiple locations to minimize the risk of loss. Cloud storage also offers high transfer throughput, making it well suited for processing large numbers of files in parallel.</li></ol><p>In short, Google Drive is convenient for sharing, whereas cloud storage is designed for workflows that require large-scale and recurring data movement.</p><pre># Google Cloud Storage<br>!gsutil cp gs://your-bucket/data.tif /content/data.tif<br><br># AWS S3<br>import boto3<br>s3 = boto3.client(&#39;s3&#39;)<br>s3.download_file(&#39;your-bucket&#39;, &#39;data.tif&#39;, &#39;/content/data.tif&#39;)py</pre><h3>PostGIS or Cloud Databases</h3><p>If you are working with large and frequently updated datasets, especially vector data, this is likely the better option. I am not yet confident enough to say whether PostGIS is the optimal solution for large raster datasets, but for vector data, there are several clear advantages:</p><ol><li><strong>Spatial queries for vector data:</strong> Operations such as filtering by bounding box, spatial joins, intersections, and other spatial analyses can be performed directly within the database. These capabilities are not available natively in cloud storage.</li><li><strong>Support for dynamic data:</strong> When a dataset is updated, everyone automatically accesses the latest version without needing to re-download the data.</li><li><strong>Simultaneous editing:</strong> Multiple team members can work with the same data concurrently without concerns about locked files or file corruption. In contrast, cloud storage is more prone to conflicts because it primarily stores static files.</li></ol><pre>import geopandas as gpd<br>from sqlalchemy import create_engine<br><br>engine = create_engine(&quot;postgresql://user:pass@host:5432/geodb&quot;)<br>gdf = gpd.read_postgis(&quot;SELECT * FROM districts&quot;, engine, geom_col=&#39;geometry&#39;)</pre><h3>Which Option Is Right for You?</h3><p>In practice, teams often combine multiple approaches depending on data volume and workflow complexity. As workflows become more automated and data volumes grow, the setup tends to become more complex as well, often requiring a combination of several solutions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*UM1Oqfuq_fj1Ju0lUVMbOw.png" /><figcaption>Setup complexity of each option</figcaption></figure><p>A common starting point is to use Google Drive and GitHub when the team and project requirements are still relatively small. As data volume and operational needs increase, teams can gradually migrate toward cloud storage solutions.</p><h3>Conclusion</h3><p>Colab is not a replacement for a full collaborative development environment. Instead, it helps bridge the gap for those who need an accessible cloud-based Python notebook platform. The key is understanding which collaboration approach best fits your data volume and workflow complexity. By choosing the right setup, teams can collaborate more effectively while avoiding frustration caused by conflicting notebook states, corrupted files, or missing data.</p><p>To conclude, here is a practical guide for choosing the right collaboration stack in Colab:</p><ul><li><strong>Small teams working on research or exploratory projects:</strong> Use Google Drive for data storage, GitHub for scripts and code, GEE for imagery access and processing, and external APIs when additional data sources are needed.</li><li><strong>Teams with more mature or structured workflows:</strong> Add cloud storage services such as Google Cloud Storage or Amazon S3 for raster data while continuing to use GitHub for version control.</li><li><strong>Production-oriented teams:</strong> Use cloud storage for raster datasets, PostGIS for vector data and spatial queries, GitHub for code management, and GEE for large-scale imagery processing.</li></ul><h3>References</h3><ul><li><a href="https://colab.research.google.com/">https://colab.research.google.com/</a></li><li><a href="https://developers.google.com/colab">https://developers.google.com/colab</a></li><li><a href="https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb">https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb</a></li><li><a href="https://www.youtube.com/watch?v=-Z43Xx6X6wE">https://www.youtube.com/watch?v=-Z43Xx6X6wE</a></li><li><a href="https://colab.research.google.com/github/opengeos/leafmap/blob/master/docs/notebooks/14_postgis.ipynb">https://colab.research.google.com/github/opengeos/leafmap/blob/master/docs/notebooks/14_postgis.ipynb</a></li><li><a href="https://colab.research.google.com/github/bytehub-ai/code-examples/blob/main/tutorials/04_using_cloud_storage.ipynb">https://colab.research.google.com/github/bytehub-ai/code-examples/blob/main/tutorials/04_using_cloud_storage.ipynb</a></li><li><a href="https://colab.research.google.com/drive/12pxf4gDHfKpWrLUR97URpUoXlb-94-pd?usp=sharing">https://colab.research.google.com/drive/12pxf4gDHfKpWrLUR97URpUoXlb-94-pd?usp=sharing</a></li><li><a href="https://python.plainenglish.io/how-to-load-data-from-aws-s3-into-google-colab-7e76fbf534d2">https://python.plainenglish.io/how-to-load-data-from-aws-s3-into-google-colab-7e76fbf534d2</a></li></ul><p><a href="http://linkedin.com/in/mwahyur"><strong>Connect with me</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b0b0d17e6f0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/design-bootcamp/avoiding-dependency-hell-with-collaborative-geospatial-workflows-in-google-colab-3b0b0d17e6f0">Avoiding Dependency Hell with Collaborative Geospatial Workflows in Google Colab</a> was originally published in <a href="https://medium.com/design-bootcamp">Bootcamp</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Collaborative Geospatial Workflow di Google Colab untuk Menghindari Dependency Hell]]></title>
            <link>https://wahyu-ramadhan.medium.com/collaborative-geospatial-workflow-di-google-colab-untuk-menghindari-dependency-hell-60b6128b499e?source=rss-f79aaab49237------2</link>
            <guid isPermaLink="false">https://medium.com/p/60b6128b499e</guid>
            <category><![CDATA[remote-sensing]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[gis]]></category>
            <category><![CDATA[google-colab]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Wahyu Ramadhan]]></dc:creator>
            <pubDate>Thu, 04 Jun 2026 10:01:07 GMT</pubDate>
            <atom:updated>2026-06-21T03:51:10.678Z</atom:updated>
            <content:encoded><![CDATA[<h4>Cara memilih tools kolaborasi yang tepat sesuai kebutuhan dan kompleksitas pekerjaan</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RK4bHJ82TflfcHTQtEjURQ.png" /><figcaption>Dibuat dengan <a href="https://science.nasa.gov/specials/your-name-in-landsat/">Your Name In Landsat</a></figcaption></figure><p>Halo semuanya,</p><p>Google Earth Engine (GEE) menjadi langkah awal saya tertarik kepada domain <em>geospatial data science</em>. Meskipun makin kesini saya merasa konsep <em>closed sanbox</em> dari Code Editor-nya GEE tidak memberi saya keleluasaan. Misalnya jika tidak ada fungsi atau algoritma tertentu di <em>library</em> GEE, maka mau tidak mau harus membuatnya sendiri. Beda dengan ekosistem <em>open-soure </em>dari Python yang memungkinkan kita mengimpor berbagai <em>library</em>.</p><p>Konsekuensi dari kemudahan Python adalah harus melakukan <em>environment setup</em> di awal, seperti <em>install </em>IDE (cth: VSCode + Jupyter Extension) serta <em>library</em> yang dibutuhkan. <em>Install </em>Anaconda yang sudah <em>include </em>paket Python yang lengkap juga bisa diambil sebagai pilihan. Oh ya, barusan adalah konteksnya apabila bekerja di <em>local</em> atau <em>desktop</em>. Apakah ada opsi yang lebih tidak merepotkan lagi? Tentu saja ada, salah satu contoh populernya adalah <em>cloud-based environment</em> seperti Google Colaboratory.</p><p>Saat ini Google Colaboratory (Colab) telah menjadi pilihan praktis bagi banyak orang yang ingin bekerja melalui <em>cloud</em>. Alasannya adalah tidak perlu pusing soal <em>environment setup </em>khususnya <em>dependency hell </em>atau risiko terjadi ketidaksesuaian (<em>conflict</em>)<em> </em>antar paket yang selama ini menjadi semacam ‘kutukan’. Namun sebetulnya saya masih penasaran, disamping peran sebagai IDE, bagaimana kemampuan Colab dalam <em>collaborative workflow</em>?</p><h3>Latar Belakang</h3><h4>Apa itu Google Colaboratory?</h4><p>Singkatnya Colab adalah <em>cloud-based</em> Jupyter Notebook <em>environment</em> yang disediakan oleh Google. Kita dapat menulis dan menjalankan Python (juga mendukung bahasa pemrogramanR dan Julia) langsung pada browser tanpa instalasi di <em>local</em>. Tiap <em>session</em> berjalan pada <em>virtual machine </em>dari infrastruktur Google yang juga menyediakan opsi CPU, GPU dan/atau TPU untuk kebutuhan tambahan seperti Machine Learning serta Deep learning.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F5sgJsCah9bs%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D5sgJsCah9bs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F5sgJsCah9bs%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/af4b7cae7bf44b808e0109f65701ace9/href">https://medium.com/media/af4b7cae7bf44b808e0109f65701ace9/href</a></iframe><h4>Peran dalam Geospatial Data Science</h4><p>Bagi saya yang berada dalam domain geospasial, setidaknya Colab memecahkan dua hambatan pada <em>daily workflow</em> yakni komputasi dan <em>environment setup</em>. Sama seperti GEE, komputasi dilakukan secara <em>cloud</em> dengan catatan versi gratisnya punya kemampuan yang terbatas. Soal <em>environment,</em> Colab punya <em>pre-installed</em> Python <em>library</em> seperti pandas dan numpy serta dapat ditambahkan lagi yang lain untuk kebutuhan geospasial via pip.</p><figure><img alt="Berbagai library Python untuk berbagai aspek geospasial, seperti analisis vektor/raster, visualisasi peta hingga GeoAI. Meskipun ada aspek tidak kalah penting yang belum disebutkan yakni integrasi dengan cloud data, misalnya Google Earth Engine (ee) dan Google BigQuery (query massive spatial SQL database)" src="https://cdn-images-1.medium.com/max/800/0*pjCFOYIyREb38kEs" /><figcaption>Berbagai Python library untuk Analisis Geospasial (<a href="https://www.linkedin.com/posts/geospatial-python-remotesensing-share-7342843310606073857-dHrb/?utm_source=share&amp;utm_medium=member_desktop&amp;rcm=ACoAACf9bGUBUx60MaYSnMXtERvs-uqeawu_LSo">sumber</a>)</figcaption></figure><p>Satu lagi, karena masih dalam ekosistem Google, Colab dapat dihubungkan dengan Google Drive untuk membaca data yang tersimpan layaknya bekerja di <em>local</em>. Mekanisme <em>sharing</em> juga mudah, tinggal kirim <em>link</em> maka seseorang akan mendapatkan <em>environment</em>, <em>script</em>, dan <em>workflow</em> yang sama tanpa <em>setup </em>apa pun.</p><h3>Kelebihan dan Kekurangan</h3><h4>Kelebihan</h4><ul><li><strong>GPU dan TPU</strong>: Bagi saya ini adalah sebuah keunggulan karena akan membantu <em>iterative</em>/<em>parallel processing </em>jika tujuannya <em>deep learning </em>pada citra.</li><li><strong><em>Zero setup</em></strong>: Semua orang dapat membuka dan menjalankannya melalui browser dari berbagai jenis <em>device</em>.</li><li><strong><em>Real-time co-editing</em></strong>: Prinsipnya mirip seperti Google Docs yang mendukung lebih dari satu orang dapat melihat, <em>comment, </em>dan edit dalam satu notebook pada waktu yang bersamaan.</li><li><strong>Mekanisme <em>sharing</em></strong>: Kita dapat berbagi notebook hanya dari link dengan <em>permissons</em> entah untuk edit, <em>view</em> dan/atau <em>comment</em>.</li></ul><h4>Kekurangan</h4><ul><li><strong>Session time out</strong>: <em>Tier </em>gratis akan terputus (<em>runtime disconnected</em>) setiap 90 menit apabila tidak ada aktivitas sama sekali pada Notebook yang kita buka. Jadi harus mengulang <em>session </em>dari awal. <em>User</em> harus <em>re-run </em>pip install setiap kali <em>session</em> berakhir untuk <em>install </em>Python<em> library</em> kembali ke <em>environment</em>.</li><li><strong>Konsekuensi <em>Real-time co-editing</em></strong>: Tidak seperti Git, jika lebih dari satu orang melakukan editing sebuah cell secara bersamaan, hasilnya bisa susah diprediksi. Maksud saya tidak ada <em>version conflict resolution</em> seperti pada Git.</li><li><strong>Tidak ada <em>cell execution order</em></strong>: Maksudnya adalah <em>user </em>dapat menjalankan <em>cell</em> dengan tidak berurutan, hal ini menyebabkan inkonsistensi dan susah untuk mengatasi <em>error</em>. Meski sebetulnya ini merupakan masalah umum dalam <em>workflow </em>berbasis Jupyter.</li></ul><h3>Opsi Kolaborasi untuk Workflow Geospasial</h3><p>Berikut ini adalah inti dari artikel ini yakni elaborasi beberapa jalan untuk kolaborasi dalam Colab. Saya akan mulai dari yang sederhana hingga orientasinya adalah <em>production-grade.</em> Masing-masing disesuaikan dengan konteks geospasial.</p><h4>Google Drive dengan Shared Folder atau File ID</h4><p>Cara ini adalah yang paling <em>accessible</em>, hanya dengan <em>mount</em> Google Drive ke dalam Colab untuk dapat mengakses <em>shared datasets</em> melalui jalur folder tim. Lalu kita juga bisa mengakses langsung melalui ID file dan/atau folder yang berasal dari <em>link</em> Drive yang sudah dibagikan anggota tim.</p><pre># Mount Drive<br>from google.colab import drive<br>drive.mount(&#39;/content/drive&#39;)<br><br>import geopandas as gpd<br>gdf = gpd.read_file(&#39;/content/drive/Shareddrives/1aBcDeFgHiJkLmNoPqRsTuVwXyZ123456/area.geojson&#39;)</pre><p>Tapi jika ingin mengambil file yang spesifik tanpa harus mencantumkan <em>path </em>dari folder secara lengkap, gunakan gdown untuk mengambil ID tersebut.</p><pre>import gdown<br><br>file_id = &quot;1xYzAbCdEfGhIjKlMnOpQrStUvWx789012&quot;<br>gdown.download(f&quot;https://drive.google.com/uc?id={file_id}&quot;, &quot;area.geojson&quot;)<br><br>gdf = gpd.read_file(&quot;area.geojson&quot;)</pre><p>gdown juga bisa dipakai untuk <em>batch processing</em>, bedanya adalah ambil folder ID menggunakan download_folder.</p><pre>folder_id = &quot;1aBcDeFgHiJkLmNoPqRsTuVwXyZ123456&quot;<br>gdown.download_folder(f&quot;https://drive.google.com/drive/folders/{folder_id}&quot;, output=&quot;/content/geo_data/&quot;)</pre><p>Perhatikan bahwa file yang diambil via gdown akan masuk ke direktori temporary pada Colab (/content/), bukan di Drive. Artinya ketika <em>session </em>berakhir, maka file tersebut juga hilang. Maka perlu diekspor dahulu ke dalam <em>mounted </em>Drive setelah pemrosesan.</p><figure><img alt="Area warna merah adalah bagian temporary directory dari Colab, saat coba mengambil file atau folder, maka akan terunduh di area tersebut. Saat sesi berakhir, akan hilang atau reset. Sedangkan ‘drive’ adalah Drive yang telah di Mount pada session." src="https://cdn-images-1.medium.com/max/418/1*q7OFJ8t85Jy70YmIHnNnlw.png" /><figcaption>Direktori sementara dari Colab</figcaption></figure><p>Pengaturan General Access sebetulnya cukup sebagai <em>Viewer </em>dengan <strong>restricted link</strong>, baik pada folder atau file. Ubah menjadi <em>Editor</em> hanya jika ada seseorang yang perlu <em>upload</em> atau <em>export</em> kembali ke <em>shared folder</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*Eq9NDmBJ_Pw2kDP4-KO98A.png" /><figcaption>General Access pada Google Drive</figcaption></figure><h4>GitHub untuk Kode dan Data Berukuran Kecil</h4><p>GitHub adalah pilihan umum jika seseorang atau tim ingin memiliki efisiensi <em>version tracking </em>terhadap notebook atau script mereka dengan. Kita dapat <em>clone repository</em> secara langsung ke dalam <em>session </em>Colab<em>.</em></p><pre>!git clone https://github.com/your-org/geo-project.git<br>%cd geo-project</pre><p>Berdasarkan pengalaman, data vektor dan raster berukuran kecil masih dapat disimpan di <em>repository </em>bersama dengan script Sedangkan file yang lebih besar, rasanya lebih baik disimpan di tempat lain, misalnya Drive. Opsi GitHub ini memungkinkan <em>code review</em> melalui <em>pull request</em>, yang berguna ketika beberapa orang bekerja pada <em>pipeline </em>yang sama. Pastikan bahwa dalam <em>repository </em>terdapat requirements.txt berisi versi dan daftar <em>library </em>yang harus di-<em>install</em>.</p><pre># Install requirements to ensure everyone runs the exact same package versions<br># Regardless of when they start their session<br>!pip install -r requirements.txt</pre><h4>Google Earth Engine API dan/atau Assets</h4><p>Modul Python untuk akses GEE yaitu ee sudah <em>pre-installed</em> di Colab, tinggal masukkan perintah import saja. Setelahnya diperlukan autentikasi menggunakan akun Google masing-masing.</p><pre>import ee<br><br>ee.Authenticate()<br>ee.Initialize(project=&#39;your-project-id&#39;)<br><br>image = ee.ImageCollection(&#39;COPERNICUS/S2_SR&#39;) \<br>    .filterDate(&#39;2026-01-01&#39;, &#39;2026-06-01&#39;) \<br>    .filterBounds(ee.Geometry.Point([112.6, -7.9]))  # East Java for example</pre><p>Alur kolaborasinya seperti ini (<a href="https://developers.google.com/earth-engine/guides/access#create-a-project">sumber</a>):</p><ol><li>Satu orang membuat GEE Cloud Project</li><li><em>Invite </em>rekan via Google Cloud Console dengan menambahkan akun Google sebagai anggota <em>project</em></li><li>Masing-masing anggota melakukan autentikasi dengan ee.Authenticate() dan menambahkan project ID yang sama via ee.Initialize(project=’your-project-id’)</li><li>Semua orang tidak perlu <em>login</em> di akun yang sama, semua assets, hasil ekspor dapat diakses oleh semua anggota dalam project tersebut</li></ol><p>Seperti pada code block berikut, ekspor dapat dilakukan ke dalam GEE sebagai Assets, atau <em>shared folder</em> di Drive.</p><pre># Export to shared project assets<br>task = ee.batch.Export.image.toAsset(<br>    image=image,<br>    description=&#39;s2_export&#39;,<br>    assetId=&#39;projects/your-project-id/assets/s2_result&#39;<br>)<br>task.start()<br><br># Fallback: export to shared Google Drive folder<br>task = ee.batch.Export.image.toDrive(<br>    image=image,<br>    description=&#39;s2_export&#39;,<br>    folder=&#39;shared_folder&#39;,<br>    fileNamePrefix=&#39;s2_result&#39;,<br>    scale=10,<br>    region=geometry<br>)<br>task.start()</pre><h4>Cloud Storage (Google Cloud Storage atau AWS S3)</h4><p>Pendekatan ini digunakan ketika ukuran tim lebih besar atau preferensinya sudah <em>production-oriented</em>. Alasannya adalah:</p><ol><li><strong><em>Scalable</em> </strong>karena bisa menampung data sampai petabyte, tidak seperti Drive yang memiliki batasan</li><li>Lebih murah dengan sistem <strong><em>pay-as-you-go</em></strong><em> </em>atau bayar sesuai penggunaan</li><li><strong>Otomatisasi </strong>atau mendukung <em>event-driven pipelines</em>. Misalnya ketika ada data masuk, akan menjadi <em>trigger </em>kode tertentu secara otomatis tanpa ada tindakan manual</li><li>Lebih aman karena menggunakan <strong>Identity and Access Management (IAM)</strong>, misalnya secara spesifik mengatur user A hanya bisa <em>write </em>tapi tidak <em>delete</em>. Beda dengan mekanisme Drive yang masih umum yakni <em>viewer</em>/<em>editor</em></li><li><strong>Durabilitas dan performa</strong> yang menjamin data tidak hilang dengan replikasi secara otomatis ke berbagai lokasi (server cadangan). Lalu kecepatan transfer yang tinggi untuk memproses banyak file secara paralel</li></ol><p>Singkatnya, Drive mudah untuk <em>sharing</em>, tapi <em>cloud storage </em>dirancang untuk workflow yang memerlukan data dipindah secara berkala dalam skala besar.</p><pre># Google Cloud Storage<br>!gsutil cp gs://your-bucket/data.tif /content/data.tif<br><br># AWS S3<br>import boto3<br>s3 = boto3.client(&#39;s3&#39;)<br>s3.download_file(&#39;your-bucket&#39;, &#39;data.tif&#39;, &#39;/content/data.tif&#39;)py</pre><h4>PostGIS atau Cloud Database</h4><p>Kalau pertimbangannya adalah bekerja dengan dataset besar yang sifatnya dinamis khususnya vektor (saya belum berani jamin kalau PostGIS optimal untuk raster berukuran besar), maka pilih opsi ini. Beberapa alasan singkatnya adalah:</p><ol><li><strong>Spatial query pada data vektor</strong>: Misalnya melakukan filter by bounding box, spatial join, intersection dan analisis spasial lainnya. Hal tersebut tidak dapat dilakukan secara <em>native</em> di <em>cloud storage</em>.</li><li><strong>Bisa <em>handle </em>data yang dinamis</strong>: Misalnya ada <em>update </em>pada suatu data, semua orang akan mengakses versi terbaru tanpa perlu <em>re-download</em> data tersebut.</li><li><strong>Editing file secara simultan</strong> dapat dilakukan oleh semua anggota dalam tim tanpa masalah, seperti file terkunci atau <em>corrupt</em>. Beda dengan cloud storage yang rentan terjadi <em>conflict</em> karena hanya menyimpan file statis.</li></ol><pre>import geopandas as gpd<br>from sqlalchemy import create_engine<br><br>engine = create_engine(&quot;postgresql://user:pass@host:5432/geodb&quot;)<br>gdf = gpd.read_postgis(&quot;SELECT * FROM districts&quot;, engine, geom_col=&#39;geometry&#39;)</pre><h3>Mana yang lebih tepat?</h3><p>Pada praktiknya seringkali dilakukan gabungan beberapa opsi tergantung ukuran data dan kompleksitas <em>workflow</em>. Sebagai contoh,<em> demand </em>terhadap otomatisasi dan pemrosesan data berukuran besar pada <em>production-grade</em> berbanding lurus dengan <em>setup complexity</em> yang tinggi karena menggabungkan beberapa opsi.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*UM1Oqfuq_fj1Ju0lUVMbOw.png" /><figcaption>Kegunaan dan kompleksitas setup pada masing-masing opsi</figcaption></figure><p><em>Starting point</em> yang umum dilakukan adalah menggunakan Drive dan GitHub ketika tim dan kebutuhannya masih kecil. Dari situ, akan bertahap melakukan migrasi ke <em>cloud storage</em> seiring skala data yang bertumbuh.</p><h3>Kesimpulan</h3><p>Colab bukan sepenuhnya menggantikan <em>full collaborative development environment</em>, melainkan bisa menutup kesenjangan bagi yang membutuhkan <em>cloud-based</em> Python Notebook yang mudah diakses. Maka kuncinya adalah memahami opsi mana yang tepat, entah dari segi ukuran data atau kompleksitas <em>workflow</em>. Sehingga pemorsesan dan analisis bersama menjadi lancar dan menghindari rasa frustrasi karena <em>cell </em>yang saling <em>conflict</em> serta data <em>corrupt</em> maupun <em>missing.</em></p><p>Saya coba buat pedoman praktis memilih kombinasi yang tepat untuk kolaborasi melalui Colab:</p><ul><li>Tim berukuran kecil yang cenderung mengerjakan project bersifat riset atau eksploratif sebaiknya menggunakan Drive untuk data, GitHub untuk script/kode, GEE untuk akses dan pemrosesan citra, atau menambahkan data lain dari API tertentu</li><li>Tim dengan <em>workflow</em> yang sudah berkembang atau terstruktur dapat menambahkan <em>cloud storage</em> seperti Google atau S3 untuk menyimpan data raster. Sementara itu, dapat mempertahankan GitHub untuk <em>version control</em></li><li>Tim yang sudah berorientasi produksi dapat menggunakan <em>cloud storage</em> untuk menyimpan raster, PostGIS untuk <em>vector </em>dan <em>spatial queries</em>, GitHub untuk kore, ditambah GEE untuk pemrosesan citra</li></ul><h3>Referensi</h3><ul><li><a href="https://colab.research.google.com/">https://colab.research.google.com/</a></li><li><a href="https://developers.google.com/colab">https://developers.google.com/colab</a></li><li><a href="https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb">https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb</a></li><li><a href="https://www.youtube.com/watch?v=-Z43Xx6X6wE">https://www.youtube.com/watch?v=-Z43Xx6X6wE</a></li><li><a href="https://colab.research.google.com/github/opengeos/leafmap/blob/master/docs/notebooks/14_postgis.ipynb">https://colab.research.google.com/github/opengeos/leafmap/blob/master/docs/notebooks/14_postgis.ipynb</a></li><li><a href="https://colab.research.google.com/github/bytehub-ai/code-examples/blob/main/tutorials/04_using_cloud_storage.ipynb">https://colab.research.google.com/github/bytehub-ai/code-examples/blob/main/tutorials/04_using_cloud_storage.ipynb</a></li><li><a href="https://colab.research.google.com/drive/12pxf4gDHfKpWrLUR97URpUoXlb-94-pd?usp=sharing">https://colab.research.google.com/drive/12pxf4gDHfKpWrLUR97URpUoXlb-94-pd?usp=sharing</a></li><li><a href="https://python.plainenglish.io/how-to-load-data-from-aws-s3-into-google-colab-7e76fbf534d2">https://python.plainenglish.io/how-to-load-data-from-aws-s3-into-google-colab-7e76fbf534d2</a></li></ul><p><a href="http://linkedin.com/in/mwahyur"><strong>Connect with me</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60b6128b499e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementasi GeoAI untuk Pemetaan Perairan Dangkal]]></title>
            <link>https://wahyu-ramadhan.medium.com/implementasi-geoai-untuk-pemetaan-perairan-dangkal-6f967c380d66?source=rss-f79aaab49237------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f967c380d66</guid>
            <category><![CDATA[remote-sensing]]></category>
            <category><![CDATA[oceanography]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[geospatial]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Wahyu Ramadhan]]></dc:creator>
            <pubDate>Wed, 31 Dec 2025 16:44:16 GMT</pubDate>
            <atom:updated>2026-06-14T03:03:39.060Z</atom:updated>
            <content:encoded><![CDATA[<h4>Ringkasan #30DayMapChallenge 2025</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5mVB9T3WczJ_etaf" /><figcaption>Photo by <a href="https://unsplash.com/@xidhern?utm_source=medium&amp;utm_medium=referral">Zidhan Ibrahim</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Halo semuanya,</p><p>Menjelang berakhirnya tahun 2025, saya ingin membagikan sesuatu yang cukup personal. Proyek ini seharusnya menjadi bagian dari #30DayMapChallenge bulan November lalu, namun karena tingginya intensitas pekerjaan, baru saat ini saya bisa merilisnya secara lengkap beserta repositori GitHub-nya.</p><p>Proyek ini adalah sebuah <em>remake</em> dari tugas akhir S1 saya. Jika dulu saya membandingkan data <em>sounding </em>dari <em>echosounder</em> dengan data Landsat 8 di Pulau Gili Ketapang, Probolinggo, kali ini saya membawanya ke level yang berbeda. Saya menggunakan data sampel lapangan yang sama sebagai input untuk pengembangan model GeoAI berbasis algoritma <strong>XGBoost Regressor</strong>, dengan memanfaatkan <strong>Sentinel-2</strong> dan <strong>Google Satellite Embeddings</strong>.</p><h3>Premis dan Pendekatan Teknis</h3><p>Premis utamanya tetap konsisten: <em>Satellite-Derived Bathymetry</em> (SDB) menawarkan solusi yang jauh lebih <em>cost-effective</em> untuk pemetaan perairan dangkal (<em>shallow water</em>). Dalam repositori ini, saya mendokumentasikan alur kerja dari hulu ke hilir:</p><ol><li><strong>Preprocessing &amp; Deglinting:</strong> Mengadaptasi metode Hedley (2005) untuk koreksi <em>sunglint</em>.</li><li><strong>Model Development:</strong> Melatih XGBoost untuk memetakan hubungan spektral dengan kedalaman aktual.</li><li><strong>Inference:</strong> Menghasilkan peta batimetri dalam format GeoTIFF.</li></ol><p>Sebagai konteks, #30DayMapChallenge adalah tantangan untuk membuat peta di bulan November dengan tema yang berbeda tiap harinya (<a href="https://30daymapchallenge.com/">selengkapnya</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*Fp4t8EYw3k5av5xC.png" /></figure><h3>Sekilas Mengenai Bathymetry</h3><p>Batimetri (<em>Bathymetry</em>) merupakan bidang keilmuan yang mempelajari pengukuran kedalaman dan topografi dasar perairan. Tujuannya beragam, mulai dari navigasi, pemetaan ekosistem, hingga manajemen bencana. Pada awal perkembangannya, pengukuran dilakukan secara manual, bersifat lokal, dan cakupan spasial yang terbatas dengan cara menggunakan <em>lead-line</em> atau pemberat yang diturunkan ke dasar perairan [1–3, 5].</p><p>Pengukuran batimetri di abad ke-20 mulai mengadaptasi sensor akustik (gelombang suara) yang ditembakkan ke dasar perairan secara vertikal, dan waktu tempuh gelombang tersebut kembali ke atas digunakan untuk menghitung kedalaman [3]. Sistem akustik umumnya terbagi dua: <em>Single-beam echosounders</em> (SBE) yang memancarkan <em>single-pulse</em>, serta <em>Multibeam echosounders</em> (MBE) dengan <em>simultaneous pulse</em> dengan cakupan ‘sapuan’ dasar perairan lebih luas serta detail [1, 2, 4, 5, 7].</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FkjRxQX8FTEA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fshorts%2FkjRxQX8FTEA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FkjRxQX8FTEA%2Fhq2.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/442059cf12443dd503fae210d86759c7/href">https://medium.com/media/442059cf12443dd503fae210d86759c7/href</a></iframe><p>Metode konvensional tersebut punya keunggulan yakni akurasi yang sangat tinggi karena data kedalaman diperoleh melalui pengukuran langsung. Tapi di sisi lain, tidak <em>cost-effective</em> karena harus menyediakan perangkat yang mahal, kendaraan (kapal), dan personel dengan keahlian survei hidrografi. Lalu, <em>reproducibility</em>-nya juga rendah karena cakupan spasial yang sempit, terutama akibat keterbatasan manuver kendaraan survei di perairan dangkal, lokasi dengan risiko bahaya tinggi, dan area terpencil [2, 3, 5, 6, 8–11]. Jadi, sebagian besar data yang tersedia relatif <em>outdated</em> dan tidak dapat memadai untuk wilayah pesisir yang berubah dengan cepat.</p><h4>Satellite-Derived Bathymetry</h4><p>Bisa dibilang <em>Satellite-Derived Bathymetry</em> (SDB) adalah respons dari kesenjangan data batimetri pada skala global, terutama di perairan dangkal optis, pulau-pulau kecil dan/atau terpencil. Di samping tujuan dasarnya yang sama dengan metode konvensional, SDB menggunakan prinsip dasar penginderaan jauh yakni interaksi antara cahaya matahari dan objek (kolom air dan dasar perairan). Dalam hal ini, SDB mengeksploitasi <em>nature</em> dari band hijau dari sensor satelit yang memiliki kemampuan penetrasi ke dasar perairan yang lebih baik [1, 2, 4, 8, 11, 12, 17].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*iX5QlBepQx3Zgtz4UMowvA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*UMMLzsirEMo4CpcEXMX-ew.png" /><figcaption>Ilustrasi cara kerja SDB (kiri) [18], dan kurva pantulan spektral (kanan) (<a href="https://seos-project.eu/remotesensing/remotesensing-c01-p06.html">sumber</a>)</figcaption></figure><p>Keunggulan SDB <em>basically</em> juga mirip dengan premis dasar penginderaan jauh; cakupan spasial yang luas, <em>cost-effective</em>, dan kemampuan untuk menjangkau area yang sulit (perairan sangat dangkal). Selain itu, karena hal ini memanfaatkan nilai piksel dari reflektansi kolom air dan substrat, maka kedalaman yang dapat dideteksi juga terbatas. Biasanya kedalaman SDB berkisar antara 20–30 meter, itu pun terbatas pada perairan dangkal yang relatif jernih. Jadi tingkat atenuasi (pelemahan cahaya karena penyerapan dan/atau hamburan di kolom perairan yang umumnya karena <em>total suspended solids</em>) juga rendah [2, 5, 6, 8–11, 13, 14, 17].</p><h3>Lokasi dan Data Lapangan</h3><p>Data dasar yang digunakan dalam eksperimen ini dikumpulkan melalui survei <em>Single Beam Echosounder</em> (SBES) pada tahun 2018 di <strong>Pulau Gili Ketapang, Jawa Timur</strong>. Meskipun data dikumpulkan pada tahun 2018, metodologi ini tetap relevan untuk diaplikasikan pada data satelit terbaru karena karakteristik geomorfologi dasar laut di area studi cenderung stabil.</p><h3>Alur untuk Versi Remake</h3><p>Awalnya, SDB dihasilkan melalui pendekatan <em>band-ratio</em> seperti metode Lyzenga dengan band hijau dan biru yang dikalibrasi menggunakan data kedalaman dari <em>echosounder</em> [6, 17]. Metode itu adalah yang saya adaptasi dalam penelitian untuk tugas akhir saya dulu dengan Landsat 8 untuk membuat batimetri, atau lebih tepatnya peta <em>isobath</em> karena <em>output</em>-nya adalah kontur.</p><p>Apa yang saya lakukan untuk tugas akhir dulu sebetulnya tidak <em>baru-baru amat</em> karena metode <em>band-ratio</em> dari Lyzenga sudah ada sejak 1978 [1, 7]. Namun, kekurangannya adalah cara tersebut hanya memanfaatkan dua <em>band</em> sehingga hubungan antara kualitas perairan dengan kedalaman susah ditangkap. Jadi saya (sekarang) berpikir, agak sayang kalau hanya mengambil dua <em>band</em> dari Landsat 8 yang dulu saya gunakan untuk <em>generate</em> batimetri.</p><h4>Dataset dan Algoritma Machine Learning</h4><p>Dalam <em>remake</em> ini, saya akan gunakan <strong>Sentinel-2</strong> (B1, B2, B3, B4, B5, B6, B7, B8, B8A, B11, B12) tanggal akuisisi 31 Mei 2018 supaya mendekati waktu survei saya pada April 2018. Selain itu, saya juga coba eksplorasi lain yaitu <em>compare</em> dengan <strong>Google Satellite Embedding (GSE)</strong> yang menggabungankan dataset dari multi-sensor (optis, radar, LiDAR, dsb.) resolusi 10m dan memiliki 64 band (lebih tepatnya vektor 64-dimensi) atau bisa dikatakan hiperspektral (<a href="https://developers.google.com/earth-engine/datasets/catalog/GOOGLE_SATELLITE_EMBEDDING_V1_ANNUAL">sumber</a>). Lalu, karena algoritma <em>tree</em>-<em>based </em>yang dikenal mampu menangkap hubungan <em>non</em>-<em>linear</em> antar <em>band</em> dan robust [17], maka algoritma <strong>XGBoost </strong>saya pakai sebagai basis dalam model development.</p><h3>Sunglint Correction</h3><p>Khusus untuk Sentinel-2, meskipun level koreksi sudah <em>Surface Reflectance</em>, tapi <em>noise</em> tetap seringkali ditemukan di perairan. Maka, <em>treatment</em> khusus yang saya terapkan adalah <em>sunglint correction</em> dengan metode Hedley et al. (2005) [16] yang menggunakan regresi linear antara band NIR dan <em>visible</em> (RGB). <em>Sunglint</em> sendiri adalah pantulan cahaya matahari dari permukaan air yang dapat menjadi gangguan saat interpretasi karena bisa jadi dikenali sebagai daratan atau objek oleh model GeoAI nantinya.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*T4-asWfD8SrD2WBiTaCzTA.png" /><figcaption>Contoh sunglint pada citra penginderaan jauh (<a href="https://sees-rsrc.science.uq.edu.au/rstoolkit/ina/html/marine/resources/fundamentals/corrections/sun-glint.html">sumber</a>)</figcaption></figure><p>Cara tersebut dilakukan untuk menghitung besarnya gangguan pantulan matahari (<em>sunglint</em>) yang seharusnya diserap oleh air. Nilai gangguan tersebut lalu dikurangi dari setiap band <em>visible</em> secara proporsional supaya menghasilkan citra yang bersih dari <em>sunglint</em>.</p><p>Adaptasi metode tersebut saya aplikasikan ke dalam <em>function</em> sunglint_correction yang terletak pada <a href="http://preprocessing.py/">preprocessing.py</a> dari repository GitHub yang saya lampirkan di bawah. <em>Workflow</em>nya adalah:</p><h4>A. Mencari Koefisien Regresi (bi)</h4><p>Menggunakan function linegress untuk mendapatkan nilai <em>slope</em> dari area perairan dalam. Variabel <em>slope</em> adalah representasi langsung dari <em>bi</em> dalam rumus Hedley.</p><pre># Di dalam fungsi sunglint_correction:<br># nir_pixels: sampel NIR di air dalam<br># vis_pixels: sampel band visibel (R/G/B) di perairan dalam<br><br>slope, intercept, r_value, p_value, std_err = linregress(nir_pixels, vis_pixels)</pre><h4>B. Menentukan Minimum Reference</h4><p>Mencari satu piksel dari <em>band</em> NIR dengan nilai <em>sunglint</em> terendah, bisa jadi nol atau paling tidak serendah mungkin di dalam data tersebut. Karena tahap ini menggunakan NumPy, jadi semua <em>band</em> (termasuk NIR) dianggap sebagai <em>array</em>. Hal itu adalah <em>rule of thumb</em> yang saya pakai, karena jika langsung menerapkan koreksi tanpa memperhitungkan ‘nilai piksel minimum’, bisa jadi akan <em>over correction</em>’.</p><pre>min_nir = np.min(nir_band)</pre><h4>C. Eksekusi Sunglint Correction</h4><p>Menerapkan pengurangan pada seluruh <em>array</em> atau dalam konteks ini adalah <em>band</em> yang digunakan dalam tahap koreksi.</p><pre>corrected_band = vis_band - slope * (nir_band - min_nir)</pre><p>Perbedaan utama dari formula asli dan adaptasi yang saya lakukan adalah soal skalabilitas. Jika Hedley melakukannya per piksel, sedangkan dengan Python dapat secara simultan diterapkan pada seluruh piksel dalam dataset. Sekali lagi, metode ini sangat efektif untuk perairan jernih, dan seluruh fondasi logikanya akan runtuh pada perairan dengan kekeruhan tinggi.</p><h3>Evaluasi performa model dan hasil SDB</h3><h4>Scatterplot</h4><p>Memang tidak <em>apple to apple</em> membandingkan hasil dari Sentinel-2 dan GSE, jadi anggap saja <em>scatterplot</em> dan metrik R2 serta RMSE ini sebagai <em>benchmarking</em> antara dua dataset yang ‘mentah’ dengan ‘olahan’. Keduanya memiliki korelasi yang sangat baik (R2 diatas 0.94), tapi sebaran titik Sentinel-2 di kedalaman 15–20m terlihat lebih <em>scattered</em>. Indikasinya adalah karena keterbatasan sensor menangkap relfketansi substrat karena atenuasi di perairan yang lebih dalam. Lalu, <em>error</em> dari GSE yang berada di bawah 1m (RMSE = 0.882m) menurut saya cukup impresif.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n7rGYNw56M4mXgPmBoyfNw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1nrHLK7fOL8RAiX2UxXSrA.png" /><figcaption>Scatterplot Sentinel-2 (kiri), dan GSE (kanan)</figcaption></figure><h3>Feature Importance</h3><p><em>Feature importance</em> untuk mengidentifikasi variabel mana yang paling berpengaruh (dalam konteks ini adalah <em>band</em>) saat <em>model development</em>. Sesuai dugaan awal saya, Band 3 (hijau) dari Sentinel-2 mendominasi secara mutlak karena memiliki daya penetrasi tertinggi di kolom air jika kita tinjau dari kurva pantulan spektral. Lalu, sifat <em>black box</em> dari GSE juga terungkap, kita tidak tahu bahwa <em>band</em> A51, dan A34 sebagai kontributor utama ini mewakili fitur apa di perairan.</p><h4>Peta Satellite-Derived Bathymetry</h4><p>Secara visual, meski telah mengalami <em>sunglint correction</em>, tapi hasil Sentinel-2 masih sangat <em>noisy</em> terutama di bagian selatan dan barat daya, sedangkan GSE lebih <em>smooth</em> secara ‘artifisial’ di lokasi yang sama. Kotak-kotak samar yang ditunjukkan oleh GSE juga telah di<em>mention</em> dalam dokumentasi yang menyebutkan bahwa akan ada <em>visual arctifact </em>diakibatkan oleh penggabungan <em>swath </em>sensor dan proses tiling saat pembuatan dataset tersebut. Setelah membaca ulang beberapa referensi, kelemahan metode Hedley dapat menjelaskan mengapa hasilnya seperti itu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qemalm3lDN84gfQZ7hQHQw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sod-pRI-iXPsEY809hw1fg.png" /><figcaption>Peta SDB Sentinel-2 (kiri), dan GSE (kanan)</figcaption></figure><h4>Mengapa masih banyak <em>noise</em>?</h4><p><em>Sunglint correction</em> dari Hedley memiliki ketergantungan pada asumsi bahwa perairan dapat menyerap spektrum NIR secara total, sehingga NIR yang dipantulkan kembali (dan ditangkap oleh sensor) hanyalah <em>glint</em>. Lalu, <em>noise</em> dari hasil model saya cenderung mengindikasikan bahwa ini adalah karena turbiditas tinggi dari <em>mainland </em>(Pulau Jawa) karena karena cenderung acak, bukan seperti pola riak gelombang yang kecil dan berulang (<em>glint</em>). Hal ini diperkuat dengan <em>noise </em>yang <em>mostly</em> berada di perairan dalam (&lt;15m), karena lemahnya reflektansi substrat di kedalaman tersebut ‘bertabrakan’ dengan hamburan cahaya dari sedimen.</p><p>Perlu diingat bahwa Gili Ketapang saat itu (2018) memiliki dua dermaga, masing-masing di utara dan selatan dengan banyak keramba di timur serta selatan. Jadi, aspek visual tambahan yang dapat saya amati adalah soal kemampuan model dalam menangkap detail morfologi pada tiap datasetnya berdasarkan kondisi tersebut. Zona transisi dari paparan terumbu (<em>reef flat</em>) menuju lereng terumbu (<em>reef slope</em>) di Sentinel-2 tidak punya garis delineasi setajam GSE. Wajar, karena sekali lagi GSE punya 64 fitur yang dapat merekonstruksi struktur dasar laut secara lebih presisi.</p><h3>Kesimpulan</h3><p>Harus diakui bahwa GSE menghasilkan visualisasi hingga performa model yang lebih tinggi, tapi saya rasa Sentinel-2 (atau citra optis lain) <em>single</em>-<em>date</em> tetap menjadi opsi utama yang representatif terhadap kondisi fisik serta sinkron dengan waktu survei lapangan. Namun, selama tidak ada <em>major event</em> seperti bencana alam atau perubahan antropogenik yang mengubah struktur dasar perairan secara drastis, GSE masih ‘aman’ untuk digunakan. Kembali lagi, pemilihan dataset harus mempertimbangkan antara presisi morfologi laten yang lebih <em>polished</em> atau akurasi data yang presisi terhadap kondisi riil saat pengambilan sampel.</p><p>Akses repositori GitHub <a href="https://github.com/mwahyur46/satellite-derived-bathymetry-geoai"><strong>di sini</strong></a></p><h3>Referensi</h3><p>[1] Sagawa, T., Yamashita, Y., Okumura, T., &amp; Yamanokuchi, T. (2019). Satellite derived bathymetry using machine learning and Multi-Temporal satellite images. <em>Remote Sensing</em>, <em>11</em>(10), 1155. <a href="https://doi.org/10.3390/rs11101155">https://doi.org/10.3390/rs11101155</a></p><p>[2] Cesbron, G., Melet, A., Almar, R., Lifermann, A., Tullot, D., &amp; Crosnier, L. (2021). Pan-European Satellite-Derived Coastal Bathymetry — Review, user needs and future services. <em>Frontiers in Marine Science</em>, <em>8</em>. <a href="https://doi.org/10.3389/fmars.2021.740830">https://doi.org/10.3389/fmars.2021.740830</a></p><p>[3] Li, Z., Peng, Z., Zhang, Z., Chu, Y., Xu, C., Yao, S., García-Fernández, Á. F., Zhu, X., Yue, Y., Levers, A., Zhang, J., &amp; Ma, J. (2023). Exploring modern bathymetry: A comprehensive review of data acquisition devices, model accuracy, and interpolation techniques for enhanced underwater mapping. <em>Frontiers in Marine Science</em>, <em>10</em>. <a href="https://doi.org/10.3389/fmars.2023.1178845">https://doi.org/10.3389/fmars.2023.1178845</a></p><p>[4] Wicaksono, P., Harahap, S. D., &amp; Hendriana, R. (2023). Satellite-derived bathymetry from WorldView-2 based on linear and machine learning regression in the optically complex shallow water of the coral reef ecosystem of Kemujan island. <em>Remote Sensing Applications Society and Environment</em>, <em>33</em>, 101085. <a href="https://doi.org/10.1016/j.rsase.2023.101085">https://doi.org/10.1016/j.rsase.2023.101085</a></p><p>[5] Gülher, E., &amp; Alganci, U. (2025). Sensor synergy in bathymetric mapping: integrating optical, LIDAR, and echosounder data using machine learning. <em>Remote Sensing</em>, <em>17</em>(16), 2912. <a href="https://doi.org/10.3390/rs17162912">https://doi.org/10.3390/rs17162912</a></p><p>[6] Leder, T. D., Baučić, M., Leder, N., &amp; Gilić, F. (2023). Optical Satellite-Derived Bathymetry: an Overview and WOS and Scopus Bibliometric analysis. <em>Remote Sensing</em>, <em>15</em>(5), 1294. <a href="https://doi.org/10.3390/rs15051294">https://doi.org/10.3390/rs15051294</a></p><p>[7] Munawaroh, M., Wicaksono, P., Farda, N. M., Lumban-Gaol, Y., Khakhim, N., &amp; Kamal, M. (2024). Performance test of clean-coastal-water composite sentinel 2A image for shallow water bathymetry mapping. <em>Remote Sensing Applications Society and Environment</em>, <em>35</em>, 101212. <a href="https://doi.org/10.1016/j.rsase.2024.101212">https://doi.org/10.1016/j.rsase.2024.101212</a></p><p>[8] Duan, Z., Chu, S., Cheng, L., Ji, C., Li, M., &amp; Shen, W. (2022). Satellite-derived bathymetry using Landsat-8 and Sentinel-2A images: assessment of atmospheric correction algorithms and depth derivation models in shallow waters. <em>Optics Express</em>, <em>30</em>(3), 3238. <a href="https://doi.org/10.1364/oe.444557">https://doi.org/10.1364/oe.444557</a></p><p>[9] Ma, Y., Xu, N., Liu, Z., Yang, B., Yang, F., Wang, X. H., &amp; Li, S. (2020). Satellite-derived bathymetry using the ICESat-2 lidar and Sentinel-2 imagery datasets. <em>Remote Sensing of Environment</em>, <em>250</em>, 112047. <a href="https://doi.org/10.1016/j.rse.2020.112047">https://doi.org/10.1016/j.rse.2020.112047</a></p><p>[10] Xie, C., Chen, P., Pan, D., Zhong, C., &amp; Zhang, Z. (2021). Improved filtering of ICESAT-2 LIDAR data for nearshore bathymetry estimation using Sentinel-2 imagery. <em>Remote Sensing</em>, <em>13</em>(21), 4303. <a href="https://doi.org/10.3390/rs13214303">https://doi.org/10.3390/rs13214303</a></p><p>[11] Caballero, I., &amp; Stumpf, R. P. (2023). Confronting turbidity, the major challenge for satellite-derived coastal bathymetry. <em>The Science of the Total Environment</em>, <em>870</em>, 161898. <a href="https://doi.org/10.1016/j.scitotenv.2023.161898">https://doi.org/10.1016/j.scitotenv.2023.161898</a></p><p>[12] Ashphaq, M., Srivastava, P. K., &amp; Mitra, D. (2021). Review of near-shore satellite derived bathymetry: Classification and account of five decades of coastal bathymetry research. <em>Journal of Ocean Engineering and Science</em>, <em>6</em>(4), 340–359. <a href="https://doi.org/10.1016/j.joes.2021.02.006">https://doi.org/10.1016/j.joes.2021.02.006</a></p><p>[13] Traganos, D., Poursanidis, D., Aggarwal, B., Chrysoulakis, N., &amp; Reinartz, P. (2018). Estimating Satellite-Derived Bathymetry (SDB) with the Google Earth Engine and Sentinel-2. <em>Remote Sensing</em>, <em>10</em>(6), 859. <a href="https://doi.org/10.3390/rs10060859">https://doi.org/10.3390/rs10060859</a></p><p>[14] Babbel, B. J., Parrish, C. E., &amp; Magruder, L. A. (2021). ICESAT‐2 Elevation retrievals in support of Satellite‐Derived Bathymetry for global science applications. <em>Geophysical Research Letters</em>, <em>48</em>(5), e2020GL090629. <a href="https://doi.org/10.1029/2020gl090629">https://doi.org/10.1029/2020gl090629</a></p><p>[15] Eugenio, F., Marcello, J., Mederos-Barrera, A., &amp; Marques, F. (2021). High-Resolution Satellite Bathymetry Mapping: Regression and Machine Learning-Based Approaches. <em>IEEE Transactions on Geoscience and Remote Sensing</em>, <em>60</em>, 1–14. <a href="https://doi.org/10.1109/tgrs.2021.3135462">https://doi.org/10.1109/tgrs.2021.3135462</a></p><p>[16] Hedley, J. D., Harborne, A. R., &amp; Mumby, P. J. (2005). Technical note: Simple and robust removal of sun glint for mapping shallow‐water benthos. <em>International Journal of Remote Sensing</em>, <em>26</em>(10), 2107–2112. <a href="https://doi.org/10.1080/01431160500034086">https://doi.org/10.1080/01431160500034086</a></p><p>[17] Gülher, E., &amp; Alganci, U. (2023). Satellite–Derived Bathymetry in Shallow Waters: Evaluation of Gokturk-1 Satellite and a Novel Approach. <em>Remote Sensing</em>, <em>15</em>(21), 5220. <a href="https://doi.org/10.3390/rs15215220">https://doi.org/10.3390/rs15215220</a></p><p>[18] He, J., Zhang, S., Cui, X., &amp; Feng, W. (2024). Remote sensing for shallow bathymetry: A systematic review. <em>Earth-Science Reviews</em>, <em>258</em>, 104957. <a href="https://doi.org/10.1016/j.earscirev.2024.104957">https://doi.org/10.1016/j.earscirev.2024.104957</a></p><p><a href="http://linkedin.com/in/mwahyur"><strong>Connect with me</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f967c380d66" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Menjelajahi Piksel di Kedalaman]]></title>
            <link>https://wahyu-ramadhan.medium.com/menjelajahi-piksel-di-kedalaman-ff63ef5d4e95?source=rss-f79aaab49237------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff63ef5d4e95</guid>
            <category><![CDATA[laut]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[peta]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Wahyu Ramadhan]]></dc:creator>
            <pubDate>Tue, 31 Dec 2024 10:02:08 GMT</pubDate>
            <atom:updated>2024-12-31T10:02:08.498Z</atom:updated>
            <content:encoded><![CDATA[<h4>Ringkasan #30DayMapChallenge 2024</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*17emhoo6RiEAQ-T-cm77rw.png" /></figure><p>Halo semuanya,</p><p>Memasuki tahun kelima saya menemukan #30DayMapChallenge, sama seperti tahun 2023, lagi-lagi saya belum bisa menyelesaikannya dengan sempurna. Saya tidak akan memberi banyak <em>excuses</em>,<em> </em>karena memang semua ide saya sedang dialihkan pada komitmen yang lain. Tapi yang jelas <em>challenge </em>ini tetap membuat saya antusias tiap bulan November.</p><p>Meskipun awalnya pesimis, tapi saya coba sedikit oportunis dengan mengeksekusi beberapa hari sekaligus. Idenya adalah membuat model Geospatial Artificial Intelligence (GeoAI) untuk klasifikasi habitat bentik di laut dangkal. <em>Effort</em>-nya lumayan, terutama di tahap pra-pemrosesan. Walaupun masih tergolong <em>shallow learning</em>, tapi keseluruhan prosesnya bahkan bisa dibagi menjadi beberapa konten.</p><p>Sebagai konteks, #30DayMapChallenge diinisiasi oleh <a href="https://tjukanov.org/">Topi Tjukanov</a> pada 2019 dan rutin diselenggarakan tiap tahunnya di bulan November. Tantangannya adalah untuk membuat peta setiap hari dengan tema yang berbeda dalam waktu sebulan. Peta ini tidak dibatasi metode atau bagaimana cara membuatnya asalkan harus dibagikan ke media sosial. Baca lebih lanjut dalam situs resminya di <a href="https://30daymapchallenge.com/"><strong>sini</strong></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*ZS5MS-QGwH-s7Ioc.png" /><figcaption>Tema harian <a href="https://30daymapchallenge.com/">#30DayMapChallenge 2024</a></figcaption></figure><p>Ngomong-ngomong, akun Google saya untuk menyimpan peta/gambar dan video di konten <em>recap </em>tahun-tahun sebelumnya kebetulan di <em>banned </em>tanpa alasan jelas, mungkin perlu waktu untuk mengunggahnya ulang.</p><h3>Habitat bentik</h3><p>Habitat bentik adalah lingkungan yang letaknya di dasar perairan (laut dan/atau darat), tempat berbagai organisme beraktivitas dan berinteraksi dengan substrat. Sederhananya, kondisi habitat bentik berbanding lurus dengan biodiversitas yang ada di dalamnya. Kalau konteksnya geosains, habitat bentik yang dapat dipetakan sejauh ini terbatas pada manifestasi objek yang tampak pada perairan dangkal optis (<em>optically shallow water</em>) saja [2] [3]. Jadi, objek seperti terumbu karang, lamun, alga, pasir dsb. yang berada di bawah tubir atau batas antara <em>optically shallow water</em> cenderung susah untuk dideteksi terutama dari citra penginderaan jauh.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*CMVs7Ssps_lTeMoM.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JN4GtTD748AnTV2qLyE4lA.png" /><figcaption>Zonasi terumbu karang (kiri) (<a href="https://www.coastalwiki.org/wiki/Coral_reefs">sumber</a>), serta optically shallow water pada citra penginderaan jauh, warna tubir tampak lebih gelap (kanan)</figcaption></figure><h3>Pra-pemrosesan</h3><h4><strong>Memperoleh label data</strong></h4><p>Tahap ini bertujuan untuk memberi label pada dataset yang akan digunakan oleh model GeoAI untuk melakukan prediksi atau klasfikasi habitat bentik pada citra. Jika urutan logis pada klasifikasi <em>Land Use Land Cover </em>(LULC) adalah membuat titik lalu pergi ke lokasi tersebut dan mengambil sampel (beserta variabel-variabel lain yang dibutuhkan), habitat bentik sedikit berbeda.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sWETcz-P7WAZvfgjfsZFUw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CDJWuShAqY4pvyjbXrhNcA.png" /><figcaption>Ilustrasi line transect (kiri), dan kerja lapangan dalam mengambil sampel habitat bentik (kanan) [1]</figcaption></figure><p><em>Uncertainty </em>dari kondisi perairan menyulitkan kita untuk berada di <em>exact location</em> dari titik acuan yang direncanakan, oleh karena itu <em>approach</em>nya adalah melalui <em>line transect</em>. Teknisnya di lapangan adalah menjadikan garis tersebut sebagai acuan <em>sampling, </em>entah dengan metode <em>photo transect</em> atau <em>spot check</em> [1]. Kalau satu kelas (misalnya lamun) ditemukan dominan pada persentase tertentu di satu titik sampel, maka titik sampel dianggap mewakili kelas tersebut. Atau bahkan kelas campuran apabila komposisi persentasenya memenuhi suatu kondisi [9].</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FM9xA4mYlCRo%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DM9xA4mYlCRo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FM9xA4mYlCRo%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/22e583abe4d7715b31671285845fc6db/href">https://medium.com/media/22e583abe4d7715b31671285845fc6db/href</a></iframe><p>Dari segi kepraktisan dan efisiensi waktu di lapangan, agaknya <em>photo transect</em> bisa jadi opsi. Dengan kamera dan GPS <em>hanheld</em>, kita ambil foto substrat sepanjang <em>line transect </em>yang sudah dibuat dengan interval jarak misalnya 1 meter. Soal integrasi dokumentasi dengan data GPS (koordinat) dan perhitungan persentase kelas dalam satu titik sampel bisa dilakukan pasca lapangan.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FDV-qdpI0KPs%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DDV-qdpI0KPs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FDV-qdpI0KPs%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2dc03e0078aa6b3a68be574c304a8e96/href">https://medium.com/media/2dc03e0078aa6b3a68be574c304a8e96/href</a></iframe><h4>Data referensi</h4><p>Allen Coral Atlas (ACA) v2.0 saya anggap cukup bagus untuk menjadi referensi dalam membuat label dataset berhubung tidak ada data dari lapangan. Jadi saya mengandaikan seolah-olah sedang melakukan survei di lapangan dengan langkah berikut:</p><ol><li>Membuat <em>line transect</em></li><li>Mengubah ke <em>points</em> dengan interval 1m</li><li><em>Extract</em> nilai piksel (kode/id kelas habitat bentik)</li></ol><p><strong>*Gunakan <em>script </em>GEE </strong><a href="https://code.earthengine.google.com/376baa9ce32c0260b49c3df206067375"><strong>ini</strong></a><strong> untuk ketiga langkah diatas</strong>.</p><p><em>Line transect</em> sebisa mungkin dibuat secara melintang, baik ke arah laut (vertikal) dan mengikuti garis pantai (horizontal) untuk mendapatkan variasi kelas yang cukup. Selain itu, buat garisnya hingga ke mendekati tubir. Oh ya, saya revisi lagi <em>statement</em> saya tentang sampel harus poligon di <a href="https://wahyu-ramadhan.medium.com/strategi-klasifikasi-citra-penginderaan-jauh-b6d4ee901f6a">sini</a>, mengingat dinamika kondisi lapangan. Tidak ada salahnya sampel berupa <em>point</em>, asalkan memenuhi jumlah piksel minimum tiap kelas sehingga representatif (<a href="https://wahyu-ramadhan.medium.com/strategi-klasifikasi-citra-penginderaan-jauh-b6d4ee901f6a">selengkapnya</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kDsfBGSY2YnHcATpzRW0oQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xu0LV2PaWNPzahk47gww5A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dfI8yrQfJU0qS3ZBMXKTWA.png" /><figcaption>Pengambilan sampel kelas habitat bentik di Google Earth Engine (GEE). Line transect (kiri), konversi line ke points (tengah), dan overlay titik sampel dengan layer habitat bentik ACA (kanan)</figcaption></figure><h4><strong>Seleksi shallow water</strong></h4><p>Saat ini sensor penginderaan jauh (spektral) hanya efektif menangkap objek di bawah air pada panjang gelombang visible (400–700nm). Dengan kata lain habitat bentik yang dapat dideteksi terbatas pada kedalaman tertentu, tergantung kejernihan perairan dan reflektansi akibat penetrasi cahaya. Jadi, seleksi wilayah dengan kedalaman yang <em>mostly</em> adalah <em>optically shallow water</em> harus dilakukan supaya lebih efektif.</p><figure><img alt="Lihat kurva pada objek air, cenderung menurun setelah melalui panjang gelombang merah dan ‘habis’ ketika mendekati inframerah-dekat" src="https://cdn-images-1.medium.com/max/1024/0*bJLyLQeVHdARXzW7.png" /><figcaption>Kurva pantulan spektral [4]</figcaption></figure><p>Saya memakai pendekatan dengan Normalized Difference Water Index (NDWI) untuk segmentasi wilayah <em>shallow water</em>. Raster Calculator di QGIS adalah cara mudah untuk menghitung NDWI dengan formula (Green-NIR)/(Green+NIR). FYI karena data citranya PlanetScope (8 <em>band</em>), jadi Green = B4 dan NIR = B8. Setelah itu, gunakan <em>rule of thumb</em> untuk <em>reclass </em>hasil NDWI yaitu nilai &gt; 0 dianggap sebagai <em>shallow water</em>. Kemudian <em>convert</em> NDWI yang telah di <em>reclass </em>format vektor untuk <em>masking </em>citra PlanetScope.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wPIPYDy4r0_NFp1ZOZTKpw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*1D6rxl_n_sQ0-edKP8INYQ.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tRbgzO9W4i0-FmHUfY15gQ.png" /><figcaption>Tahapan masking shallow water pada citra PlanetScope</figcaption></figure><p>Data yang telah di<em>masking </em>pada <em>shallow water</em> siap digunakan pada tahapan berikutnya dengan Python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2dpw0JRfCEw2nstDGmYIUw.png" /><figcaption>Data yang telah di masking hanya pada optically shallow water</figcaption></figure><h3>Unduh script Python</h3><p><em>Script </em>lengkapnya ada di <strong>GitHub repository</strong> saya<strong> </strong><a href="https://github.com/mwahyur46/benthic_habitat_classification"><strong>di sini</strong></a>, karena cukup panjang dan akan lebih mudah apabila ingin <em>update </em>daripada melalui medium. Prosesnya terbagi menjadi tiga <em>file </em>Python (.ipynb), yaitu mempersiapkan dataset <em>training </em>dan <em>testing</em>, membuat model GeoAI, dan menerapkan model pada data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AV2fdg_xhLmzE19o0FBDXQ.png" /><figcaption><a href="https://github.com/mwahyur46/benthic_habitat_classification.git">GitHub repository</a></figcaption></figure><h3>Mempersiapkan dataset training dan testing</h3><p>Sebetulnya saya sudah membuat <em>markdown </em>atau catatan pada <em>file </em>.ipynb di repository, tapi saya akan menambahkan beberapa detail yang belum ada dalam <em>file </em>tersebut. Jika di-<em>breakdown</em>, ada empat hal yang dilakukan di tahap ini: memberi deskripsi <em>band</em> pada data PlanetScope, ekstraksi nilai piksel, membuat <em>training </em>dan <em>testing </em>dataset, serta menangani <em>class imbalance</em>.</p><p>Khusus pada pemberian deskripsi pada data, secara teknis bisa saja dihapus dari <em>workflow </em>kalau paham betul struktur atau urutan <em>band</em>. Tapi apabila ada tambahan fitur seperti geomorfologi (batimetri), atau bahkan fusi (raster stack) dengan citra lain, maka itu berpotensi menyulitkan. Demi menjaga konsistensi dan mudah diingat, sebaiknya langkah ini tetap diperlukan.</p><pre># Retrieve the list of band descriptions from the dataset<br>desc = dataset.descriptions<br><br># If descriptions are not available, create manual descriptions<br>if not desc or all(d is None for d in desc):<br>    desc = [&quot;B1&quot;, &quot;B2&quot;, &quot;B3&quot;, &quot;B4&quot;, &quot;B5&quot;, &quot;B6&quot;, &quot;B7&quot;, &quot;B8&quot;]<br><br># Create a dictionary to associate band descriptions with their indices after transpose<br>band_descriptions = {f&quot;Band {i+1}&quot;: desc[i] for i in range(len(desc))}<br><br># Display the dimensions and descriptions for each band<br>print(&quot;\nDimensions of the raster data after transpose:&quot;, planetscope.shape)<br>print(&quot;Descriptions for each band after transpose:&quot;)<br>for band, description in band_descriptions.items():<br>    print(f&#39;{band}: {description}&#39;)</pre><p>Kebetulan biodiversitas habitat bentik di Kepulauan Gili tidak banyak memperlihatkan kelas Microalgal Mats, jadi jumlah sampel kelas tersebut sangat timpang dibanding lainnya. Dampaknya nanti bisa jadi model GeoAI akan menjadi bias, atau lebih baik dalam memprediksi kelas mayoritas [5]. Jadi saya lakukan random oversampling untuk meningkatkan jumlah sampel dari kelas yang teridentifikasi sebagai minoritas. Saya gunakan modul RandomOverSampler dari library imblearn untuk oversampling pada dataset <em>training</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gOypCS_MyGkDooEVijAAIQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Xns8Z9Tr0Lnzmk_U.png" /><figcaption>Kelas Microalgal Mats (kiri) dan oversample terhadap kelas minoritas (kanan) [3]</figcaption></figure><h3>Pembuatan model GeoAI</h3><p><em>Outline </em>dari langkah pembuatan model GeoAI adalah: impor dataset <em>training </em>dan <em>test</em>, hyperparameter tuning, dan evaluasi model. Model GeoAI tersebut dibangun menggunakan algoritma Machine Learning (ML) Extreme Gradient Boosting (XGBoost) dengan <em>function</em> XGBClassifier dari <em>library</em> xgboost. Opsi algoritma lain (berbasis pohon keputusan) yang lebih <em>common </em>untuk klasifikasi habitat bentik adalah Random Forest, tapi klaim bahwa XGBoost lebih efisien [6] sejujurnya membuat saya penasaran.</p><p>XGBoost secara singkat bekerja dengan prinsip <em>boosting</em> atau membangun model secara iteratif dengan menggabungkan <em>weak learner </em>[7] [8]. Beda dengan RF yang menggabungkan banyak pohon keputusan yang dilatih secara independen atau paralel (<em>bagging</em>) [6]. <em>Weak learner</em> diasosiasikan sebagai model yang masih memiliki kesalahan (<em>error</em>) lantas diperbaiki hingga <em>error </em>pada <em>output</em> bisa minim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*P52uI8AxrI18h9w-.png" /><figcaption>Alur kerja algoritma algoritma ML berbasis boosting yang memperbaiki weak learner [7]</figcaption></figure><p>Hal penting lain di proses pembuatan model GeoAI adalah hyperparameter tuning. Saya pilih metode grid search untuk mencari kombinasi paling optimal dari sekian hyperparameter yang tersedia. Sedangkan Cross-Validation (CV) 5-Folds dipakai selama <em>training </em>dan <em>testing </em>untuk evaluasi model. Model akan dilatih dengan 4 dari 5 folds (data <em>training</em>), diuji pada <em>fold </em>yang tersisa (data <em>testing</em>), diulang 5x sehingga tiap fold jadi data <em>testing</em> 1x. Daftar hyperparameter dari XGBoost secara lengkap ada di <a href="https://xgboost.readthedocs.io/en/latest/parameter.html">sini</a>.</p><pre># Define a list of parameters for hyperparameter tuning<br># List of the parameters<br>param_list = {<br>    &#39;n_estimators&#39;: [50, 100, 300], #  Number of trees to build in the model. Trying 50, 100, and 300 trees.<br>    &#39;max_depth&#39;: [3, 6, 9], # Maximum depth of each tree. Trying depths of 3, 6, and 9.<br>    &#39;eta&#39;: [0.1, 0.3, 0.5], # Controls the step size of the learning process. Trying values of 0.1, 0.3, and 0.5.<br>    &#39;gamma&#39;: [0, 0.1, 0.2], # Minimum loss reduction required for further partitioning a leaf node. Trying values of 0, 0.1, and 0.2.<br>    &#39;subsample&#39;: [0.8, 1.0], # Fraction of the training data to use for fitting each tree. Trying 0.8 and 1.0.<br>    &#39;colsample_bytree&#39;: [0.8, 1.0], # Fraction of features to use for each tree. Trying 0.8 and 1.0.<br>}<br><br># 5-fold cross-validation GridSearchCV<br>grid_search = GridSearchCV(<br>    xgb_model,            # The model you want to tune (XGBoost classifier)<br>    param_list,           # The grid of hyperparameters to search<br>    cv=5,                 # Number of folds for cross-validation (5-fold)<br>    scoring=&#39;accuracy&#39;,   # The metric used to evaluate model performance (accuracy)<br>    n_jobs=-1,            # Use all available CPU cores for parallel processing<br>    verbose=5             # Display progress and information (higher value gives more details)<br>)</pre><p>Sayangnya hasil evaluasi klasifikasinya menunjukkan <em>overall accuracy </em>(OA) yang tidak begitu memuaskan, hanya sebesar 60.19%. Kelas Seagrass punya performa terbaik: <em>Precision</em>/<em>User Accuracy </em>(UA) 76.93%, <em>recall</em>/<em>Producer Accuracy</em> (PA) 77.63%. Sementara performa kelas Micoralgal Mats: UA 16% dan PA 18.18%, tidak memuaskan meski sudah melalui oversampling. Akurasi yang terbatas ini rasanya wajar karena identifikasi karakteristik spektral objek di bawah air memang cukup sulit, apalagi tanpa <em>pre-processing</em> apapun yang mempengaruhi kualitas data citra.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*c5RmEO-kcIqTt_86DyOTag.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*bZSRDry4SLE5xSLuYVLFIw.png" /><figcaption>Confusion matrix klasifikasi habitat bentik di Kepulauan Gili</figcaption></figure><h3>Menerapkan model</h3><p>Sebenarnya tidak ada catatan khusus untuk tahap yang dimaksudkan untuk menerapkan model XGBoost ke data PlanetScope. Tapi <em>output</em> klasifikasinya selalu menunjukkan perairan dalam dan darat merupakan kelas Rock. Padahal saya sudah beri nilai -9999 pada piksel NoData (null) di dalam <em>function </em>untuk klasifikasi data. Solusi sementara adalah <em>masking</em> dengan poligon <em>shallow water</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*t-Or3Em_UfiTGLksJsKx6w.png" /><figcaption>Output klasifikasi habitat bentik Kepulauan Gili</figcaption></figure><p>Karena visualisasi peta di Python kurang intutitif, jadi saya <em>prefer </em>membuat layout peta di tempat lain. Seperti biasanya, saya gunakan QGIS dan Figma.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WdiK1os9PBvlMPz74m4nEQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-w6uiCqZ3MDUu9X3r4Lkog.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q2xftGoNCZy5RpktLb8q9g.png" /><figcaption>Titik sampel, line transect, dan ndwi (shallow water)</figcaption></figure><p>Saya baru sadar saat <em>layouting</em> peta ini, ternyata ada ketidaksempurnaan pada <em>shallow</em> <em>water </em>di bagian utara pulau Gili Meno. Yah, mungkin saya kurang teliti saat memilih datanya karena secara visual tutupan awannya sangat tipis 😔</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JOfsZnkiqtTbU_Hs0x2OHg.png" /><figcaption>Peta klasifikasi habitat bentik Kepulauan Gili</figcaption></figure><h3>Referensi</h3><p>[1] Roelfsema, C. (2010). Integrating field data with high spatial resolution multispectral satellite imagery for calibration and validation of coral reef benthic community maps. Journal of Applied Remote Sensing, 4(1), 043527. <a href="https://doi.org/10.1117/1.3430107">https://doi.org/10.1117/1.3430107</a></p><p>[2] Hedley, J. D., Roelfsema, C., Brando, V., Giardino, C., Kutser, T., Phinn, S., Mumby, P. J., Barrilero, O., Laporte, J., &amp; Koetz, B. (2018b). Coral Reef Applications of Sentinel-2: Coverage, characteristics, bathymetry and benthic mapping with comparison to Landsat 8. <em>Remote Sensing of Environment</em>, <em>216</em>, 598–614. <a href="https://doi.org/10.1016/j.rse.2018.07.014">https://doi.org/10.1016/j.rse.2018.07.014</a></p><p>[3] Wicaksono, P., Aryaguna, P. A., &amp; Lazuardi, W. (2019). Benthic habitat mapping model and cross-validation using machine-learning classification algorithms. <em>Remote Sensing</em>, <em>11</em>(11), 1279. <a href="https://doi.org/10.3390/rs11111279">https://doi.org/10.3390/rs11111279</a></p><p>[4] O’Donohue, D. (2024, October 1). Understanding spectral reflectance in remote sensing. mapscaping.com. <a href="https://mapscaping.com/understanding-spectral-reflectance-in-remote-sensing/">https://mapscaping.com/understanding-spectral-reflectance-in-remote-sensing/</a>. Diakses pada 24 Desember 2024.</p><p>[5] Tang, T. (2023, April 25). Class imbalance strategies — A visual guide with code. Medium. <a href="https://towardsdatascience.com/class-imbalance-strategies-a-visual-guide-with-code-8bc8fae71e1a">https://towardsdatascience.com/class-imbalance-strategies-a-visual-guide-with-code-8bc8fae71e1a</a>. Diakses pada 24 Desember 2024.</p><p>[6] Shao, Z., Ahmad, M. N., &amp; Javed, A. (2024). Comparison of Random Forest and XGBoost Classifiers Using Integrated Optical and SAR Features for Mapping Urban Impervious Surface. Remote Sensing, 16(4), 665. <a href="https://doi.org/10.3390/rs16040665">https://doi.org/10.3390/rs16040665</a></p><p>[7] Chen, T., &amp; Guestrin, C. (2016). XGBoost. Proceedings of the 22nd ACM SIGKDD International Conference on Knowledge Discovery and Data Mining, 785–794. <a href="https://doi.org/10.1145/2939672.2939785">https://doi.org/10.1145/2939672.2939785</a></p><p>[8] GeeksforGeeks. (2023, February 6). XGBoost. <a href="https://www.geeksforgeeks.org/xgboost/">https://www.geeksforgeeks.org/xgboost/</a>. Diakses pada 24 Desember 2024.</p><p>[9] Wicaksono, P., &amp; Harahap, S. D. (2023). Mapping seagrass biodiversity indicators of Pari Island using multiple worldview-2 bands derivatives. <em>Geosfera Indonesia</em>, <em>8</em>(2), 189. <a href="https://doi.org/10.19184/geosi.v8i2.41214">https://doi.org/10.19184/geosi.v8i2.41214</a></p><p>Connect with me on <a href="http://linkedin.com/in/mwahyur"><strong>LinkedIn</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff63ef5d4e95" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Pixels Beneath]]></title>
            <link>https://python.plainenglish.io/exploring-pixels-beneath-05159932f02b?source=rss-f79aaab49237------2</link>
            <guid isPermaLink="false">https://medium.com/p/05159932f02b</guid>
            <category><![CDATA[maps]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[marine]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Wahyu Ramadhan]]></dc:creator>
            <pubDate>Tue, 31 Dec 2024 10:01:41 GMT</pubDate>
            <atom:updated>2026-09-08T08:47:29.226Z</atom:updated>
            <content:encoded><![CDATA[<h4>The #30DayMapChallenge 2024 Recap</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BvV8wk11u2TYmY6E5PB5HQ.png" /></figure><p>Halo semuanya,</p><p>As I begin my fifth year in the #30DayMapChallenge, I realize, similar to 2023, that I can’t finish it flawlessly. I won’t make many excuses, as most of my ideas have been redirected to other commitments. I’m not sure about joining this year’s challenge initially, but I decided to adopt a more opportunistic mindset by addressing several days at once. However, one thing remains certain — this challenge continues to excite me every November.</p><p>My concept was to develop a Geospatial Artificial Intelligence (GeoAI) model for benthic habitat classification. The effort turned out to be quite hard, particularly in the pre-processing. While it’s still categorized as shallow learning, the entire process actually can be broken down into several contents.</p><p>For context, the #30DayMapChallenge was initiated by Topi Tjukanov in 2019 and takes place every November. This challenge invites participants to create a map each day, with each map based on a different theme. There are no restrictions on the methods or tools used, as long as the maps are shared on social media. You can find additional information on the official website <a href="http://30daymapchallenge.com/">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*ZS5MS-QGwH-s7Ioc.png" /><figcaption><a href="https://30daymapchallenge.com/">#30DayMapChallenge 2024</a> daily themes</figcaption></figure><p>By the way, my Google account, where I stored maps/images, and videos for recap content from previous years, was unexpectedly banned for no clear reason. Re-uploading everything might take some time.</p><h3>Benthic habitat</h3><p>Benthic habitats are environments located at the bottom of aquatic systems, whether marine or terrestrial, where various organisms interact with the substrate. Essentially, the condition of a benthic habitat is closely linked to the biodiversity it supports. In the field of geoscience, mapping benthic habitats has often been limited to objects visible in optically shallow waters [2] [3]. As a result, features like coral reefs, seagrasses, algae, and sand found below the shelf or the boundary of optically shallow water can be difficult to detect, especially when using remote sensing data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*vtsJ2Gki7cJPJNVe.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JN4GtTD748AnTV2qLyE4lA.png" /><figcaption>Coral reef zonation (left) (<a href="https://www.coastalwiki.org/wiki/Coral_reefs">source</a>), also optically shallow water from remote sensing (satellite) imagery (right)</figcaption></figure><h3>Pre-processing</h3><h4>Obtaining data labels</h4><p>This stage aims to label the dataset that the GeoAI model will use to predict or classify benthic habitats in the imagery. The logical sequence in Land Use Land Cover (LULC) classification involves creating points, visiting those locations, and collecting samples (along with other required variables). However, the approach for benthic habitats is somewhat different.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sWETcz-P7WAZvfgjfsZFUw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CDJWuShAqY4pvyjbXrhNcA.png" /><figcaption>Line transect (left), and field surveys to taking benthic habitat samples (right) [1]</figcaption></figure><p>The uncertainty of aquatic conditions makes it challenging to precisely locate the reference points as planned, so we use line transects instead. Technically, in the field, this line serves as a sampling reference, either through photo transects or spot checks [1]. If a single class (e.g., seagrass) is found to dominate at a certain percentage in a sample point, that point is considered representative of that class. Alternatively, it can even be classified as a mixed class if the composition percentages meet specific criteria [9].</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FM9xA4mYlCRo%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DM9xA4mYlCRo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FM9xA4mYlCRo%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/22e583abe4d7715b31671285845fc6db/href">https://medium.com/media/22e583abe4d7715b31671285845fc6db/href</a></iframe><p>In terms of practicality and time efficiency in the field, the photo transect method seems to be a viable option. Using a camera and a handheld GPS, photos of the substrate are taken along the predefined line transect at regular intervals, such as every meter. Integration of the documentation with GPS data (coordinates) and calculation of class percentages for each sample point can be performed post-fieldwork.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FDV-qdpI0KPs%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DDV-qdpI0KPs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FDV-qdpI0KPs%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2dc03e0078aa6b3a68be574c304a8e96/href">https://medium.com/media/2dc03e0078aa6b3a68be574c304a8e96/href</a></iframe><h4>Reference data</h4><p>The Allen Coral Atlas (ACA) v2.0 is regarded as a reliable reference for labeling datasets, especially when field data is not available. The workflow simulates a field survey through the following steps:</p><ol><li>Create line transects.</li><li>Convert the transects into points at 1-meter intervals.</li><li>Extract pixel values, which include benthic habitat class codes and IDs.</li></ol><p><strong><em>*Use </em></strong><a href="https://code.earthengine.google.com/376baa9ce32c0260b49c3df206067375"><strong><em>this GEE script</em></strong></a><strong><em> to perform all three steps.</em></strong></p><p>The transects should ideally be drawn perpendicular to the coastline — both seaward (vertical) and along the coastline (horizontal) — to capture enough class variation. Additionally, the lines should be extended to approach the reef slope. I would like to revise my earlier statement regarding samples needing to be polygons: due to the dynamic nature of field conditions, point samples are also acceptable. The important factor is to ensure a minimum number of pixels per class for representativeness (<a href="https://wahyu-ramadhan.medium.com/remote-sensing-image-classification-strategies-d2f9f42aa0a7">details here</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kDsfBGSY2YnHcATpzRW0oQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xu0LV2PaWNPzahk47gww5A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dfI8yrQfJU0qS3ZBMXKTWA.png" /><figcaption>Sampling benthic habitat classes in Google Earth Engine (GEE): Line transect (left), converting lines to points (center), and overlaying sample points with the ACA benthic habitat layer (right)</figcaption></figure><h4>Shallow water selection</h4><p>Currently, remote sensing sensors are effective at capturing underwater objects only within the visible wavelength range (400–700 nm). This means that the detection of benthic habitats is limited to a certain depth, which depends on water clarity and light penetration. Therefore, selecting areas that are primarily shallow water is crucial for more efficient analysis.</p><figure><img alt="The reflectance curve for water typically declines after passing the red wavelength and fades completely as it approaches near-infrared." src="https://cdn-images-1.medium.com/max/1024/0*bJLyLQeVHdARXzW7.png" /><figcaption>Spectral reflectance curve [4]</figcaption></figure><p>I used the Normalized Difference Water Index (NDWI) approach to segment shallow water areas. A simple way to calculate NDWI in QGIS is by using the Raster Calculator with the formula (Green — NIR) / (Green + NIR). Since I used PlanetScope imagery (8 bands), Green = B4 and NIR = B8. After that, I applied a rule of thumb to reclassify the NDWI results: values greater than 0 are considered as optically shallow water. Then, I converted the reclassified NDWI into vector format for masking the PlanetScope imagery.</p><p>I used the Normalized Difference Water Index (NDWI) approach to segment shallow water areas. A straightforward way to calculate NDWI in QGIS is by using the Raster Calculator with the formula (Green — NIR) / (Green + NIR). In my case, using PlanetScope imagery (8 bands), Green = B4 and NIR = B8. After that, I applied a rule of thumb to reclassify the NDWI results: values greater than 0 are considered optically shallow water. Finally, I converted the reclassified NDWI into vector format to mask the PlanetScope imagery.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wPIPYDy4r0_NFp1ZOZTKpw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*1D6rxl_n_sQ0-edKP8INYQ.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tRbgzO9W4i0-FmHUfY15gQ.png" /><figcaption>Masking the optically shallow water on the PlanetScope data in QGIS</figcaption></figure><p>The data masked for shallow water is now ready for the next steps using Python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2dpw0JRfCEw2nstDGmYIUw.png" /><figcaption>Shallow waters masking results</figcaption></figure><h3>Python script</h3><p>The complete script is available in my GitHub repository <a href="https://github.com/mwahyur46/benthic_habitat_classification/tree/main?tab=readme-ov-file"><strong>here</strong></a>, as it is easier to update there compared to Medium. The process is divided into three Python files (.ipynb): one for preparing the training and testing dataset, another for building the machine learning (ML) model, and the last for applying the model to the PlanetScope data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AV2fdg_xhLmzE19o0FBDXQ.png" /><figcaption><a href="https://github.com/mwahyur46/benthic_habitat_classification.git">GitHub repository</a></figcaption></figure><h4>Preparing the training and testing dataset</h4><p>Although I have already included markdown notes in the .ipynb files within the repository, I will add some additional details that are not included there. This stage involves four main steps: describing the bands in the PlanetScope data, extracting pixel values, creating the training and testing dataset, and handling the class imbalance.</p><p>The step of adding a description to the data can technically be skipped if we are completely familiar with the structure or order of the bands. However, incorporating features like geomorphology (e.g., bathymetry) could complicate the process. To ensure clarity and consistency, it is best to keep this step in the workflow.</p><pre># Retrieve the list of band descriptions from the dataset<br>desc = dataset.descriptions<br><br># If descriptions are not available, create manual descriptions<br>if not desc or all(d is None for d in desc):<br>    desc = [&quot;B1&quot;, &quot;B2&quot;, &quot;B3&quot;, &quot;B4&quot;, &quot;B5&quot;, &quot;B6&quot;, &quot;B7&quot;, &quot;B8&quot;]<br><br># Create a dictionary to associate band descriptions with their indices after transpose<br>band_descriptions = {f&quot;Band {i+1}&quot;: desc[i] for i in range(len(desc))}<br><br># Display the dimensions and descriptions for each band<br>print(&quot;\nDimensions of the raster data after transpose:&quot;, planetscope.shape)<br>print(&quot;Descriptions for each band after transpose:&quot;)<br>for band, description in band_descriptions.items():<br>    print(f&#39;{band}: {description}&#39;)</pre><p>The benthic habitat biodiversity in the Gili Islands shows a minimal presence of the Microalgal Mats class, resulting in a highly imbalanced sample distribution compared to other classes. This imbalance could potentially cause the GeoAI model to become biased or perform better at predicting the majority classes [5]. To address this, I applied random oversampling to increase the sample size of the minority class. For this, I used the RandomOverSampler module from the imblearn library to oversample the training dataset.</p><p>The biodiversity of benthic habitats in the Gili Islands shows a minimal presence of the Microalgal Mats class, leading to a highly imbalanced sample distribution compared to other classes. This imbalance could potentially cause the GeoAI model to become biased or perform better at predicting the majority classes [5]. To address this issue, I applied random oversampling to increase the sample size of the minority class. For this purpose, I used the RandomOverSampler module from the imblearn library to oversample the training dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gOypCS_MyGkDooEVijAAIQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Xns8Z9Tr0Lnzmk_U.png" /><figcaption>Microalgal Mats class (left) and oversampling results for the minority class (right) [3].</figcaption></figure><h3>Building the GeoAI model</h3><p>The outline for building the GeoAI model includes importing the training and test datasets, hyperparameter tuning, and model evaluation. The GeoAI model is constructed using the Extreme Gradient Boosting (XGBoost) ML algorithm, implemented via the XGBClassifier function from the xgboost library. While Random Forest, another tree-based algorithm, is a more common choice for benthic habitat classification, I was intrigued by claims of XGBoost’s superior efficiency [6].</p><p>XGBoost utilizes the boosting approach, iteratively improving model performance by combining weak learners. These learners, which start with errors, are refined to reduce inaccuracies [7][8]. In contrast, Random Forest employs bagging, aggregating decision trees that are trained independently or in parallel [6].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*P52uI8AxrI18h9w-.png" /><figcaption>The workflow of boosting-based ML algorithms that iteratively improve weak learners [7]</figcaption></figure><p>Another critical step in building the GeoAI model is hyperparameter tuning. I used the grid search method to find the most optimal combination of available XGBoost hyperparameters. Additionally, 5-Fold Cross-Validation (CV) was utilized for training and testing to assess performance. During this process, the model trains on 4 of the 5 folds (training data) and evaluates the remaining fold (testing data). This cycle repeats five times, ensuring that each fold serves as the testing set once. A complete list of XGBoost hyperparameters is available <a href="https://xgboost.readthedocs.io/en/latest/parameter.html">here</a>.</p><pre># Define a list of parameters for hyperparameter tuning<br># List of the parameters<br>param_list = {<br>    &#39;n_estimators&#39;: [50, 100, 300], #  Number of trees to build in the model. Trying 50, 100, and 300 trees.<br>    &#39;max_depth&#39;: [3, 6, 9], # Maximum depth of each tree. Trying depths of 3, 6, and 9.<br>    &#39;eta&#39;: [0.1, 0.3, 0.5], # Controls the step size of the learning process. Trying values of 0.1, 0.3, and 0.5.<br>    &#39;gamma&#39;: [0, 0.1, 0.2], # Minimum loss reduction required for further partitioning a leaf node. Trying values of 0, 0.1, and 0.2.<br>    &#39;subsample&#39;: [0.8, 1.0], # Fraction of the training data to use for fitting each tree. Trying 0.8 and 1.0.<br>    &#39;colsample_bytree&#39;: [0.8, 1.0], # Fraction of features to use for each tree. Trying 0.8 and 1.0.<br>}<br><br># 5-fold cross-validation GridSearchCV<br>grid_search = GridSearchCV(<br>    xgb_model,            # The model you want to tune (XGBoost classifier)<br>    param_list,           # The grid of hyperparameters to search<br>    cv=5,                 # Number of folds for cross-validation (5-fold)<br>    scoring=&#39;accuracy&#39;,   # The metric used to evaluate model performance (accuracy)<br>    n_jobs=-1,            # Use all available CPU cores for parallel processing<br>    verbose=5             # Display progress and information (higher value gives more details)<br>)</pre><p>The classification evaluation results revealed an overall accuracy (OA) of only 60.19%, which is considered unsatisfactory. The Seagrass class demonstrated the best performance, achieving a Precision/User Accuracy (UA) of 76.93% and a Recall/Producer Accuracy (PA) of 77.63%. In contrast, the Microalgal Mats class showed significantly lower metrics, with a UA of 16% and a PA of 18.18%, despite the application of oversampling. This level of accuracy is understandable, given the inherent difficulty in distinguishing the spectral features of underwater objects, especially in the absence of pre-processing to enhance the quality of the image data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*c5RmEO-kcIqTt_86DyOTag.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*bZSRDry4SLE5xSLuYVLFIw.png" /><figcaption>Confusion matrix of benthic habitat classification in Gili Islands</figcaption></figure><h3>Applying the model</h3><p>There are no specific notes for the stage intended to implement the XGBoost model on the PlanetScope dataset. However, the classification output consistently indicates that deep water and land are categorized as Rock. I have assigned a value of -9999 to the NoData (null) pixels in the function for processing the dataset. A temporary solution is to mask with a shallow water polygon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*t-Or3Em_UfiTGLksJsKx6w.png" /><figcaption>Benthic habitat classification output in Gili Islands</figcaption></figure><p>Since map visualization in Python is less intuitive, I prefer to create the map layout elsewhere to enhance the options. I use QGIS and Figma as usual.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WdiK1os9PBvlMPz74m4nEQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-w6uiCqZ3MDUu9X3r4Lkog.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q2xftGoNCZy5RpktLb8q9g.png" /><figcaption>Sample points, line transect and ndwi (shallow water area)</figcaption></figure><p>I just noticed while making the map layout that there is a thin haze or clouds (?) in the shallow water area in the northern part of Gili Meno 😔</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JOfsZnkiqtTbU_Hs0x2OHg.png" /><figcaption>Benthic habitat classification map in Gili Islands</figcaption></figure><h3>References</h3><p>[1] Roelfsema, C. (2010). Integrating field data with high spatial resolution multispectral satellite imagery for calibration and validation of coral reef benthic community maps. Journal of Applied Remote Sensing, 4(1), 043527. <a href="https://doi.org/10.1117/1.3430107">https://doi.org/10.1117/1.3430107</a></p><p>[2] Hedley, J. D., Roelfsema, C., Brando, V., Giardino, C., Kutser, T., Phinn, S., Mumby, P. J., Barrilero, O., Laporte, J., &amp; Koetz, B. (2018b). Coral Reef Applications of Sentinel-2: Coverage, characteristics, bathymetry and benthic mapping with comparison to Landsat 8. <em>Remote Sensing of Environment</em>, <em>216</em>, 598–614. <a href="https://doi.org/10.1016/j.rse.2018.07.014">https://doi.org/10.1016/j.rse.2018.07.014</a></p><p>[3] Wicaksono, P., Aryaguna, P. A., &amp; Lazuardi, W. (2019). Benthic habitat mapping model and cross-validation using machine-learning classification algorithms. <em>Remote Sensing</em>, <em>11</em>(11), 1279. <a href="https://doi.org/10.3390/rs11111279">https://doi.org/10.3390/rs11111279</a></p><p>[4] O’Donohue, D. (2024, October 1). Understanding spectral reflectance in remote sensing. mapscaping.com. <a href="https://mapscaping.com/understanding-spectral-reflectance-in-remote-sensing/">https://mapscaping.com/understanding-spectral-reflectance-in-remote-sensing/</a>. Diakses pada 24 Desember 2024.</p><p>[5] Tang, T. (2023, April 25). Class imbalance strategies — A visual guide with code. Medium. <a href="https://towardsdatascience.com/class-imbalance-strategies-a-visual-guide-with-code-8bc8fae71e1a">https://towardsdatascience.com/class-imbalance-strategies-a-visual-guide-with-code-8bc8fae71e1a</a>. Accessed 24 December 2024.</p><p>[6] Shao, Z., Ahmad, M. N., &amp; Javed, A. (2024). Comparison of Random Forest and XGBoost Classifiers Using Integrated Optical and SAR Features for Mapping Urban Impervious Surface. Remote Sensing, 16(4), 665. <a href="https://doi.org/10.3390/rs16040665">https://doi.org/10.3390/rs16040665</a></p><p>[7] Chen, T., &amp; Guestrin, C. (2016). XGBoost. Proceedings of the 22nd ACM SIGKDD International Conference on Knowledge Discovery and Data Mining, 785–794. <a href="https://doi.org/10.1145/2939672.2939785">https://doi.org/10.1145/2939672.2939785</a></p><p>[8] GeeksforGeeks. (2023, February 6). XGBoost. <a href="https://www.geeksforgeeks.org/xgboost/">https://www.geeksforgeeks.org/xgboost/</a>. Accessed 24 December 2024.</p><p>[9] Wicaksono, P., &amp; Harahap, S. D. (2023). Mapping seagrass biodiversity indicators of Pari Island using multiple worldview-2 bands derivatives. <em>Geosfera Indonesia</em>, <em>8</em>(2), 189. <a href="https://doi.org/10.19184/geosi.v8i2.41214">https://doi.org/10.19184/geosi.v8i2.41214</a></p><p>Connect with me on <a href="http://linkedin.com/in/mwahyur"><strong>LinkedIn</strong></a></p><h3>Before you go</h3><ul><li>Please take a moment to like the post and follow the writer!</li><li>Did you know that over 400,000 developers share what they’re building, learning, and discovering across our platforms every month? Learn how you can contribute <a href="https://plainenglish.io/write-for-us">here</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=05159932f02b" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/exploring-pixels-beneath-05159932f02b">Exploring Pixels Beneath</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Feature Engineering: Feature Selection]]></title>
            <link>https://ai.plainenglish.io/feature-engineering-feature-selection-ad688dc77426?source=rss-f79aaab49237------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad688dc77426</guid>
            <category><![CDATA[geospatial]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[remote-sensing]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Wahyu Ramadhan]]></dc:creator>
            <pubDate>Mon, 02 Dec 2024 11:02:14 GMT</pubDate>
            <atom:updated>2024-12-23T10:20:25.896Z</atom:updated>
            <content:encoded><![CDATA[<h4>The initial and fundamental stage of developing a GeoAI model</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1y4f75qV3fBp3BQmKiGClQ.png" /></figure><p>Halo semuanya,</p><p>A paradigm shift occurred in geoscience branches like geographic information science and remote sensing. The focuses have shifted from algorithmic approaches using mainly deterministic models for geospatial analysis to the development of heuristics, supported, for example, by Artificial Intelligence (AI), Machine Learning (ML), and Deep Learning (DL). This statement is my conclusion after various insights during the lectures and with professors on campus.</p><p>This transition makes us flexible in identifying patterns from data without having to follow through a rigid set of rules. In this context, AI can develop and induce insights from data, not unlike human intuition in the process of decision-making. While the results are usually not 100% perfect, there is justification that explains these imperfections. But that is just exactly where the beauty lies.</p><p>I might start content on this blog with the theme of Geospatial Artificial Intelligence (GeoAI). I don’t think it will be a series like #BelajarGEE. Besides being easy to adjust, GEE can be integrated with GeoAI through Python, as shown in content from my friend <a href="https://medium.com/u/4a6ebe92c5d2">Yakub Hariana</a>. As is commonly done, data processing should begin with pre-processing, and one important step is Feature Engineering.</p><p>In the era of big data today, one aspect of feature engineering — namely feature selection — can greatly assist our work. When preparing high-dimensional data for GeoAI, whether for Machine Learning (ML) or Deep Learning (DL), feature selection helps reduce noise, and eliminate redundant and irrelevant features, which ultimately decreases computational load and improves model accuracy. The assumption is that by processing only the most relevant features, the AI model becomes better at interpretation, prediction, and preventing overfitting [1] [2].</p><p>To give a brief example, let’s say we want to perform multispectral classification using an image with 12 bands. Not all features (in this case, the bands of the image) are necessarily significant for predictions made by the AI model. The irrelevant features are removed to improve the efficiency or accuracy of the model. This aligns with what American mathematician Richard Ernest Bellman said about the Curse of Dimensionality in 1961. We are experiencing the effects of this now due to the exponential growth of data. I believe the compromise lies in managing data more efficiently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YAsGTa5ddxiFqqAB.png" /><figcaption>Feature selection (<a href="https://towardsdatascience.com/an-introduction-to-feature-selection-dd72535ecf2b">sumber</a>)</figcaption></figure><h3>Preparing Training Samples</h3><h4>Download the Required Materials</h4><p>The materials I use for performing feature selection are twofold: raster imagery and training samples for labeling the raster data. To make it easier, I’m using data from <a href="https://wahyu-ramadhan.medium.com/limitasi-pada-data-cobalah-hal-ini-85ec90b70fe2">my previous content</a>. Download the materials below:</p><ol><li><a href="https://1drv.ms/i/s!AhfNAWExLGYtr89i0aBMZo79pguxZw?e=DTOEFw">Sentinel-2 data</a></li><li><a href="https://1drv.ms/u/s!AhfNAWExLGYtr89poxdqeOlucc1KcQ?e=gouuj7">Training sample</a> for labeling the data</li></ol><h4>Convert Training Samples to Raster</h4><p>This step can be done using QGIS. Here’s how:</p><ol><li>Convert the projection system of the vector-format training sample (the one I used has a .geojson extension) to UTM.</li><li>Rasterize it using the settings shown below.</li><li>Reproject the raster back to the geographic coordinate system</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HNUiD2ZufXn8EzniyJzMTA.png" /><figcaption>Rasterize the training sample</figcaption></figure><p>The training samples used represent land cover classes, with each class labeled by a number from 1 to 7, corresponding to the following object names in order: water, built-up land, agricultural vegetation, vegetation, mangrove, low vegetation, and clouds. When converted to raster format, these numbers change and are recognized as raster values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*LzB2hel26aMZQDAqfve3Rg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*NUrX7SlTvlW8_Jy7_t5yRQ.png" /><figcaption>Class label(left) represented by class number in the ‘lc’ column (right)</figcaption></figure><h4>Preparing the Anaconda environment</h4><p>We will use Python to process the data from here. There are no restrictions on the Integrated Development Environment (IDE) that can be used; it can be cloud-based like Google Colab or Kaggle or desktop-based like Jupyter Notebook, PyCharm, and Visual Studio Code (VSCode) with Jupyter and Python extensions. However, so far, I feel most comfortable using VSCode.</p><p>I use Anaconda because it comes with many pre-installed Python libraries and packages. After installing Anaconda, the next step is to create a virtual environment to avoid conflicts between different versions of libraries and Python packages. To create and activate it, open the Anaconda Prompt. If you’re using Windows, search for ‘Anaconda Prompt’ in the Start menu. Then, enter the following command if you want to create a virtual environment named ‘geo’.</p><pre>conda create -n geo python=3.12<br>conda activate geo</pre><p>Make sure with ctrl+shift+P, then Select Interpreter and choose the previously created virtual environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*Fuj_wEynVQKcRTdfkAkaUg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*__FtZ4T61QHsInDqZl2fFg.png" /><figcaption>Select Python environment and install Jupyer extension in VSCode</figcaption></figure><h4>Create a Notebook File and Organize the Folder Structure</h4><p>Place the training sample and image files in the ‘Data’ folder, which should be inside the main project folder. Then, create a Python notebook file with the .ipynb extension inside it. To do this, right-click on the project folder and select ‘New File’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*UOwxmKRgtgA9QX4pT7uzWw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*-A4LH9rG1We_LzqmMYRJAg.png" /><figcaption>Folder structure and Python notebook file creation</figcaption></figure><h4>Convert training sample into CSV</h4><p>We need to convert the training samples into a tabular format, as most Python libraries work with this format. This type of data is also referred to as a Python dataframe when it has column headers, similar to attribute tables in vector data. Meanwhile, a matrix or Python array (which can be 2D or multidimensional) represents raster data. Why is this the case? Because Python libraries, including those for Machine Learning (ML) such as Scikit-learn, TensorFlow, and PyTorch, are designed to be compatible with tabular data manipulation [3] [4]. The most common libraries for handling Python arrays are Numpy, Pandas for dataframes, and Geopandas for geospatial dataframes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/0*g-hd19lelvceuprm.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*bcKdzcTDkkY1Y_Hr" /><figcaption>Python array and dataframe (left) (<a href="https://www.geeksforgeeks.org/convert-a-numpy-array-to-pandas-dataframe-with-headers/">source</a>), type of array dimensions (right), if the data is multispectral which also means a multidimensional array (<a href="https://indianaiproduction.com/python-numpy-array/">source</a>)</figcaption></figure><p><strong>Python libraries used:</strong></p><ol><li>rasterio: Recognizes raster geospatial data, including resampling (changing spatial resolution) and changing projection systems.</li><li>numpy: Recognizes and manipulates Python arrays.</li><li>pandas: Manipulates Python dataframes.</li></ol><pre>import rasterio<br>from rasterio.enums import Resampling<br>from rasterio.warp import reproject, calculate_default_transform<br>from rasterio.mask import mask<br>import numpy as np<br>import pandas as pd<br><br>def training_sample(raster_path, roi_path, output_csv_path):<br>    # Load raster data<br>    raster = rasterio.open(raster_path)<br>    <br>    # Load training sample<br>    roi = rasterio.open(roi_path)<br><br>    # Calculate the transform and dimensions for the resampled roi<br>    transform, width, height = calculate_default_transform(roi.crs, raster.crs, raster.width, raster.height, *raster.bounds)<br><br>    # Create an array to hold the resampled data<br>    roi_resampled = np.empty(shape=(height, width), dtype=roi.dtypes[0])<br><br>    # Reproject the roi to match the raster data<br>    reproject(<br>    source=rasterio.band(roi, 1),<br>    destination=roi_resampled,<br>    src_transform=roi.transform,<br>    src_crs=roi.crs,<br>    dst_transform=raster.transform,<br>    dst_crs=raster.crs,<br>    resampling=Resampling.nearest<br>    )<br><br>    # Create a mask from the resampled roi<br>    roi_mask = roi_resampled != roi.nodata<br><br>    # Apply the mask to the raster data<br>    raster_data = raster.read()<br>    raster_masked = np.where(roi_mask, raster_data, np.nan)<br><br>    # Stack the layers<br>    stacked_data = np.vstack([roi_resampled[np.newaxis, ...], raster_masked])<br><br>    # Convert to DataFrame, set the class and band names (depend on what raster data that you use, this case is for Sentinel-2)<br>    df = pd.DataFrame(<br>        stacked_data.reshape(stacked_data.shape[0], -1).T,<br>        columns=[&quot;class&quot;, &quot;B2&quot;, &quot;B3&quot;, &quot;B4&quot;, &quot;B5&quot;, &quot;B6&quot;, &quot;B7&quot;, &quot;B8&quot;, &quot;B8A&quot;, &quot;B9&quot;, &quot;B11&quot;, &quot;B12&quot;])<br>    <br>    # Filter out unwanted class values and ensure &#39;class&#39; column is integer<br>    valid_classes = [1, 2, 3, 4, 5, 6, 7]<br>    df = df[df[&#39;class&#39;].isin(valid_classes)]<br><br>    # Convert &#39;class&#39; column to integer<br>    df[&#39;class&#39;] = df[&#39;class&#39;].astype(int)<br><br>    # Remove rows with missing values<br>    df_clean = df.dropna()<br><br>    # Save to CSV<br>    df_clean.to_csv(output_csv_path, index=False)<br><br>    print(f&quot;CSV file created succesfully! {df_clean}&quot;)<br><br># Run the function<br>training_sample(<br>    raster_path=r&quot;....Your Path\Data\s2_median.tif&quot;,<br>    roi_path=r&quot;....Your Path\Data\Training sample Lampung_gcs.tif&quot;,<br>    output_csv_path=r&quot;....Your Path\Data\1. training_data_new2.csv&quot;<br>)</pre><p>The output CSV will have a column named class representing the land cover class, followed by the names of the bands from Sentinel-2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*-TmbgJ7fAr-Dz2uzH5m5Zw.png" /><figcaption>CSV output</figcaption></figure><h3>Feature selection process</h3><p>There are several methods of feature selection; this time, I’ll try the most common: Boruta and Recursive Feature Elimination. These two methods are considered efficient, flexible in integration with various algorithms, and allow a reduction of overfitting. Of course, we have to make compromises. For instance, Boruta selects the features that are likely relevant but are quite resource-consuming. On the other hand, RFE is lighter but may remove important features [5] [6].</p><h4>Import the Boruta library</h4><p>Let’s start with using Boruta. To import the library, use the following command. If you do not have it installed on your computer, open the Anaconda prompt and use the command conda install boruta to download it. In this step, we will import Boruta and RandomForestClassifier from Scikit-learn.</p><pre>import sklearn<br>import boruta<br><br>from sklearn.ensemble import RandomForestClassifier</pre><p>Load training sample (.csv) that was previously created.</p><pre>sample_path = r&quot;....Your Path\Data\1. training_data.csv&quot;<br><br>df = pd.read_csv(sample_path)<br>print(f&quot;Training Data Prop {df.head()}&quot;, f&quot;Training Data{df.info}&quot;)</pre><p>A little tip to quickly get the directory of a file in VSCode, right-click the file in question and select Copy Path.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/469/1*okAKsDl_rRKJ-_BOpxI3Qg.png" /><figcaption>Quickly get file directory in the VSCode</figcaption></figure><h4>Split data into training and test sets</h4><p>As is common in machine learning, we need to split the sample data into two sets: one for training and one for testing. Here’s a brief explanation:</p><ul><li>x = df.iloc[:, 1:]: This selects all columns from the dataframe (training sample) except the first column, which contains the class labels.</li><li>y = df.iloc[:, 0]: The first column of the dataframe is used as the target.</li></ul><pre>from sklearn.model_selection import train_test_split<br><br>x = df.iloc[:, 1:]<br>y = df.iloc[:, 0]<br><br>x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.33, random_state=42)<br>print(f&quot;X train {x_train}&quot;)<br>print(f&quot;X test {x_test}&quot;)<br>print(f&quot;Y test {y_test}&quot;)<br>print(f&quot;Y train {y_train}&quot;)</pre><h4>Feature Selection with Boruta</h4><p>This step involves configuring feature selection with Boruta. I want to be a bit more aggressive by adjusting some parameters, such as:</p><ul><li>max_depth = 10: A larger tree depth, with the assumption that it can capture more complex patterns.</li><li>alpha = 0.01: Tightening the selection criteria, meaning only the most significant features will be selected. The risk is that some features, which may be relevant, might be overlooked due to the stricter criteria.</li><li>max_iter = 50: The maximum number of iterations in the feature selection process.</li></ul><p>This aggressive configuration is not always necessary, considering its consequences, such as increased computational load and the risk of overfitting.</p><pre>from boruta import BorutaPy<br><br># Numpy file type, in case you have a newer version of Numpy<br>np.int = np.int32<br>np.float = np.float64<br>np.bool = np.bool_<br><br># max_depth: A deeper tree might capture more complex patterns, but it could also lead to overfitting.<br>rf = RandomForestClassifier(n_jobs=1, class_weight=&#39;balanced&#39;, max_depth=10)<br><br># Define boruta selection method<br>boruta_selector = BorutaPy(<br>    rf,<br>    n_estimators = &#39;auto&#39;,<br>    verbose = 2,<br>    random_state = 1,<br>    alpha = 0.01,<br>    max_iter = 50 # Number of iterations, in case you want to do more &#39;aggresive&#39; approach<br>)<br><br># Find all relevant features - 5 features should be selected - Convert training data to numpy arrays<br>x_train2 = np.array(x_train)<br>y_train2 = np.array(y_train)<br><br>boruta_selector.fit(x_train2, y_train2)<br><br>print(f&quot;Ranking: {boruta_selector.ranking_}&quot;)<br>print(f&quot;Nr. of significant features: {boruta_selector.n_features_}&quot;)</pre><p>The process will show this kind of report in the console that explains the result of iteration and the number of relevant features selected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*xMRWA_rWz-AvPuKGssAxWA.png" /><figcaption>Feature selection report with Boruta</figcaption></figure><h4>Save the training and test data</h4><p>Use the following command to save the results of feature selection with Boruta.</p><pre># Feature selection<br>feature_index = boruta_selector.ranking_.astype(bool)<br><br># Save training data<br>selected_train = pd.concat([x_train.loc[:, feature_index], y_train], axis=1)<br>selected_train.to_csv(r&quot;....Your Path\Data\2. selected_features_train_data_boruta.csv&quot;, index=False)<br><br># Save test data<br>selected_test = pd.concat([x_test.loc[:, feature_index], y_test], axis=1)<br>selected_test.to_csv(r&quot;...Your Path\Data\3. selected_features_test_data_boruta.csv&quot;, index=False)</pre><h4>Feature selection with RFE</h4><p>The steps are similar to Boruta, but the difference lies in the RFE configuration. You should still use the training and test data that has already been split for the configuration below. Additionally, we will print the names and count of the features that have been successfully selected in the console.</p><p>The description of the RFE configuration used is as follows:</p><ul><li>estimator: Just like in Boruta, use RandomForestClassifier it as the base model.</li><li>step: The number of features to remove at each iteration.</li><li>cv (5): Use StratifiedKFold with 5 folds for cross-validation.</li><li>scoring: The metric used to evaluate the model’s performance, in this case, is ‘accuracy’.</li><li>min_features_to_select: The minimum number of features to select.</li></ul><pre>from sklearn.feature_selection import RFECV<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.model_selection import StratifiedKFold<br><br># Configure RFE selector<br>selector = RFECV(<br>    estimator=RandomForestClassifier(n_jobs=1, class_weight=&#39;balanced&#39;, max_depth=10),<br>    step = 1 ,<br>    cv = StratifiedKFold(5),<br>    scoring=&#39;accuracy&#39;,<br>    min_features_to_select=10,<br>    n_jobs = 1<br>)<br><br>selector = selector.fit(x_train, y_train)<br><br># Get selected feature names and number<br>feature_names = selector.get_feature_names_out()<br>feature_number = selector.n_features_<br><br># Print feature name and number in the console<br>print(f&quot;Selected features {feature_names}&quot;)<br>print(f&quot;Number of selected features {feature_number}&quot;)</pre><p>The result will look like this. Compare it with the training data that hasn’t gone through feature selection. Pay attention to whether any Sentinel-2 bands were eliminated during this process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*jfjINfGtAyjmuMIf3lNixA.png" /><figcaption>Sentinel-2 features considered relevant by RFE</figcaption></figure><h4>Save the training and test data</h4><p>Use the following command to save the results of feature selection with RFE.</p><pre># Save filtered training data<br>pd.concat([x_train[feature_names], y_train], axis=1).to_csv(<br>    r&quot;...Your Path\Data\2. selected_features_train_data_rfe.csv&quot;, <br>    index=False<br>)<br><br># Save filtered test data<br>pd.concat([x_test[feature_names], y_test], axis=1).to_csv(<br>    r&quot;...Your Path\Data\3. selected_features_test_data_rfe.csv&quot;, <br>    index=False<br>)</pre><p><strong>To make sure…</strong></p><p>Both Boruta and RFE will generate this kind of CSV or dataframe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*SN_zFT4BRC09oJ5WraM4Eg.png" /><figcaption>RFE feature selection result</figcaption></figure><h3>References</h3><p>[1] Li, J., Cheng, K., Wang, S., Morstatter, F., Trevino, R. P., Tang, J., &amp; Liu, H. (2017). Feature selection. <em>ACM Computing Surveys</em>, <em>50</em>(6), 1–45. <a href="https://doi.org/10.1145/3136625">https://doi.org/10.1145/3136625</a><br>[2] Venkatesh, B., &amp; Anuradha, J. (2019). A review of feature selection and its methods. <em>Cybernetics and Information Technologies</em>, <em>19</em>(1), 3–26. <a href="https://doi.org/10.2478/cait-2019-0001">https://doi.org/10.2478/cait-2019-0001</a><br>[3] (<a href="https://pygis.io/docs/f_rs_ml_predict.html">https://pygis.io/docs/f_rs_ml_predict.html</a>)<br>[4] <a href="https://www.learndatasci.com/tutorials/geospatial-data-python-geopandas-shapely/">https://www.learndatasci.com/tutorials/geospatial-data-python-geopandas-shapely/</a><br>[5] <a href="https://www.machinelearningplus.com/machine-learning/feature-selection/">https://www.machinelearningplus.com/machine-learning/feature-selection/</a><br>[6] <a href="https://blog.kxy.ai/effective-feature-selection/index.html">https://blog.kxy.ai/effective-feature-selection/index.html</a><br>[7] <a href="https://github.com/scikit-learn-contrib/boruta_py">GitHub — scikit-learn-contrib/boruta_py: Python implementations of the Boruta all-relevant feature selection method.</a><br>[8] <a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.RFE.html">https://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.RFE.html</a></p><p>Connect with me on <a href="http://linkedin.com/in/mwahyur"><strong>LinkedIn</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad688dc77426" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/feature-engineering-feature-selection-ad688dc77426">Feature Engineering: Feature Selection</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Feature Engineering: Feature Selection]]></title>
            <link>https://wahyu-ramadhan.medium.com/feature-engineering-feature-selection-fc5b55df8e4a?source=rss-f79aaab49237------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc5b55df8e4a</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[geospatial]]></category>
            <category><![CDATA[maps]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[remote-sensing]]></category>
            <dc:creator><![CDATA[Wahyu Ramadhan]]></dc:creator>
            <pubDate>Sat, 28 Sep 2024 14:00:03 GMT</pubDate>
            <atom:updated>2025-06-10T15:35:26.272Z</atom:updated>
            <content:encoded><![CDATA[<h4>Tahap awal dan fundamental dalam membangun model GeoAI</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Kw6XhvLrVnMvAWZQeqtIQ.png" /></figure><p>Halo semuanya,</p><p>Perubahan paradigma telah dialami oleh cabang-cabang ilmu geosains, sebut saja sains informasi geografi dan/atau penginderaan jauh. Pada mulanya fokus pada pendekatan algoritmik dalam penggunaan model deterministik untuk analisis geospasial. Sekarang perkembangannya bergeser ke arah heuristik, lebih tepatnya <em>Artificial Intelligence </em>(AI) yang dapat diiris lagi menjadi <em>Machine Learning </em>(ML) dan <em>Deep Learning </em>(DL). <em>Statement </em>tanpa sitasi tersebut sejujurnya adalah simpulan saya dari <em>cipratan-cipratan ilmu </em>selama kuliah master hingga <em>ngobrol </em>dengan dosen di kampus.</p><p>Transisi ini membuat kita lebih fleksibel dalam menemukan pola dari suatu data tanpa harus melewati rangkaian aturan yang cenderung kaku. Dalam konteks ini AI mampu mengembangkan dan menyimpulkan sesuatu dari kumpulan data selayaknya intuisi<em> </em>manusia dalam mengambil keputusan. Memang seringkali hasilnya tidak seratus persen sempurna, ada justifikasi yang bisa menjelaskan ketidaksempurnaan itu. Tapi, justru di situlah letak seninya 😁.</p><p>Mungkin akan mengawali konten dengan tema Geospatial Artificial Intelligence (GeoAI) di blog ini. Saya pikir tidak akan berseri seperti <strong>#BelajarGEE</strong>, selain akan mudah disesuaikan, GEE juga sebetulnya bisa diintegrasikan dengan GeoAI melalui Python seperti konten teman saya <a href="https://medium.com/u/4a6ebe92c5d2">Yakub Hariana</a> <a href="https://medium.com/@yakubhariana70/use-python-for-earth-engine-analysis-save-directly-to-your-local-drive-5434dfc59c4a">ini</a>. Seperti pada umumnya, pengolahan data sebaiknya diawali dengan <em>pre-processing</em>, salah satunya adalah <em>Feature Engineering</em>.</p><p><em>Well</em>, di era <em>big data </em>sekarang, salah satu bagian dari <em>feature engineering </em>yakni <em>feature selection</em> dapat membantu kerja kita. Apabila kita mempersiapkan data berdimensi besar untuk GeoAI baik ML atau DL, <em>feature selection </em>akan mengurangi <em>noise</em>, mengeliminasi fitur-fitur redundan dan kurang relevan sehingga ujungnya adalah mengurangi beban komputasi serta meningkatkan akurasi model. Asumsinya adalah dengan hanya fitur-fitur paling relevan yang diolah, maka model AI makin mudah melakukan interpretasi, prediksi maupun mencegah <em>overfitting </em>[1] [2].</p><p>Sedikit gambaran, misalnya kita ingin melakukan klasifikasi multispektral menggunakan citra dengan 12 <em>band</em>, belum tentu semua fitur (dalam hal ini adalah <em>band</em> dari citra) punya signifikansi pada prediksi oleh model AI. Fitur-fitur yang tidak relevan tersebut akan dihapus untuk meningkatkan efisiensi atau akurasi model. Sejalan dengan matematikawan Amerika yakni <a href="https://en.wikipedia.org/wiki/Richard_E._Bellman">Richard Ernest Bellman</a> yang mengatakan <a href="https://en.wikipedia.org/wiki/Curse_of_dimensionality"><em>Curse of Dimensionality</em></a> pada 1961, kenyataanya baru kita rasakan sekarang akibat pertumbuhan data yang eksponensial. Saya rasa bentuk komprominya adalah melakukan manajemen data secara lebih efisien.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YAsGTa5ddxiFqqAB.png" /><figcaption>Ilustrasi feature selection (<a href="https://towardsdatascience.com/an-introduction-to-feature-selection-dd72535ecf2b">sumber</a>)</figcaption></figure><h3>Mempersiapkan training sample</h3><h4><strong>Unduh bahan yang dibutuhkan</strong></h4><p>Bahan yang saya gunakan untuk melakukan <em>feature selection </em>ini ada dua, yaitu citra raster dan <em>training sample </em>untuk memberi label kelas pada data raster. Supaya lebih mudah, saya gunakan data dari konten saya <a href="https://wahyu-ramadhan.medium.com/limitasi-pada-data-cobalah-hal-ini-85ec90b70fe2">sebelumnya</a>. Unduh bahan di bawah:</p><ol><li><a href="https://1drv.ms/i/s!AhfNAWExLGYtr89i0aBMZo79pguxZw?e=DTOEFw"><strong>Citra Sentinel-2</strong></a></li><li><a href="https://1drv.ms/u/s!AhfNAWExLGYtr89poxdqeOlucc1KcQ?e=gouuj7"><strong><em>Training sample</em></strong></a> untuk memberi label kelas pada data</li></ol><h4><strong>Ubah training sample menjadi raster</strong></h4><p>Tahap ini dapat dilakukan dengan QGIS. Caranya: 1) ubah sistem proyeksi <em>training sample</em> berformat vektor (yang saya gunakan memiliki ekstensi <em>.geojson</em>) menjadi UTM; 2) <em>rasterize </em>dengan pengaturan seperti di bawah ini; 3) <em>reproject raster</em> agar kembali ke sistem koordinat geografis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HNUiD2ZufXn8EzniyJzMTA.png" /><figcaption>Proses rasterize training sample</figcaption></figure><p><em>Training sample </em>yang digunakan adalah kelas penutup lahan, setiap kelas memiliki label yang diwakili nomor 1 sampai 7 dengan nama objek yang berurutan yakni air, lahan terbangun, vegetasi pertanian, vegetasi, mangrove, vegetasi rendah dan awan. Ketika diubah menjadi raster, nomor tersebut berubah dan dikenali sebagai <em>raster value</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*LzB2hel26aMZQDAqfve3Rg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*NUrX7SlTvlW8_Jy7_t5yRQ.png" /><figcaption>Label kelas (kiri) diwakili oleh nomor kelas dalam kolom ‘lc’ (kanan)</figcaption></figure><h4><strong>Mempersiapkan <em>environment </em>Anaconda</strong></h4><p>Mulai dari sini kita akan menggunakan Python untuk memproses data. Integrated Development Enviroment (IDE) yang bisa digunakan tidak ada batasan, bisa berbasis <em>cloud </em>seperti <a href="https://colab.research.google.com/">Google Colab</a>, <a href="https://www.kaggle.com/">Kaggle </a>atau <em>desktop </em>seperti <a href="https://jupyter.org/install">Jupyter Notebook</a>, <a href="https://www.jetbrains.com/pycharm/download/?section=windows">Pycharm </a>dan <a href="https://code.visualstudio.com/download">Visual Studio Code (VSCode)</a> dengan ekstensi Jupyter dan Python. Tapi <em>so far</em> saya lebih nyaman menggunakan VSCode.</p><p>Oh ya, saya menggunakan <a href="https://www.anaconda.com/download">Anaconda </a>karena banyak <em>library </em>dan <em>package </em>Python yang <em>pre-installed</em> di dalamnya. Setelah Anaconda di<em>install</em>, hal yang kita lakukan adalah membuat <em>virtual environment </em>supaya tidak ada konflik antar versi <em>library</em> dan <em>package</em> Python. Cara membuat dan mengaktifkannya adalah buka anaconda prompt, jika konteksnya windows, cari <em>keyword </em>‘anaconda prompt’ pada start menu. Lalu masukkan perintah berikut misalnya ingin membuat <em>virtual environment</em> dengan nama ‘geo’.</p><pre>conda create -n geo python=3.12<br>conda activate geo</pre><p><em>Make sure </em>dengan ctrl+shift+P, lalu pilih Select Interpreter dan pilih <em>virtual environment</em> yang baru saja dibuat.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*Fuj_wEynVQKcRTdfkAkaUg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*__FtZ4T61QHsInDqZl2fFg.png" /><figcaption>Memilih environment dan install ekstensi Jupyter di VSCode</figcaption></figure><h4><strong>Buat file notebook dan atur struktur folder</strong></h4><p>Letakkan file <em>training sample</em> dan citra di folder <strong>Data </strong>yang berada dalam folder utama proyek, lalu buat file Python notebook dengan ekstensi .ipynb di dalamnya. Cara pembuatannya dengan klik kanan pada folder project dan pilih New File.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*UOwxmKRgtgA9QX4pT7uzWw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*-A4LH9rG1We_LzqmMYRJAg.png" /><figcaption>Struktur folder dan pembuatan file Python notebook</figcaption></figure><h4><strong>Ubah training sample menjadi CSV</strong></h4><p>Kita harus mengubah <em>training sample </em>supaya menjadi tabular, karena <em>mostly library </em>Python bekerja dengan format ini. Jenis data ini juga memiliki istilah yakni Python dataframe kalau memiliki <em>head column</em> seperti tabel atribut pada data vektor, sedangkan matriks atau Python array (bisa 2D atau multidimensi) sebagai representasi data raster. Kenapa begitu? Karena <em>library </em>Python termasuk untuk ML seperti Scikit-learn, TensorFlow dan Pytorch didesain kompatibel untuk manipulasi data tabular [3] [4]. <em>Library </em>paling <em>common </em>untuk Python array adalah Numpy, Pandas untuk dataframe serta Geopandas dalam <em>handling </em>Geodataframe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/0*g-hd19lelvceuprm.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*bcKdzcTDkkY1Y_Hr" /><figcaption>Python array dan dataframe (kiri) (<a href="https://www.geeksforgeeks.org/convert-a-numpy-array-to-pandas-dataframe-with-headers/">sumber</a>), jenis dimensi array (kanan), misalnya datanya adalah citra multispektral berarti juga array multidimensi (<a href="https://indianaiproduction.com/python-numpy-array/">sumber</a>)</figcaption></figure><p><strong>Library yang digunakan pada langkah ini adalah</strong>:</p><ol><li>rasterio: Mengenali data citra berformat raster geospasial, termasuk <em>resample </em>(mengubah resolusi spasial) dan mengubah sistem proyeksi.</li><li>numpy: Mengenali dan memanipulasi data Python array.</li><li>pandas: Manipulasi data Python dataframe.</li></ol><pre>import rasterio<br>from rasterio.enums import Resampling<br>from rasterio.warp import reproject, calculate_default_transform<br>from rasterio.mask import mask<br>import numpy as np<br>import pandas as pd<br><br>def training_sample(raster_path, roi_path, output_csv_path):<br>    # Load raster data<br>    raster = rasterio.open(raster_path)<br>    <br>    # Load training sample<br>    roi = rasterio.open(roi_path)<br><br>    # Calculate the transform and dimensions for the resampled roi<br>    transform, width, height = calculate_default_transform(roi.crs, raster.crs, raster.width, raster.height, *raster.bounds)<br><br>    # Create an array to hold the resampled data<br>    roi_resampled = np.empty(shape=(height, width), dtype=roi.dtypes[0])<br><br>    # Reproject the roi to match the raster data<br>    reproject(<br>    source=rasterio.band(roi, 1),<br>    destination=roi_resampled,<br>    src_transform=roi.transform,<br>    src_crs=roi.crs,<br>    dst_transform=raster.transform,<br>    dst_crs=raster.crs,<br>    resampling=Resampling.nearest<br>    )<br><br>    # Create a mask from the resampled roi<br>    roi_mask = roi_resampled != roi.nodata<br><br>    # Apply the mask to the raster data<br>    raster_data = raster.read()<br>    raster_masked = np.where(roi_mask, raster_data, np.nan)<br><br>    # Stack the layers<br>    stacked_data = np.vstack([roi_resampled[np.newaxis, ...], raster_masked])<br><br>    # Convert to DataFrame, set the class and band names (depend on what raster data that you use, this case is for Sentinel-2)<br>    df = pd.DataFrame(<br>        stacked_data.reshape(stacked_data.shape[0], -1).T,<br>        columns=[&quot;class&quot;, &quot;B2&quot;, &quot;B3&quot;, &quot;B4&quot;, &quot;B5&quot;, &quot;B6&quot;, &quot;B7&quot;, &quot;B8&quot;, &quot;B8A&quot;, &quot;B9&quot;, &quot;B11&quot;, &quot;B12&quot;])<br>    <br>    # Filter out unwanted class values and ensure &#39;class&#39; column is integer<br>    valid_classes = [1, 2, 3, 4, 5, 6, 7]<br>    df = df[df[&#39;class&#39;].isin(valid_classes)]<br><br>    # Convert &#39;class&#39; column to integer<br>    df[&#39;class&#39;] = df[&#39;class&#39;].astype(int)<br><br>    # Remove rows with missing values<br>    df_clean = df.dropna()<br><br>    # Save to CSV<br>    df_clean.to_csv(output_csv_path, index=False)<br><br>    print(f&quot;CSV file created succesfully! {df_clean}&quot;)<br><br># Run the function<br>training_sample(<br>    raster_path=r&quot;....Your Path\Data\s2_median.tif&quot;,<br>    roi_path=r&quot;....Your Path\Data\Training sample Lampung_gcs.tif&quot;,<br>    output_csv_path=r&quot;....Your Path\Data\1. training_data_new2.csv&quot;<br>)</pre><p>Output CSV nanti akan memiliki nama kolom class yang mewakili kelas penutup lahan, lalu diikuti dengan nama <em>band </em>dari Sentinel-2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*-TmbgJ7fAr-Dz2uzH5m5Zw.png" /><figcaption>Output CSV</figcaption></figure><h3>Proses variable selection</h3><p>Banyak metode yang dapat digunakan untuk melakukan <em>feature selection</em>, namun kali ini saya akan coba yang sudah <em>common </em>yakni Boruta dan Recursive Feature Elimination (RFE). Kedua metode ini banyak digunakan karena dinilai efisien, fleksibel untuk integrasi pelbagai algoritma sehingga dapat membantu dalam mengurangi <em>overfitting</em>. Tentu kita harus mengambil kompromi, misalnya Boruta fitur yang terpilih kemungkinan besar relevan, tapi cukup <em>resource consuming. </em>Sedangkan RFE lebih ringan, di sisi lain berpotensi mengeliminasi fitur yang sebenarnya penting [5] [6].</p><h4><strong>Impor library Boruta</strong></h4><p>Kita coba pakai Boruta terlebih dahulu, jadi gunakan perintah seperti ini untuk mengimpor <em>library</em>-nya, jika belum terpasang di komputer maka masuk ke Anaconda prompt lalu gunakan perintah berikut untuk mengunduhnya conda install boruta. Pada langkah ini pada dasarnya kita impor boruta dan RandomForestClassifier dari <a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html">Scikit-learn</a>.</p><pre>import sklearn<br>import boruta<br><br>from sklearn.ensemble import RandomForestClassifier</pre><h4><strong>Buka training sample</strong></h4><p>Buka file <em>training sample</em> berformat CSV yang sebelumnya sudah dibuat.</p><pre>sample_path = r&quot;....Your Path\Data\1. training_data.csv&quot;<br><br>df = pd.read_csv(sample_path)<br>print(f&quot;Training Data Prop {df.head()}&quot;, f&quot;Training Data{df.info}&quot;)</pre><p>Sedikit tips untuk mendapatkan direktori dari sebuah file dengan cepat di VSCode, klik kanan file yang dimaksud dan pilih Copy Path.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/469/1*okAKsDl_rRKJ-_BOpxI3Qg.png" /><figcaption>Mendapatkan direktori file di VSCode</figcaption></figure><h4><strong>Bagi data menjadi dua, <em>training </em>dan <em>test</em></strong></h4><p>Seperti <em>machine learning </em>pada umumnya, kita harus membagi data sampel menjadi dua untuk <em>training </em>dan <em>test</em>. Mungkin ada sedikit penjelasan dari sini, yaitu:</p><ul><li>x = df.iloc[:, 1:] : Semua kolom dari dataframe (<em>training sample</em>) <strong>kecuali</strong> kolom pertama yang berisi label kelas.</li><li>y = df.iloc[:,0] : Kolom pertama dari dataframe sebagai target.</li></ul><pre>from sklearn.model_selection import train_test_split<br><br>x = df.iloc[:, 1:]<br>y = df.iloc[:, 0]<br><br>x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.33, random_state=42)<br>print(f&quot;X train {x_train}&quot;)<br>print(f&quot;X test {x_test}&quot;)<br>print(f&quot;Y test {y_test}&quot;)<br>print(f&quot;Y train {y_train}&quot;)</pre><h4><strong>Feature selection dengan Boruta</strong></h4><p>Langkah ini adalah konfigurasi <em>feature selection </em>dengan Boruta, saya ingin sedikit agresif dengan menyesuaikan beberapa hal seperti:</p><ul><li>max_depth = 10 : Kedalaman <em>tree</em> yang lebih besar, asumsinya dapat menangkap pola yang lebih kompleks.</li><li>alpha = 0.01 : Memperketat kriteria seleksi, jadi hanya fitur-fitur paling signifikan yang akan dipilih. Risikonya kemungkinan mengabaikan beberapa fitur yang sebenarnya relevan karena kriteria yang lebih ketat.</li><li>max_iter = 50 : Jumlah maksimal iterasi dalam proses <em>feature selection</em>.</li></ul><p>Agresivitas konfigurasi ini tidak harus selalu dilakukan, mengingat konsekuensinya adalah komputasi yang lebih berat dan overfitting.</p><pre>from boruta import BorutaPy<br><br># Numpy file type, in case you have a newer version of Numpy<br>np.int = np.int32<br>np.float = np.float64<br>np.bool = np.bool_<br><br># max_depth: A deeper tree might capture more complex patterns, but it could also lead to overfitting.<br>rf = RandomForestClassifier(n_jobs=1, class_weight=&#39;balanced&#39;, max_depth=10)<br><br># Define boruta selection method<br>boruta_selector = BorutaPy(<br>    rf,<br>    n_estimators = &#39;auto&#39;,<br>    verbose = 2,<br>    random_state = 1,<br>    alpha = 0.01,<br>    max_iter = 50 # Number of iterations, in case you want to do more &#39;aggresive&#39; approach<br>)<br><br># Find all relevant features - 5 features should be selected - Convert training data to numpy arrays<br>x_train2 = np.array(x_train)<br>y_train2 = np.array(y_train)<br><br>boruta_selector.fit(x_train2, y_train2)<br><br>print(f&quot;Ranking: {boruta_selector.ranking_}&quot;)<br>print(f&quot;Nr. of significant features: {boruta_selector.n_features_}&quot;)</pre><p>Setelah proses berjalan, akan menunjukkan <em>report </em>seperti ini di console yang menjelaskan hasil iterasi dan jumlah fitur relevan yang dipilih.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*xMRWA_rWz-AvPuKGssAxWA.png" /><figcaption>Report feature selection dengan Boruta</figcaption></figure><p><strong>Simpan data training dan test</strong></p><p>Gunakan perintah berikut ini untuk menyimpan hasil <em>feature selection</em> dengan Boruta.</p><pre># Feature selection<br>feature_index = boruta_selector.ranking_.astype(bool)<br><br># Save training data<br>selected_train = pd.concat([x_train.loc[:, feature_index], y_train], axis=1)<br>selected_train.to_csv(r&quot;....Your Path\Data\2. selected_features_train_data_boruta.csv&quot;, index=False)<br><br># Save test data<br>selected_test = pd.concat([x_test.loc[:, feature_index], y_test], axis=1)<br>selected_test.to_csv(r&quot;...Your Path\Data\3. selected_features_test_data_boruta.csv&quot;, index=False)</pre><h3>Feature selection dengan RFE</h3><p>Langkahnya masih sama dengan Boruta, bedanya hanya pada konfigurasi RFE saja. Tetap gunakan <em>training </em>dan <em>test </em>data yang sudah di split untuk konfigurasi di bawah, selain itu kita akan <em>print </em>di <em>console </em>nama dan jumlah fitur yang telah berhasil terseleksi.</p><p>Deskripsi konfigurasi RFE yang digunakan adalah:</p><ul><li>estimator : Masih sama seperti pada Boruta, gunakan RandomForestClassifier sebagai <em>base model</em>.</li><li>step : Jumlah fitur yang dihapus pada setiap iterasi.</li><li>cv (5) : Menggunakan StratifiedKFold dengan 5 lipatan (<em>fold</em>) untuk cross-validation.</li><li>scoring : Metrik yang digunakan untuk evaluasi performa model dalam hal ini adalah ‘accuracy’.</li><li>min_features_to_select : Jumlah minimum fitur yang dipilih.</li></ul><pre>from sklearn.feature_selection import RFECV<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.model_selection import StratifiedKFold<br><br># Configure RFE selector<br>selector = RFECV(<br>    estimator=RandomForestClassifier(n_jobs=1, class_weight=&#39;balanced&#39;, max_depth=10),<br>    step = 1 ,<br>    cv = StratifiedKFold(5),<br>    scoring=&#39;accuracy&#39;,<br>    min_features_to_select=10,<br>    n_jobs = 1<br>)<br><br>selector = selector.fit(x_train, y_train)<br><br># Get selected feature names and number<br>feature_names = selector.get_feature_names_out()<br>feature_number = selector.n_features_<br><br># Print feature name and number in the console<br>print(f&quot;Selected features {feature_names}&quot;)<br>print(f&quot;Number of selected features {feature_number}&quot;)</pre><p>Hasilnya akan seperti ini, bandingkan dengan training data yang belum melalui <em>feature selection</em>, perhatikan apakah ada <em>band </em>dari Sentinel-2 yang dieliminasi oleh proses ini?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*jfjINfGtAyjmuMIf3lNixA.png" /><figcaption>Fitur-fitur Sentinel-2 yang dianggap relevan oleh RFE</figcaption></figure><p><strong>Simpan data <em>training </em>dan <em>test</em></strong></p><p>Gunakan perintah berikut ini untuk menyimpan hasil <em>feature selection</em> dengan RFE.</p><pre># Save filtered training data<br>pd.concat([x_train[feature_names], y_train], axis=1).to_csv(<br>    r&quot;...Your Path\Data\2. selected_features_train_data_rfe.csv&quot;, <br>    index=False<br>)<br><br># Save filtered test data<br>pd.concat([x_test[feature_names], y_test], axis=1).to_csv(<br>    r&quot;...Your Path\Data\3. selected_features_test_data_rfe.csv&quot;, <br>    index=False<br>)</pre><p><strong>Untuk memastikan</strong></p><p>Baik Boruta maupun RFE akan menghasilkan file CSV atau dataframe seperti ini.</p><pre>train_ouput = pd.read_csv(r&quot;...Your Path\Data\2. selected_features_train_data_rfe.csv&quot;)<br>test_output = pd.read_csv(r&quot;...Your Path\Data\3. selected_features_test_data_rfe.csv&quot;)<br><br>print(f&quot;Train output: {train_ouput.head(3)}&quot;)<br>print(f&quot;Test output: {test_output.head(3)}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*SN_zFT4BRC09oJ5WraM4Eg.png" /><figcaption>Hasil feature selection RFE</figcaption></figure><h3>Referensi</h3><p>[1] Li, J., Cheng, K., Wang, S., Morstatter, F., Trevino, R. P., Tang, J., &amp; Liu, H. (2017). Feature selection. <em>ACM Computing Surveys</em>, <em>50</em>(6), 1–45. <a href="https://doi.org/10.1145/3136625">https://doi.org/10.1145/3136625</a><br>[2] Venkatesh, B., &amp; Anuradha, J. (2019). A review of feature selection and its methods. <em>Cybernetics and Information Technologies</em>, <em>19</em>(1), 3–26. <a href="https://doi.org/10.2478/cait-2019-0001">https://doi.org/10.2478/cait-2019-0001</a><br>[3] (<a href="https://pygis.io/docs/f_rs_ml_predict.html">https://pygis.io/docs/f_rs_ml_predict.html</a>)<br>[4] <a href="https://www.learndatasci.com/tutorials/geospatial-data-python-geopandas-shapely/">https://www.learndatasci.com/tutorials/geospatial-data-python-geopandas-shapely/</a><br>[5] <a href="https://www.machinelearningplus.com/machine-learning/feature-selection/">https://www.machinelearningplus.com/machine-learning/feature-selection/</a><br>[6] <a href="https://blog.kxy.ai/effective-feature-selection/index.html">https://blog.kxy.ai/effective-feature-selection/index.html</a><br>[7] <a href="https://github.com/scikit-learn-contrib/boruta_py">GitHub — scikit-learn-contrib/boruta_py: Python implementations of the Boruta all-relevant feature selection method.</a><br>[8] <a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.RFE.html">https://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.RFE.html</a></p><p>Connect with me on <a href="http://linkedin.com/in/mwahyur"><strong>LinkedIn</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc5b55df8e4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Limited Data, Can Classification Be Accurate?]]></title>
            <link>https://wahyu-ramadhan.medium.com/limited-data-can-classification-be-accurate-d4e00402c6ec?source=rss-f79aaab49237------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4e00402c6ec</guid>
            <category><![CDATA[remote-sensing]]></category>
            <category><![CDATA[gis]]></category>
            <category><![CDATA[geospatial]]></category>
            <category><![CDATA[maps]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Wahyu Ramadhan]]></dc:creator>
            <pubDate>Sat, 31 Aug 2024 10:31:41 GMT</pubDate>
            <atom:updated>2024-08-31T10:31:41.897Z</atom:updated>
            <content:encoded><![CDATA[<h4>#LearnGEE 15: Enriching the Potential of Remote Sensing Images with Image Fusion</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZYSaAUndmZjcgheXbb_OyA.png" /></figure><p>Halo semuanya,</p><p>Image classification is an attempt to extract information based on certain characteristics of pixels such as color, texture, shape, size and relation [1] [3]. If the context is multispectral classification (see <a href="https://wahyu-ramadhan.medium.com/remote-sensing-image-classification-strategies-d2f9f42aa0a7">my previous content</a>), it focuses on grouping reflectance values in pixels based on wavelength as a representation of certain objects. So the role and capabilities of spectral bands have a lot of influence on the type of multispectral classification [2].</p><p>The reason why multispectral classification is widely used besides relatively easy data access is that it provides more information than single-band imagery to capture and distinguish spectral features between objects. In addition, this type of classification is quite versatile for various needs, from agriculture, marine, forestry, urban and other environmental monitoring needs [1]. Even so, it is not without its drawbacks, not only does it become more complex when the data size is large, but multispectral imagery is highly dependent on data quality, let’s say radiometric noise [4].</p><p>The disadvantage(s) of multispectral classification is also a potential improvement, not only in the spatial resolution but also in the temporal resolution of the image. As I have mentioned, radiometric disturbances such as cloud cover, haze and fog have the potential to occur (especially in tropical regions during the rainy season) [3]. Improving the overall quality of multispectral data can be achieved by combining it with other sensor data, assuming that it can accommodate the elimination of interference.</p><p>Combining more than one image sensor is commonly referred to as image fusion, which means adding characteristics from various sensors. This aims to enrich the available information and improve the quality of analysis by adding variables [1] [3]. However, the consequence is that the dimensionality of the data becomes more complex, potentially resulting in similar or redundant information and possibly increasing the risk of overfitting the model [8].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*RV4_mb-FIkFgDVqHFNLsLA.png" /><figcaption>Ilustrasi image fusion pada tingkat piksel [3]</figcaption></figure><p>As usual, we will use Google Earth Engine (GEE) for the processing. I will include a link to access the script at the end of this post.</p><h4><strong>Table of Content</strong></h4><p>∘ <a href="#f0f4">Table of Content</a><br>· <a href="#b70a">Pre-Processing</a><br> ∘ <a href="#4938">Load data</a><br> ∘ <a href="#d256">Image resample</a><br> ∘ <a href="#2b7b">Combining image data</a><br>· <a href="#cb19">Processing</a><br> ∘ <a href="#9d4c">Creating training samples</a><br> ∘ <a href="#6aaa">Train the classification model</a><br>· <a href="#979c">Post-Processing</a><br> ∘ <a href="#896d">Summarizing the classification results</a><br> ∘ <a href="#85db">Accuracy test</a><br> ∘ <a href="#ca27">Export the Data</a><br>· <a href="#3e63">Results</a><br> ∘ <a href="#ba38">Variable Importance</a><br> ∘ <a href="#8394">Accuracy</a><br>· <a href="#7b19">Conclusion</a><br>· <a href="#d0d8">References</a></p><h3>Pre-Processing</h3><h4>Load data</h4><p>We will use three data sets: Sentinel-2, Sentinel-1 and slope from SRTM. Sentinel-2 as an optical image recognizes land cover through the spectral characteristics of each object, while Sentinel-1 and slope through texture and topography approaches.</p><pre>// Zoom to AOI<br>Map.centerObject(aoi, 12)<br><br>// ------------- Load Data ------------- <br>// Function for masking clouds on sentinel 2<br>function maskS2clouds(image) {<br> var qa = image.select(&#39;QA60&#39;);<br> <br> // Bits 10 and 11 are clouds and cirrus, respectively.<br> var cloudBitMask = 1 &lt;&lt; 10;<br> var cirrusBitMask = 1 &lt;&lt; 11;<br> <br> // Both flags should be set to zero, indicating clear conditions.<br> var mask = qa.bitwiseAnd(cloudBitMask).eq(0)<br>    .and(qa.bitwiseAnd(cirrusBitMask).eq(0));<br> <br> return image.updateMask(mask).divide(10000);<br>}<br>// Get sentinel-2 data on AOI with a certain time range<br>var s2 = ee.ImageCollection(&#39;COPERNICUS/S2_SR&#39;)<br>     .filterDate(&#39;2020-01-01&#39;, &#39;2021-05-06&#39;)<br>    // Pre-filter to get less cloudy granules.<br>     .filter(ee.Filter.lt(&#39;CLOUDY_PIXEL_PERCENTAGE&#39;,20))<br>     .map(maskS2clouds)<br>     .filterBounds(aoi)<br>     ;<br>print(s2, &quot;Sentinel-2A image collection&quot;)<br>// Create median composite for selected Sentinel-2 Data<br>var s2_median = s2.median().clip(aoi).select(&#39;B2&#39;, &#39;B3&#39;, &#39;B4&#39;, &#39;B5&#39;, &#39;B6&#39;, &#39;B7&#39;, &#39;B8&#39;, &#39;B8A&#39;, &#39;B9&#39;, &#39;B11&#39;, &#39;B12&#39;)<br>print(s2_median, &#39;s2 median komposit 2020 - 2021&#39;)<br>// Show median composite of Sentinel-2 on the map<br>Map.addLayer(s2_median, {bands: [&#39;B11&#39;, &#39;B12&#39;, &#39;B3&#39;], min: 0, max: 0.2, gamma: 0.9}, &#39;s2 median 2020 - 2021 false color&#39;);<br>Map.addLayer(s2_median, {bands: [&#39;B4&#39;, &#39;B3&#39;, &#39;B2&#39;], min: 0, max: 0.2, gamma: 0.9}, &#39;s2 median 2020 - 2021 true color&#39;);<br>// Load sentinel-1<br>var s1 = ee.ImageCollection(&#39;COPERNICUS/S1_GRD&#39;)<br>          .filter(ee.Filter.eq(&#39;instrumentMode&#39;, &#39;IW&#39;))<br>          .filter(ee.Filter.listContains(&#39;transmitterReceiverPolarisation&#39;, &#39;VH&#39;))<br>          .filter(ee.Filter.eq(&#39;orbitProperties_pass&#39;, &#39;DESCENDING&#39;))<br>          .filterMetadata(&#39;resolution_meters&#39;, &#39;equals&#39; , 10)<br>          .filterBounds(aoi);<br>          print(s1, &#39;Sentinel-1 collection AOI&#39;);<br>var vv = s1.select(&#39;VV&#39;).filterDate(&#39;2020-01-01&#39;, &#39;2021-05-06&#39;).median().clip(aoi); // set time range same as sentinel data<br>var vh = s1.select(&#39;VH&#39;).filterDate(&#39;2020-01-01&#39;, &#39;2021-05-06&#39;).median().clip(aoi); // set time range same as sentinel data<br>Map.addLayer(vv, {min:-15,max:0}, &#39;SAR VV&#39;, 0);<br>Map.addLayer(vh, {min:-25,max:0}, &#39;SAR VH&#39;, 0);<br>// Filter to reduce speckle<br>var SMOOTHING_RADIUS = 20;<br>var vv_filtered = vv.focal_mean(SMOOTHING_RADIUS, &#39;circle&#39;, &#39;meters&#39;);<br>var vh_filtered = vh.focal_mean(SMOOTHING_RADIUS, &#39;circle&#39;, &#39;meters&#39;);<br>Map.addLayer(vv_filtered, {min:-15,max:0}, &#39;SAR VV (filtered)&#39;, 0);<br>Map.addLayer(vh_filtered, {min:-25,max:0}, &#39;SAR VH (filtered&#39;, 0);<br>// Load Slope data<br>var dataset = ee.Image(&#39;USGS/SRTMGL1_003&#39;);<br>var elevation = dataset.select(&#39;elevation&#39;);<br>var slope = ee.Terrain.slope(elevation).clip(aoi);<br>Map.addLayer(slope, {min:0, max:90}, &#39;slope&#39;, 0);</pre><h4>Image resample</h4><p>Resampling is a necessary step when the images used come from different sources. Data for classification must have similar spatial resolution and projection so that distortion can be minimized. Resampling can be done by downscaling or upscaling the resolution with the reference image [3] [4]. We will use Sentinel-2 data as a reference, here is its description:</p><ul><li>var vv_resampled: Declaration of the image data resample command.</li><li>vv_filtered: Sentinel-1 data with VV polarization.</li><li>.resample(‘bilinear’): Resample function with bilinear interpolation technique.</li><li>.reproject({crs: s2_median.projection(), scale: 10}); : Adjusts the projection and spatial resolution (10 meters) of the median-filtered Sentinel-2. <br>For vh_resampled and slope_resampled the explanation is the same.</li></ul><pre>// Resample the data<br>// Check and ensure the variables are Images and then convert to float<br>var vv_resampled = ee.Image(vv_filtered).resample(&#39;bilinear&#39;).reproject({crs: s2_median.projection(), scale: 10}).toFloat();<br>var vh_resampled = ee.Image(vh_filtered).resample(&#39;bilinear&#39;).reproject({crs: s2_median.projection(), scale: 10}).toFloat();<br>var slope_resampled = ee.Image(slope).resample(&#39;bilinear&#39;).reproject({crs: s2_median.projection(), scale: 10}).toFloat();</pre><h4>Combining image data</h4><p>This stage is the most important, or at least the core of this content as a form of image fusion. Here is the explanation:</p><ul><li>var merged_raster<strong>: </strong>The name of the variable used to declare the merged image.</li><li>ee.Image.cat(): A function to merge multiple data or image layers into one, perhaps .cat is an acronym for concatenate?🤷‍♂️</li></ul><pre>// Merge Sentinel-1, Sentinel-2 and Slope<br>var merged_raster = ee.Image.cat(s2_median, vv_filtered, vh_filtered, slope); // Not resampled<br>// var merged_raster = ee.Image.cat(s2_median, vv_resampled, vh_resampled, slope_resampled); // Resampled<br>print(merged_raster, &quot;Merged raster data&quot;)</pre><h3>Processing</h3><h4>Creating training samples</h4><p>The strategy for creating training samples can be seen in my <a href="https://wahyu-ramadhan.medium.com/remote-sensing-image-classification-strategies-d2f9f42aa0a7">previous content</a>, but here we need to mention the bands used in the classification. Since more than one data is used (<a href="https://developers.google.com/earth-engine/datasets/catalog/COPERNICUS_S1_GRD">Sentinel-1</a>, <a href="https://developers.google.com/earth-engine/datasets/catalog/COPERNICUS_S2_SR_HARMONIZED">Sentinel-2</a> and <a href="https://developers.google.com/earth-engine/datasets/catalog/USGS_SRTMGL1_003">slope</a>) and the mention of each band is different, it is necessary to first look at the catalog page of these data.</p><pre>//------------ Classification Model ------------ <br>// Training Sample<br>// Merge feature collection<br>var sample = ee.FeatureCollection([water, urban, cropland, vegetation, mangrove, low_veg]).flatten();<br><br>// Define bands<br>var bands = [&#39;B2&#39;, &#39;B3&#39;, &#39;B4&#39;, &#39;B5&#39;, &#39;B6&#39;, &#39;B7&#39;, &#39;B8&#39;, &#39;B8A&#39;, &#39;B9&#39;, &#39;B11&#39;, &#39;B12&#39;, &#39;VV&#39;, &#39;VH&#39;, &#39;slope&#39;] // Merged raster<br>var bands_s2 = [&#39;B2&#39;, &#39;B3&#39;, &#39;B4&#39;, &#39;B5&#39;, &#39;B6&#39;, &#39;B7&#39;, &#39;B8&#39;, &#39;B8A&#39;, &#39;B9&#39;, &#39;B11&#39;, &#39;B12&#39;] // Only Sentinel-2<br>var training1 = merged_raster.select(bands).sampleRegions({<br>                collection: sample,<br>                properties: [&#39;lc&#39;],<br>                scale: 10 });<br>var training2 = s2_median.select(bands_s2).sampleRegions({<br>                collection: sample,<br>                properties: [&#39;lc&#39;],<br>                scale:10<br>})<br>                <br>var withRandom1 = training1.randomColumn(&#39;random&#39;);<br>var withRandom2 = training2.randomColumn(&#39;random&#39;);<br>// Split training sample<br>var split = 0.7; // Roughly 70% training, 30% testing.<br>// Merged Raster<br>var trainingP = withRandom1.filter(ee.Filter.lt(&#39;random&#39;, split));<br>var testingP = withRandom1.filter(ee.Filter.gte(&#39;random&#39;, split));<br>// Sentinel-2<br>var trainingP_s2 = withRandom2.filter(ee.Filter.lt(&#39;random&#39;, split));<br>var testingP_s2 = withRandom2.filter(ee.Filter.gte(&#39;random&#39;, split));</pre><h4>Train the classification model</h4><p>After the training sample is successfully created and divided into train and test, the next step is to run the classification model with the following configuration.</p><pre>// Train model for classification with Random Forest<br>var rf = ee.Classifier.smileRandomForest(1000).train({<br>          features: trainingP,<br>          classProperty: &#39;lc&#39;,<br>          inputProperties: bands<br>});<br>print(rf, &#39;rf model merged&#39;)<br><br>var rf_s2 = ee.Classifier.smileRandomForest(1000).train({<br>          features: trainingP_s2,<br>          classProperty: &#39;lc&#39;,<br>          inputProperties: bands_s2<br>});<br>print(rf_s2, &#39;rf model sentinel2&#39;)<br>// Perform classification for testing data<br>var test = testingP.classify(rf);<br>print(test, &#39;test&#39;)<br>var test_s2 = testingP_s2.classify(rf_s2);<br>print(test_s2, &#39;test&#39;)<br>// Run the Classification<br>// Visualization Parameter<br>var values = [1, 2, 3, 4, 5, 6];<br>var palette = [&#39;0066ff&#39;, &#39;fc3a3a&#39;, &#39;93ff17&#39;, &#39;1f8f0b&#39;, &#39;36703b&#39;, &#39;f7f302&#39;];<br>var names = [&#39;Water&#39;, &#39;Urban&#39;, &#39;Cropland&#39;, &#39;Vegetation&#39;, &#39;Mangrove&#39;, &#39;Low Vegetation&#39;];<br>// Merged raster<br>var classified = merged_raster.select(bands).classify(rf, &#39;classified&#39;).set({<br>  &#39;classified_values&#39;: values,<br>  &#39;classified_palette&#39;: palette<br>});<br>// Sentinel-2<br>var classified_s2 = s2_median.select(bands_s2).classify(rf_s2, &#39;classified&#39;).set({<br>  &#39;classified_values&#39;: values,<br>  &#39;classified_palette&#39;: palette<br>});<br>// Display the Classification<br>Map.addLayer(classified, {min: 1, max: 6, palette: palette},&#39;LC Classification merged&#39;);<br>Map.addLayer(classified_s2, {min: 1, max: 6, palette: palette},&#39;LC Classification Sentinel 2&#39;);</pre><h3>Post-Processing</h3><h4>Summarizing the classification results</h4><p>Create a graph that shows the variable importance of the data as a summary of the classification results.</p><pre>// Create a summary for variable importance<br>var dict = rf.explain();<br>var explainTitle = &#39;Explain Random Forest Merged :&#39;;<br>print(explainTitle, dict);<br>var variable_importance = ee.Feature(null, ee.Dictionary(dict).get(&#39;importance&#39;));<br><br>var dict_s2 = rf_s2.explain();<br>var explainTitle_s2 = &#39;Explain Random Forest Sentinel 2 :&#39;;<br>print(explainTitle_s2, dict_s2);<br>var variable_importance_s2 = ee.Feature(null, ee.Dictionary(dict_s2).get(&#39;importance&#39;));<br><br>// Create a chart for variable importance<br>// Merged raster chart<br>var chart =<br>ui.Chart.feature.byProperty(variable_importance)<br>    .setChartType(&#39;ColumnChart&#39;)<br>    .setOptions({<br>      title: &#39;Random Forest Variable Importance&#39;,<br>      legend: {position: &#39;none&#39;},<br>      hAxis: {title: &#39;Bands&#39;},<br>      vAxis: {title: &#39;Importance Merged Raster&#39;}<br>});<br>print(chart);<br>// Sentinel-2 Chart<br>var chart_s2 =<br>ui.Chart.feature.byProperty(variable_importance_s2)<br>    .setChartType(&#39;ColumnChart&#39;)<br>    .setOptions({<br>      title: &#39;Random Forest Variable Importance&#39;,<br>      legend: {position: &#39;none&#39;},<br>      hAxis: {title: &#39;Bands&#39;},<br>      vAxis: {title: &#39;Importance Sentinel-2&#39;}<br>});<br>print(chart_s2);</pre><h4>Accuracy test</h4><p>Of course, we have to make accuracy tests to evaluate the performance of the model.</p><pre>// ---------- Accuracy assessment ----------<br>// Sentinel-2<br>var confusionMatrix_s2 = test_s2.errorMatrix(&#39;lc&#39;, &#39;classification&#39;);<br>print(&#39;Confusion Matrix Sentinel-2&#39;, confusionMatrix_s2);<br>print(&#39;Validation overall accuracy Sentinel-2: &#39;, confusionMatrix_s2.accuracy());<br>print(&#39;Kappa Sentinel-2: &#39;, confusionMatrix_s2.kappa());<br>print(&#39;User Accuracy Sentinel-2&#39;, confusionMatrix_s2.consumersAccuracy());<br>print(&#39;Producer Accuracy Sentinel-2&#39;, confusionMatrix_s2.producersAccuracy());<br><br>// Merged raster<br>var confusionMatrix = test.errorMatrix(&#39;lc&#39;, &#39;classification&#39;);<br>print(&#39;Confusion Matrix Merged Raster&#39;, confusionMatrix);<br>print(&#39;Validation overall accuracy merged: &#39;, confusionMatrix.accuracy());<br>print(&#39;Kappa Merged Raster: &#39;, confusionMatrix.kappa());<br>print(&#39;User Accuracy Merged Raster&#39;, confusionMatrix.consumersAccuracy());<br>print(&#39;Producer Accuracy Merged Raster&#39;, confusionMatrix.producersAccuracy());<br>// Legend<br>Map.add(<br>  ui.Panel(<br>    names.map(function(name, index){<br>      return ui.Panel([<br>        ui.Label(&#39;&#39;, { width: &#39;30px&#39;, height: &#39;15px&#39;, border: &#39;0.5px solid black&#39;, backgroundColor: palette[index] }),<br>        ui.Label(name, { height: &#39;15px&#39; })<br>      ], ui.Panel.Layout.flow(&#39;horizontal&#39;));<br>    }),<br>    ui.Panel.Layout.flow(&#39;vertical&#39;),<br>    { position: &#39;bottom-left&#39; }<br>  )<br>);</pre><h4>Export the Data</h4><pre>// ---------- Export data ----------<br>Export.image.toDrive({<br>  image: classified,<br>  description: &#39;merged_raster_classification&#39;,<br>  scale: 10,<br>  region: aoi,<br>  folder: &#39;Google Earth Engine&#39;,<br>  fileNamePrefix: &#39;merged_raster_classification&#39;,<br>  fileFormat: &#39;GeoTIFF&#39;<br>})<br><br>Export.image.toDrive({<br>  image: classified_s2,<br>  description: &#39;sentinel2_classification&#39;,<br>  scale: 10,<br>  region: aoi,<br>  folder: &#39;Google Earth Engine&#39;,<br>  fileNamePrefix: &#39;sentinel2_classification&#39;,<br>  fileFormat: &#39;GeoTIFF&#39;<br>})<br>Export.table.toDrive({<br>collection: sample, // Merged training sample in feature collection<br>description: &#39;export_training_sample&#39;,<br>folder: &#39;Google Earth Engine&#39;,<br>fileNamePrefix: &#39;Training Sample&#39;<br>})</pre><h3>Results</h3><h4>Variable Importance</h4><p>Variable importance in multispectral classification shows how much each variable, in this case, the bands, contributes to the accuracy of the classification model. The two charts generated from the two image variations have similar patterns, with bands 11, 12 and 9 from Sentinel-2 having high values. Meanwhile, the Sentinel-1 data (VH and VV) does not contribute much and the slope has a significant influence. Okay, this is strange because topographic factors or surface roughness should also be captured by Sentinel-1 both VH and VV polarization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3z-XV0p8frgVVik1O2ZIoQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a2w_Zb8NmdGEwvgWOQwqTA.png" /><figcaption>Variable importance Sentinel-2 (left) and merged raster (right)</figcaption></figure><p><strong>*Notes:</strong> I found that after running the classification model, resampling reduced the implication of Sentinel-1 as seen in the variable importance graph. This resulted in classification results that were not as expected, especially the detection of objects that were quite detailed. So I tried two options, with and without resampling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zf9qykX6BBBwMa9cfuz1Rw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*neMB2C4RopYPWVJRABZ9mw.png" /><figcaption>Variable importance Sentinel-2 (left) and merged raster (right) tanpa resample</figcaption></figure><h4>Accuracy</h4><p>Overall accuracy shows reasonable results, Sentinel-2 is 0.992xxx while the combined raster is 0.996xxx. But what is notable is that visually the Sentinel-2 results appear sharper and seem to capture more details in certain areas while the combined raster tends to generalize.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*5VDN_l3-VuD8AsLay7a0OQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*Wtr3Cwq9pN-vo777b6cjRQ.png" /><figcaption>Sentinel-2 (left) and merged raster (right) overall accuracy</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*x1lFBfxoP1C-l-zZl0dQsg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*h_edzSa_wg3h5P-z1Pc6nw.png" /><figcaption>Sentinel-2 (left) and merged raster (right) classification result</figcaption></figure><p><strong>*Notes:</strong> In contrast to the importance variable, the classification results without resampling are visually similar to the resampled ones in the context of sharpness, i.e. the accuracy value of the combined raster is higher.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*hsiGlrck2KlXbGBaoRJomA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*JtLm0f5Fmr4snb874E6yqg.png" /><figcaption>Sentinel-2 (left) and merged raster (right) accuracy without resampling</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*40Zyy5x-vYVO7BJ9P4TUFw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*tVG1LgkAgUN3xI7-iZqUdA.png" /><figcaption>Sentinel-2 (left) and merged raster (right) classification result without resampling</figcaption></figure><h3><strong>Conclusion</strong></h3><p>Image fusion can improve overall accuracy, but visually shows relatively generalized results. So the Sentinel-2-only classification appears to be able to detect land cover in certain areas in more detail. I guess that the more variables, in this case, the bands of the images, are included, the more complex the model becomes. Although the overall accuracy is high, some variables may be not optimal and have implications for detecting fine details of land cover objects.</p><p>Something is surprising because in theory the merging of images should be accompanied by a resample. However, this makes Sentinel-1 have a low variable importance in the VV and VH polarizations. I honestly don’t know why, so I made some additional notes on my findings 😅.</p><p>Fortunately, the process is done with GEE or cloud computing, meaning that the computational load does not burden our computers. If you want to perform image fusion for multispectral classification on a desktop platform, there must be additional treatments inserted in the pre-processing stage. For example, variable selection to choose the most suitable features to apply in the model, if the data is raster then the variable is band. And hyperparameter tuning to adjust the behavior settings of the model so that it performs efficiently [6] [7].</p><p>Although the results are not as expected, I think image fusion is still worth trying 👍</p><p><a href="https://code.earthengine.google.com/45b5528270f0febc0e20b8893a679981"><strong><em>Link to full script</em></strong></a></p><h3>References</h3><p>[1] Lillesand, T. M., Kiefer, R. W., &amp; Chipman, J. W. (2015). <em>Remote Sensing and Image Interpretation</em> (7th ed.). USA: John Wiley &amp; Sons, Inc<br>[2] Jensen, J. R. (2015). <em>Introductory Digital Image Processing: A Remote Sesing Perspective</em> (4th ed.). USA: Pearson Education, Inc<br>[3] Ghassemian, H. (2016). A review of Remote Sensing Image Fusion Methods. <em>Information Fusion</em>, <em>32</em>, 75–89. <a href="https://doi.org/10.1016/j.inffus.2016.03.003">https://doi.org/10.1016/j.inffus.2016.03.003</a><br>[4] Belgiu, M., &amp; Stein, A. (2019). Spatiotemporal image fusion in remote sensing. <em>Remote Sensing</em>, <em>11</em>(7), 818. <a href="https://doi.org/10.3390/rs11070818">https://doi.org/10.3390/rs11070818</a><br>[5] Google. (2024). <em>Supervised classification | google earth engine | google for developers</em>. <a href="https://developers.google.com/earth-engine/guides/classification">https://developers.google.com/earth-engine/guides/classification</a><br>[6] Google. (2024a). <em>Ee.FeatureCollection.select | Google Earth engine | google for developers</em>. <a href="https://developers.google.com/earth-engine/apidocs/ee-featurecollection-select">https://developers.google.com/earth-engine/apidocs/ee-featurecollection-select</a><br>[7] Bima, P. (2023, October 19). <em>Performing feature selection in Google Earth Engine (gee) using recursive feature elimination (RFE)</em>. Medium. <a href="https://ai.plainenglish.io/performing-feature-selection-in-google-earth-engine-gee-using-recursive-feature-elimination-rfe-0f5ba2789c4c">https://ai.plainenglish.io/performing-feature-selection-in-google-earth-engine-gee-using-recursive-feature-elimination-rfe-0f5ba2789c4c</a><br>[8] Ehlers, M. (1991). Multisensor image fusion techniques in remote sensing. <em>ISPRS Journal of Photogrammetry and Remote Sensing</em>, <em>46</em>(1), 19–30. <a href="https://doi.org/10.1016/0924-2716(91)90003-e">https://doi.org/10.1016/0924-2716(91)90003-e</a></p><p>Connect with me on<strong> </strong><a href="http://linkedin.com/in/mwahyur"><strong>LinkedIn</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4e00402c6ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Limitasi Pada Data? Cobalah Hal Ini]]></title>
            <link>https://wahyu-ramadhan.medium.com/limitasi-pada-data-cobalah-hal-ini-85ec90b70fe2?source=rss-f79aaab49237------2</link>
            <guid isPermaLink="false">https://medium.com/p/85ec90b70fe2</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[maps]]></category>
            <category><![CDATA[gis]]></category>
            <category><![CDATA[remote-sensing]]></category>
            <category><![CDATA[geospatial]]></category>
            <dc:creator><![CDATA[Wahyu Ramadhan]]></dc:creator>
            <pubDate>Wed, 28 Aug 2024 10:31:52 GMT</pubDate>
            <atom:updated>2024-09-29T04:20:01.758Z</atom:updated>
            <content:encoded><![CDATA[<h4>#BelajarGEE 15: Memperkaya potensi data citra penginderaan jauh dengan image fusion</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XuMclQWvVsXz5lc1E8VIbQ.png" /></figure><p>Halo semuanya,</p><p>Klasifikasi citra adalah upaya untuk ekstraksi informasi berdasarkan karakteristik tertentu dari piksel seperti warna, tekstur, bentuk, ukuran dan relasi [1] [3]. Jika konteksnya adalah klasifikasi multispektral (seperti konten saya <a href="https://medium.com/@wahyu-ramadhan/strategi-klasifikasi-citra-penginderaan-jauh-b6d4ee901f6a">ini</a>), maka menitikberatkan pada pengelompokkan nilai reflektansi pada piksel berdasarkan panjang gelombang sebagai representasi dari objek-objek tertentu. Jadi peran dan kemampuan <em>band-band </em>spektral punya pengaruh banyak pada jenis klasifikasi multispektral [2].</p><p>Alasan mengapa klasifikasi multispektral banyak digunakan selain akses data relatif mudah adalah menyediakan lebih banyak informasi daripada citra <em>single band </em>untuk menangkap dan membedakan ciri spektral antar objek. Selain itu, jenis klasifikasi ini cukup <em>versatile </em>untuk berbagai kebutuhan, dari agrikultur, kelautan, kehutanan, perkotaan dan kebutuhan pemantauan lingkungan lainnya [1]. Meski begitu, bukan berarti tanpa kekurangan, tidak hanya menjadi semakin kompleks ketika ukuran datanya besar, tapi citra multispektral sangat tergantung pada kualitas data, <em>let’s say </em>gangguan radiometrik<em> </em>[4].</p><p><em>Disadvantage</em>(<em>s</em>) yang dimiliki klasifikasi multispektral sebetulnya juga sebuah <em>potential improvement</em>, tidak hanya pada resolusi spasial tapi juga temporal dari citra. Seperti yang sudah saya sebutkan, gangguan radiometrik seperti <em>cloud cover</em>, <em>haze</em> hingga kabut sangat berpotensi terjadi (terutama di wilayah tropis ketika musim penghujan) [3]. Meningkatkan <em>overall quality </em>dari data multispektral salah satunya dapat dicapai melalui penggabungan dengan data sensor lain, asumsinya hal itu dapat mengakomodasi eliminasi gangguan.</p><p>Penggabungan lebih dari satu sensor citra biasa disebut dengan <em>image fusion</em>, yang berarti akan menambahkan karakteristik-karakteristik dari pelbagai sensor. Hal ini bertujuan untuk memperkaya informasi yang tersedia dan meningkatkan kualitas analisis dengan adanya penambahan variabel [1] [3]. Namun, konsekuensinya adalah dimensi data menjadi makin kompleks, dan potensi menghasilkan informasi yang mirip atau redundan serta bisa jadi meningkatkan risiko <em>overfitting</em> pada model [8].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*RV4_mb-FIkFgDVqHFNLsLA.png" /><figcaption>Ilustrasi image fusion pada tingkat piksel [3]</figcaption></figure><p>Seperti biasa, kita akan gunakan Google Earth Engine (GEE) untuk pemrosesannya. Saya akan sertakan <em>link </em>untuk akses <em>script</em>nya di akhir tulisan ini.</p><h4>Daftar Isi</h4><p>· <a href="#b70a">Pra-Pemrosesan</a><br> ∘ <a href="#4938">Load Data</a><br> ∘ <a href="#d256">Resample citra</a><br> ∘ <a href="#2b7b">Menggabungkan data citra</a><br>· <a href="#cb19">Pemrosesan</a><br> ∘ <a href="#9d4c">Pembuatan training sample</a><br> ∘ <a href="#6aaa">Melatih model klasifikasi</a><br>· <a href="#979c">Post-Pemrosesan</a><br> ∘ <a href="#896d">Merangkum hasil klasifikasi</a><br> ∘ <a href="#85db">Uji akurasi</a><br> ∘ <a href="#ca27">Ekspor Data</a><br>· <a href="#3e63">Hasil</a><br> ∘ <a href="#ba38">Variable Importance</a><br> ∘ <a href="#8394">Uji Akurasi</a><br>· <a href="#1e6f">Kesimpulan</a><br>· <a href="#d0d8">Referensi</a></p><h3>Pra-Pemrosesan</h3><h4>Load Data</h4><p>Kita akan gunakan tiga data yaitu Sentinel-2, Sentinel-1 dan <em>slope</em> dari SRTM. Sentinel-2 sebagai citra optis yang mengenali penutup lahan melalui karakteristik spektral setiap objek, sedangkan Sentinel-1 dan <em>slope</em> melalui pendekatan tekstur dan topografi.</p><pre>// Zoom to AOI<br>Map.centerObject(aoi, 12)<br><br>// ------------- Load Data ------------- <br>// Function for masking clouds on sentinel 2<br>function maskS2clouds(image) {<br> var qa = image.select(&#39;QA60&#39;);<br> <br> // Bits 10 and 11 are clouds and cirrus, respectively.<br> var cloudBitMask = 1 &lt;&lt; 10;<br> var cirrusBitMask = 1 &lt;&lt; 11;<br> <br> // Both flags should be set to zero, indicating clear conditions.<br> var mask = qa.bitwiseAnd(cloudBitMask).eq(0)<br>    .and(qa.bitwiseAnd(cirrusBitMask).eq(0));<br> <br> return image.updateMask(mask).divide(10000);<br>}<br><br>// Get sentinel-2 data on AOI with a certain time range<br>var s2 = ee.ImageCollection(&#39;COPERNICUS/S2_SR&#39;)<br>     .filterDate(&#39;2020-01-01&#39;, &#39;2021-05-06&#39;)<br>    // Pre-filter to get less cloudy granules.<br>     .filter(ee.Filter.lt(&#39;CLOUDY_PIXEL_PERCENTAGE&#39;,20))<br>     .map(maskS2clouds)<br>     .filterBounds(aoi)<br>     ;<br>print(s2, &quot;Sentinel-2A image collection&quot;)<br><br>// Create median composite for selected Sentinel-2 Data<br>var s2_median = s2.median().clip(aoi).select(&#39;B2&#39;, &#39;B3&#39;, &#39;B4&#39;, &#39;B5&#39;, &#39;B6&#39;, &#39;B7&#39;, &#39;B8&#39;, &#39;B8A&#39;, &#39;B9&#39;, &#39;B11&#39;, &#39;B12&#39;)<br>print(s2_median, &#39;s2 median komposit 2020 - 2021&#39;)<br><br>// Show median composite of Sentinel-2 on the map<br>Map.addLayer(s2_median, {bands: [&#39;B11&#39;, &#39;B12&#39;, &#39;B3&#39;], min: 0, max: 0.2, gamma: 0.9}, &#39;s2 median 2020 - 2021 false color&#39;);<br>Map.addLayer(s2_median, {bands: [&#39;B4&#39;, &#39;B3&#39;, &#39;B2&#39;], min: 0, max: 0.2, gamma: 0.9}, &#39;s2 median 2020 - 2021 true color&#39;);<br><br>// Load sentinel-1<br>var s1 = ee.ImageCollection(&#39;COPERNICUS/S1_GRD&#39;)<br>          .filter(ee.Filter.eq(&#39;instrumentMode&#39;, &#39;IW&#39;))<br>          .filter(ee.Filter.listContains(&#39;transmitterReceiverPolarisation&#39;, &#39;VH&#39;))<br>          .filter(ee.Filter.eq(&#39;orbitProperties_pass&#39;, &#39;DESCENDING&#39;))<br>          .filterMetadata(&#39;resolution_meters&#39;, &#39;equals&#39; , 10)<br>          .filterBounds(aoi);<br>          print(s1, &#39;Sentinel-1 collection AOI&#39;);<br><br>var vv = s1.select(&#39;VV&#39;).filterDate(&#39;2020-01-01&#39;, &#39;2021-05-06&#39;).median().clip(aoi); // set time range same as sentinel data<br>var vh = s1.select(&#39;VH&#39;).filterDate(&#39;2020-01-01&#39;, &#39;2021-05-06&#39;).median().clip(aoi); // set time range same as sentinel data<br><br>Map.addLayer(vv, {min:-15,max:0}, &#39;SAR VV&#39;, 0);<br>Map.addLayer(vh, {min:-25,max:0}, &#39;SAR VH&#39;, 0);<br><br>// Filter to reduce speckle<br>var SMOOTHING_RADIUS = 20;<br>var vv_filtered = vv.focal_mean(SMOOTHING_RADIUS, &#39;circle&#39;, &#39;meters&#39;);<br>var vh_filtered = vh.focal_mean(SMOOTHING_RADIUS, &#39;circle&#39;, &#39;meters&#39;);<br><br>Map.addLayer(vv_filtered, {min:-15,max:0}, &#39;SAR VV (filtered)&#39;, 0);<br>Map.addLayer(vh_filtered, {min:-25,max:0}, &#39;SAR VH (filtered&#39;, 0);<br><br>// Load Slope data<br>var dataset = ee.Image(&#39;USGS/SRTMGL1_003&#39;);<br>var elevation = dataset.select(&#39;elevation&#39;);<br>var slope = ee.Terrain.slope(elevation).clip(aoi);<br>Map.addLayer(slope, {min:0, max:90}, &#39;slope&#39;, 0);</pre><h4><strong>Resample citra</strong></h4><p><em>Resampling</em> adalah langkah yang dibutuhkan ketika citra yang digunakan berasal dari sumber yang berbeda. Data untuk klasifikasi harus memiliki kesamaan resolusi spasial dan proyeksi, sehingga distorsi bisa diminimalisir. Resample bisa dengan menurunkan (<em>downscaling</em>) atau mempertajam (<em>upscaling</em>) resolusi dengan citra yang menjadi referensi [3] [4]. Kita akan gunakan data Sentinel-2 sebagai referensi, berikut ini deskripsinya:</p><ul><li>var vv_resampled: Deklarasi perintah resample data citra.</li><li>vv_filtered: Data Sentinel-1 dengan polarisasi VV.</li><li>.resample(‘bilinear’): fungsi resample dengan teknik interpolasi bilinear.</li><li>.reproject({crs: s2_median.projection(), scale: 10}); : Menyesuaikan proyeksi dan resolusi spasial (10 meter) dari Sentinel-2 yang telah mengalami filter median.<br>Untuk vh_resampled dan slope_resampled penjelasannya sama.</li></ul><pre>// Resample the data<br>// Check and ensure the variables are Images and then convert to float<br>var vv_resampled = ee.Image(vv_filtered).resample(&#39;bilinear&#39;).reproject({crs: s2_median.projection(), scale: 10}).toFloat();<br>var vh_resampled = ee.Image(vh_filtered).resample(&#39;bilinear&#39;).reproject({crs: s2_median.projection(), scale: 10}).toFloat();<br>var slope_resampled = ee.Image(slope).resample(&#39;bilinear&#39;).reproject({crs: s2_median.projection(), scale: 10}).toFloat();</pre><h4><strong>Menggabungkan data citra</strong></h4><p>Tahap ini adalah yang paling penting, atau setidaknya yang menjadi inti tulisan saya sebagai bentuk <em>image fusion</em>. Berikut ini penjelasannya:</p><ul><li>var merged_raster<strong>: </strong>Nama variabel yang digunakan untuk mendeklarasikan penggabungan citra.</li><li>ee.Image.cat(): Fungsi untuk menggabungkan beberapa data atau layer citra menjadi satu kesatuan, barangkali .cat sebenarnya adalah akronim dari concatenate? 🤷‍♂️</li></ul><pre>// Merge Sentinel-1, Sentinel-2 and Slope<br>var merged_raster = ee.Image.cat(s2_median, vv_filtered, vh_filtered, slope); // Not resampled<br>// var merged_raster = ee.Image.cat(s2_median, vv_resampled, vh_resampled, slope_resampled); // Resampled<br>print(merged_raster, &quot;Merged raster data&quot;)</pre><h3>Pemrosesan</h3><h4>Pembuatan t<em>raining sample</em></h4><p>Strategi dalam pembuatan training sample dapat dilihat pada tulisan saya yang <a href="https://medium.com/@wahyu-ramadhan/strategi-klasifikasi-citra-penginderaan-jauh-b6d4ee901f6a">ini</a>, tapi di sini jelasnya kita perlu menyebutkan <em>band</em> yang digunakan dalam klasifikasi. Berhubung yang digunakan lebih dari satu data (<a href="https://developers.google.com/earth-engine/datasets/catalog/COPERNICUS_S1_GRD">Sentinel-1</a>, <a href="https://developers.google.com/earth-engine/datasets/catalog/COPERNICUS_S2_SR_HARMONIZED">Sentinel-2</a> dan <a href="https://developers.google.com/earth-engine/datasets/catalog/USGS_SRTMGL1_003"><em>slope</em></a>) dan penyebutan masing-masing <em>band</em> berbeda, maka perlu dilihat dahulu pada laman katalog dari data-data tersebut.</p><pre>// ------------ Classification Model ------------ <br>// Training Sample<br>// Merge feature collection<br>var sample = ee.FeatureCollection([water, urban, cropland, vegetation, mangrove, low_veg]).flatten();<br><br>// Define bands<br>var bands = [&#39;B2&#39;, &#39;B3&#39;, &#39;B4&#39;, &#39;B5&#39;, &#39;B6&#39;, &#39;B7&#39;, &#39;B8&#39;, &#39;B8A&#39;, &#39;B9&#39;, &#39;B11&#39;, &#39;B12&#39;, &#39;VV&#39;, &#39;VH&#39;, &#39;slope&#39;] // Merged raster<br>var bands_s2 = [&#39;B2&#39;, &#39;B3&#39;, &#39;B4&#39;, &#39;B5&#39;, &#39;B6&#39;, &#39;B7&#39;, &#39;B8&#39;, &#39;B8A&#39;, &#39;B9&#39;, &#39;B11&#39;, &#39;B12&#39;] // Only Sentinel-2<br><br>var training1 = merged_raster.select(bands).sampleRegions({<br>                collection: sample,<br>                properties: [&#39;lc&#39;],<br>                scale: 10 });<br>var training2 = s2_median.select(bands_s2).sampleRegions({<br>                collection: sample,<br>                properties: [&#39;lc&#39;],<br>                scale:10<br>})<br>                <br>var withRandom1 = training1.randomColumn(&#39;random&#39;);<br>var withRandom2 = training2.randomColumn(&#39;random&#39;);<br><br>// Split training sample<br>var split = 0.7; // Roughly 70% training, 30% testing.<br>// Merged Raster<br>var trainingP = withRandom1.filter(ee.Filter.lt(&#39;random&#39;, split));<br>var testingP = withRandom1.filter(ee.Filter.gte(&#39;random&#39;, split));<br>// Sentinel-2<br>var trainingP_s2 = withRandom2.filter(ee.Filter.lt(&#39;random&#39;, split));<br>var testingP_s2 = withRandom2.filter(ee.Filter.gte(&#39;random&#39;, split));<br></pre><h4><strong>Melatih model klasifikasi</strong></h4><p>Setelah <em>training sample</em> berhasil dibuat dan dibagi untuk <em>train</em> dan <em>test</em>, maka selanjutnya adalah menjalankan model klasifikasi dengan konfigurasi sebagai berikut.</p><pre>// Train model for classification with Random Forest<br>var rf = ee.Classifier.smileRandomForest(1000).train({<br>          features: trainingP,<br>          classProperty: &#39;lc&#39;,<br>          inputProperties: bands<br>});<br>print(rf, &#39;rf model merged&#39;)<br><br>var rf_s2 = ee.Classifier.smileRandomForest(1000).train({<br>          features: trainingP_s2,<br>          classProperty: &#39;lc&#39;,<br>          inputProperties: bands_s2<br>});<br>print(rf_s2, &#39;rf model sentinel2&#39;)<br><br>// Perform classification for testing data<br>var test = testingP.classify(rf);<br>print(test, &#39;test&#39;)<br><br>var test_s2 = testingP_s2.classify(rf_s2);<br>print(test_s2, &#39;test&#39;)<br><br>// Run the Classification<br>// Visualization Parameter<br>var values = [1, 2, 3, 4, 5, 6];<br>var palette = [&#39;0066ff&#39;, &#39;fc3a3a&#39;, &#39;93ff17&#39;, &#39;1f8f0b&#39;, &#39;36703b&#39;, &#39;f7f302&#39;];<br>var names = [&#39;Water&#39;, &#39;Urban&#39;, &#39;Cropland&#39;, &#39;Vegetation&#39;, &#39;Mangrove&#39;, &#39;Low Vegetation&#39;];<br><br>// Merged raster<br>var classified = merged_raster.select(bands).classify(rf, &#39;classified&#39;).set({<br>  &#39;classified_values&#39;: values,<br>  &#39;classified_palette&#39;: palette<br>});<br><br>// Sentinel-2<br>var classified_s2 = s2_median.select(bands_s2).classify(rf_s2, &#39;classified&#39;).set({<br>  &#39;classified_values&#39;: values,<br>  &#39;classified_palette&#39;: palette<br>});<br><br>// Display the Classification<br>Map.addLayer(classified, {min: 1, max: 6, palette: palette},&#39;LC Classification merged&#39;);<br>Map.addLayer(classified_s2, {min: 1, max: 6, palette: palette},&#39;LC Classification Sentinel 2&#39;);</pre><h3>Post-Pemrosesan</h3><h4>Merangkum hasil klasifikasi</h4><p>Klasifikasi yang dijalankan kemudian dibuat grafik yang menunjukkan <em>variable importance</em> dari data sebagai bentuk rangkuman hasil klasifikasi.</p><pre>// Create a summary for variable importance<br>var dict = rf.explain();<br>var explainTitle = &#39;Explain Random Forest Merged :&#39;;<br>print(explainTitle, dict);<br>var variable_importance = ee.Feature(null, ee.Dictionary(dict).get(&#39;importance&#39;));<br><br>var dict_s2 = rf_s2.explain();<br>var explainTitle_s2 = &#39;Explain Random Forest Sentinel 2 :&#39;;<br>print(explainTitle_s2, dict_s2);<br>var variable_importance_s2 = ee.Feature(null, ee.Dictionary(dict_s2).get(&#39;importance&#39;));<br><br><br>// Create a chart for variable importance<br>// Merged raster chart<br>var chart =<br>ui.Chart.feature.byProperty(variable_importance)<br>    .setChartType(&#39;ColumnChart&#39;)<br>    .setOptions({<br>      title: &#39;Random Forest Variable Importance&#39;,<br>      legend: {position: &#39;none&#39;},<br>      hAxis: {title: &#39;Bands&#39;},<br>      vAxis: {title: &#39;Importance Merged Raster&#39;}<br>});<br><br>print(chart);<br><br>// Sentinel-2 Chart<br>var chart_s2 =<br>ui.Chart.feature.byProperty(variable_importance_s2)<br>    .setChartType(&#39;ColumnChart&#39;)<br>    .setOptions({<br>      title: &#39;Random Forest Variable Importance&#39;,<br>      legend: {position: &#39;none&#39;},<br>      hAxis: {title: &#39;Bands&#39;},<br>      vAxis: {title: &#39;Importance Sentinel-2&#39;}<br>});<br><br>print(chart_s2);</pre><h4>Uji akurasi</h4><p>Tentu saja, hasil klasifikasi harus melalui uji akurasi untuk mengevaluasi performa dari model.</p><pre>// ---------- Accuracy assessment ----------<br>// Sentinel-2<br>var confusionMatrix_s2 = test_s2.errorMatrix(&#39;lc&#39;, &#39;classification&#39;);<br>print(&#39;Confusion Matrix Sentinel-2&#39;, confusionMatrix_s2);<br>print(&#39;Validation overall accuracy Sentinel-2: &#39;, confusionMatrix_s2.accuracy());<br>print(&#39;Kappa Sentinel-2: &#39;, confusionMatrix_s2.kappa());<br>print(&#39;User Accuracy Sentinel-2&#39;, confusionMatrix_s2.consumersAccuracy());<br>print(&#39;Producer Accuracy Sentinel-2&#39;, confusionMatrix_s2.producersAccuracy());<br><br>// Merged raster<br>var confusionMatrix = test.errorMatrix(&#39;lc&#39;, &#39;classification&#39;);<br>print(&#39;Confusion Matrix Merged Raster&#39;, confusionMatrix);<br>print(&#39;Validation overall accuracy merged: &#39;, confusionMatrix.accuracy());<br>print(&#39;Kappa Merged Raster: &#39;, confusionMatrix.kappa());<br>print(&#39;User Accuracy Merged Raster&#39;, confusionMatrix.consumersAccuracy());<br>print(&#39;Producer Accuracy Merged Raster&#39;, confusionMatrix.producersAccuracy());<br><br>// Legend<br>Map.add(<br>  ui.Panel(<br>    names.map(function(name, index){<br>      return ui.Panel([<br>        ui.Label(&#39;&#39;, { width: &#39;30px&#39;, height: &#39;15px&#39;, border: &#39;0.5px solid black&#39;, backgroundColor: palette[index] }),<br>        ui.Label(name, { height: &#39;15px&#39; })<br>      ], ui.Panel.Layout.flow(&#39;horizontal&#39;));<br>    }),<br>    ui.Panel.Layout.flow(&#39;vertical&#39;),<br>    { position: &#39;bottom-left&#39; }<br>  )<br>);</pre><h4>Ekspor Data</h4><pre>// ---------- Export data ----------<br>Export.image.toDrive({<br>  image: classified,<br>  description: &#39;merged_raster_classification&#39;,<br>  scale: 10,<br>  region: aoi,<br>  folder: &#39;Google Earth Engine&#39;,<br>  fileNamePrefix: &#39;merged_raster_classification&#39;,<br>  fileFormat: &#39;GeoTIFF&#39;<br>})<br><br>Export.image.toDrive({<br>  image: classified_s2,<br>  description: &#39;sentinel2_classification&#39;,<br>  scale: 10,<br>  region: aoi,<br>  folder: &#39;Google Earth Engine&#39;,<br>  fileNamePrefix: &#39;sentinel2_classification&#39;,<br>  fileFormat: &#39;GeoTIFF&#39;<br>})<br><br>Export.table.toDrive({<br>collection: sample, // Merged training sample in feature collection<br>description: &#39;export_training_sample&#39;,<br>folder: &#39;Google Earth Engine&#39;,<br>fileNamePrefix: &#39;Training Sample&#39;<br>})</pre><h3>Hasil</h3><h4><strong>Variable Importance</strong></h4><p><em>Variable importance</em> dalam klasifikasi multispektral menunjukkan seberapa besar kontribusi setiap variabel dalam hal ini adalah <em>band </em>terhadap akurasi dari model klasifikasi. Kedua <em>chart </em>yang dihasilkan dari dua variasi citra, sebetulnya <em>pattern</em>nya mirip yakni <em>band </em>11, 12 dan 9 dari Sentinel-2 punya <em>value </em>yang tinggi. Sedangkan, data Sentinel-1 (VH dan VV) tidak memiliki kontribusi banyak dan <em>slope </em>cukup punya pengaruh signifikan. Oke, ini aneh karena seharusnya faktor-faktor topografi atau kekasaran permukaan juga ditangkap oleh Sentinel-1 baik polarisasi VH maupun VV.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3z-XV0p8frgVVik1O2ZIoQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a2w_Zb8NmdGEwvgWOQwqTA.png" /><figcaption>Variable importance Sentinel-2 (kiri) dan merged raster (kanan)</figcaption></figure><p><strong>*Catatan: </strong>Temuan saya setelah menjalankan model klasifikasi, ternyata <em>resampling </em>justru mengurangi implikasi Sentinel-1 yang terlihat dalam grafik <em>variable importance</em>. Sehingga mengakibatkan hasil klasifikasi tidak sesuai harapan, terutama deteksi objek yang cukup detil. Jadi saya coba dua opsi, dengan dan tanpa <em>resample</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zf9qykX6BBBwMa9cfuz1Rw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*neMB2C4RopYPWVJRABZ9mw.png" /><figcaption>Variable importance Sentinel-2 (kiri) dan merged raster (kanan) tanpa resample</figcaption></figure><h4><strong>Uji Akurasi</strong></h4><p><em>Overall accuracy </em>menunjukkan hasil yang wajar, Sentinel-2 0.992xxx sementara raster gabungan 0.996xxx. Tapi yang menjadi catatan adalah secara visual hasil Sentinel-2 tampak lebih <em>sharp</em> dan seolah-olah dapat menangkap lebih banyak detail pada area-area tertentu sementara raster gabungan cenderung mengalami generalisasi.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*5VDN_l3-VuD8AsLay7a0OQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*Wtr3Cwq9pN-vo777b6cjRQ.png" /><figcaption>Uji akurasi Sentinel-2 (kiri) dan merged raster (kanan)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*x1lFBfxoP1C-l-zZl0dQsg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*h_edzSa_wg3h5P-z1Pc6nw.png" /><figcaption>Hasil klasifikasi Sentinel-2 (kiri) dan merged raster (kanan)</figcaption></figure><p><strong>*Catatan:</strong> Berbeda dengan <em>variable importance</em>, hasil klasifikasi tanpa <em>resample</em> secara visual dalam konteks <em>sharpness </em>masih mirip dengan yang telah di<em>resample </em>yaitu nilai akurasi raster gabungan lebih tinggi.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*hsiGlrck2KlXbGBaoRJomA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*JtLm0f5Fmr4snb874E6yqg.png" /><figcaption>Uji akurasi Sentinel-2 (kiri) dan merged raster (kanan) tanpa resample</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*40Zyy5x-vYVO7BJ9P4TUFw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*tVG1LgkAgUN3xI7-iZqUdA.png" /><figcaption>Hasil klasifikasi Sentinel-2 (kiri) dan raster gabungan (kanan) tanpa resample</figcaption></figure><h3>Kesimpulan</h3><p><em>Image fusion </em>dapat meningkatkan <em>overall accuracy</em>, tapi secara visual menunjukkan hasil yang relatif tergeneralisasi. Sehingga klasifikasi hanya dengan Sentinel-2 tampak mampu mendeteksi penutup lahan pada area-area tertentu lebih detail. Dugaan saya, karena semakin banyak variabel dalam hal ini adalah <em>band </em>dari citra yang dimasukkan, membuat model semakin kompleks. Meskipun <em>overal accuracy </em>tinggi, tapi mungkin saja beberapa variabel tidak optimal dan berimplikasi untuk mendeteksi detail objek penutup lahan yang halus.</p><p>Sebetulnya ada sesuatu yang bisa dibilang mengejutkan, karena secara teori penggabungan citra harus disertai dengan <em>resample</em>. Tetapi hal tersebut malah membuat Sentinel-1 memiliki <em>variable importance </em>yang rendah pada polarisasi VV dan VH. Sejujurnya saya belum tahu mengapa, makanya saya buat beberapa catatan tambahan dari temuan saya tersebut 😅</p><p>Untungnya prosesnya dilakukan dengan GEE atau <em>cloud computing</em>, artinya beban komputasi tidak memberatkan komputer kita. Jika ingin melakukan <em>image fusion </em>untuk klasifikasi multispektral pada platform <em>desktop</em>, ya harus ada <em>treatment </em>tambahan yang disisipkan dalam tahap pra-pemrosesan. Misalnya <em>variable selection</em> untuk memilih fitur-fitur paling sesuai untuk diterapkan dalam model, jika datanya raster maka variabelnya adalah <em>band</em>. Serta <em>hyperparameter tuning</em> untuk menyesuaikan pengaturan perilaku model sehingga performanya efisien [6] [7].</p><p>Selain hasil diluar ekspektasi, saya rasa <em>image fusion</em> masih <em>worth to try</em> 👍</p><p><a href="https://code.earthengine.google.com/45b5528270f0febc0e20b8893a679981"><strong><em>Link ke full script</em></strong></a></p><h3>Referensi</h3><p>[1] Lillesand, T. M., Kiefer, R. W., &amp; Chipman, J. W. (2015). <em>Remote Sensing and Image Interpretation</em> (7th ed.). USA: John Wiley &amp; Sons, Inc<br>[2] Jensen, J. R. (2015). <em>Introductory Digital Image Processing: A Remote Sesing Perspective</em> (4th ed.). USA: Pearson Education, Inc<br>[3] Ghassemian, H. (2016). A review of Remote Sensing Image Fusion Methods. <em>Information Fusion</em>, <em>32</em>, 75–89. <a href="https://doi.org/10.1016/j.inffus.2016.03.003">https://doi.org/10.1016/j.inffus.2016.03.003</a><br>[4] Belgiu, M., &amp; Stein, A. (2019). Spatiotemporal image fusion in remote sensing. <em>Remote Sensing</em>, <em>11</em>(7), 818. <a href="https://doi.org/10.3390/rs11070818">https://doi.org/10.3390/rs11070818</a><br>[5] Google. (2024). <em>Supervised classification | google earth engine | google for developers</em>. <a href="https://developers.google.com/earth-engine/guides/classification">https://developers.google.com/earth-engine/guides/classification</a><br>[6] Google. (2024a). <em>Ee.FeatureCollection.select | Google Earth engine | google for developers</em>. <a href="https://developers.google.com/earth-engine/apidocs/ee-featurecollection-select">https://developers.google.com/earth-engine/apidocs/ee-featurecollection-select</a><br>[7] Bima, P. (2023, October 19). <em>Performing feature selection in Google Earth Engine (gee) using recursive feature elimination (RFE)</em>. Medium. <a href="https://ai.plainenglish.io/performing-feature-selection-in-google-earth-engine-gee-using-recursive-feature-elimination-rfe-0f5ba2789c4c">https://ai.plainenglish.io/performing-feature-selection-in-google-earth-engine-gee-using-recursive-feature-elimination-rfe-0f5ba2789c4c</a><br>[8] Ehlers, M. (1991). Multisensor image fusion techniques in remote sensing. <em>ISPRS Journal of Photogrammetry and Remote Sensing</em>, <em>46</em>(1), 19–30. <a href="https://doi.org/10.1016/0924-2716(91)90003-e">https://doi.org/10.1016/0924-2716(91)90003-e</a></p><p>Connect with me on <a href="http://linkedin.com/in/mwahyur"><strong>LinkedIn</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85ec90b70fe2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>