<?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 Jack Shi Wei Lun on Medium]]></title>
        <description><![CDATA[Stories by Jack Shi Wei Lun on Medium]]></description>
        <link>https://medium.com/@jackswl?source=rss-caf65b9a635e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*o9I4PiyHbzEgd2CPPfDAgA.jpeg</url>
            <title>Stories by Jack Shi Wei Lun on Medium</title>
            <link>https://medium.com/@jackswl?source=rss-caf65b9a635e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 06:18:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jackswl/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[Climate Forecasting using Seq2Seq Model with Attention Mechanism]]></title>
            <link>https://medium.com/@jackswl/climate-forecasting-using-seq2seq-model-with-attention-mechanism-6e9b23d8ba29?source=rss-caf65b9a635e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e9b23d8ba29</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[climate-change]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Jack Shi Wei Lun]]></dc:creator>
            <pubDate>Mon, 19 Jun 2023 07:01:29 GMT</pubDate>
            <atom:updated>2024-07-07T14:02:52.732Z</atom:updated>
            <content:encoded><![CDATA[<h4>Precipitation forecasting over 10 days lead times in Singapore using machine learning methods.</h4><p><strong>Acknowledgement</strong>: This article is an excerpt of my project during NUS Undergraduate Research Opportunity Programme, where I worked with Prof. <a href="https://scholar.google.com/citations?user=AWfzBLMAAAAJ&amp;hl=en">Xiaogang HE</a>, <a href="https://github.com/Zhanwei-Liu">Zhanwei LIU</a> and <a href="https://github.com/Hem-W">Huimin WANG</a>. Without them, the idea, research and codes provided in this article would not have been possible.</p><h3>Introduction</h3><p>Remarkable advances in weather forecasts during the past half-century have brought great benefits to humanity. Accurate forecasts save many lives, and early warnings can mitigate the worst effects of extreme weather events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/0*2WEri5SfuTXs7Ni2.gif" /><figcaption>Nowcasting the next hour of rain. Source: <a href="https://www.deepmind.com/blog/nowcasting-the-next-hour-of-rain">https://www.deepmind.com/blog/nowcasting-the-next-hour-of-rain</a></figcaption></figure><p>In this article, we explore precipitation forecasting over lead times of 10 days in Singapore based on a daily scale. We have experimented with a few baseline models (i.e., lightGBM, single LSTM) and tried different optimization methods (i.e., Adam and AdamW), but we shall only go through the model architecture of the best result.</p><p>The purpose of this article is twofold:</p><ol><li>Showcase the Sequence-to-Sequence (Seq2seq) model using <em>Bidirectional long-short term memory</em> (Bi-LSTM) and Luong attention mechanism [1] to forecast precipitation of 10 days lead times</li><li>Explain how we approached hyperparameter tuning process of such complex model architecture, given that most studies do not explain such crucial procedure in details.</li></ol><p>The full GitHub repository can be found <a href="https://github.com/jackswl/attentionMedium">here</a>. We will only go through the Seq2seq model (using Bi-LSTM + Luong attention) in this article, although the other experiments can be found under the ‘hpc’ folder in the GitHub repository.</p><p>Feel free to skip to any main section by clicking on the respective link in the table of contents below</p><h3>Table of Contents</h3><ul><li><a href="#f595">Study Area</a></li><li><a href="#e433">Ground Truth and Input Data</a></li><li><a href="#864c">Log Transformation and Min-Max Scaling</a></li><li><a href="#812d">Time Series Cross Validation</a></li><li><a href="#2a88">Model Architecture</a></li><li><a href="#cd87">Loss Function and Hyperparameter Tuning</a></li><li><a href="#3bb0">GridSearchCV Results and Best Result for Testing</a></li><li><a href="#35db">Results and Discussion</a></li><li><a href="#94fc">Baseline Models</a></li><li><a href="#8ec6">References</a></li></ul><h3>Study Area</h3><p>Our study area will be centered around Singapore, near the equator. The gridded degree of our GEFSv12 reforecast and reanalysis datasets is 0.25° by 0.25°, which is equivalent to about 27.75 km. The spatial average value of the 4 red dots in the figure below is used to train the model (i.e., average data points of the following coordinates: (1.5, 103.75), (1.25, 103.75), (1.5, 104.0), (1.25, 104.0)).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/0*QdKcRWF6OkoHHRRU" /></figure><p>Next, we shall look into the ground truth data and the input data used for our model. For more details on how reanalysis and reforecast came about and what they represent, feel free to refer to the start of this Medium article:</p><p><a href="https://medium.com/@jackswl/climate-downscaling-using-srgan-with-multi-task-learning-731c8257ef4d">Climate Downscaling using SRGAN with Multi-Task Learning</a></p><h3>Ground Truth and Input Data</h3><h4>Ground Truth Data (Reanalysis)</h4><p>From <a href="https://journals.ametsoc.org/view/journals/mwre/150/1/MWR-D-21-0023.1.xml">GEFSv12 reanalysis dataset</a>, we selected the total precipitation (tp) variable as the sole variable to be forecasted. The following code shows how we cleaned the ‘combined-reanalysis.nc’ file and resample them to daily data (i.e., sum of 06, 12, 18, 00 data is equivalent to a full day sample).</p><p>We first create a <a href="https://pandas.pydata.org/docs/user_guide/advanced.html">Multi-Index</a> pandas table that contains the latitude and longitude dimensions, as well as the tp variable and the lead times. Since we are trying to forecast for lead times 1 to 10 based on reanalysis lead time of day 0, we will only have 1 single lead time for reanalysis.</p><p>Then, we proceed to do some data cleaning (missing value on 2013–09–20), and convert the time variable to coherent format, and resample them into daily. We combine the 4 coordinate values into 1 single value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73f297ece21a4a6c3b179a39f5508912/href">https://medium.com/media/73f297ece21a4a6c3b179a39f5508912/href</a></iframe><p>After exporting the CSV file, this is how our final reanalysis dataset looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fdb56809db13dd7c36ae51fa28a423d3/href">https://medium.com/media/fdb56809db13dd7c36ae51fa28a423d3/href</a></iframe><h4>Input Data (Reforecast)</h4><p>From <a href="https://noaa-gefs-retrospective.s3.amazonaws.com/index.html">GEFSv12 reforecast dataset</a>, we selected five variables to help in precipitation forecasting. They are:</p><ol><li>t2m: 2-meter temperature (K)</li><li>tp: total precipitation</li><li>H: 2-meter specific humidity</li><li>C: total cloud cover (%) average</li><li>E: convective available potential energy</li></ol><p>Our model structure shall then be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fg2BPZh9j-YY9sQGrjaWaQ.png" /><figcaption>The RHS (p1, p2, …) are referring to the total precipitation of the reanalysis dataset. Source: By the author</figcaption></figure><p>Similarly to the reanalysis dataset, we first create a Multi-Index pandas table that contains the latitude and longitude dimensions, as well as the five meteorological variables mentioned above and the 10 days lead times (day 1 to day 10).</p><p>We then append the 10 lead times for each variable (only showed cape data in the code below) onto the table, while resampling to daily, accounting for duplicates and missing values. We then combine the 4 coordinate values into 1 single value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/850532ef346d117c216245c98ae9882d/href">https://medium.com/media/850532ef346d117c216245c98ae9882d/href</a></iframe><p>After exporting the CSV file, this is how our final reforecast dataset looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fc09edb753104c38f2803c17caa5762/href">https://medium.com/media/7fc09edb753104c38f2803c17caa5762/href</a></iframe><h3>Log Transformation and Min-Max Scaling</h3><p>The training dataset timeframe will be from 2000–01–01 to 2016–12–31, and the testing dataset timeframe will be from 2017–01–01 to 2019–12–31. Since we are using time-series cross validation, we do not need a specific validation dataset, as the validation will be done using part of the training dataset itself. This is because our total samples are small, since we resampled them into daily samples, and performing time-series cross validation on the bigger training dataset will help in maintaining a large enough samples for hyperparameter tuning.</p><p>To account for the skewed distribution of rainfall, we log-transformed the datasets containing precipitation variables (i.e., tp), and min-max normalized them.</p><p>Note: The correct approach is to log-transform and perform min-max normalization on the training and testing datasets separately, to prevent data leakage. One should take this approach if replicating the experiments in <a href="https://github.com/jackswl/attentionMedium">GitHub</a>.</p><h3>Time Series Cross Validation</h3><p>Time-series cross validation will be used for the hyperparameter tuning process later on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*MuAMSx8we_E5NPlzUL1jxQ.png" /></figure><p>For the image above, the blue dataset refers to the original training dataset explained earlier. Also, the word ‘Test’ shown in red is basically referring to the ‘validation’ sets within the splits.</p><p>For our full training dataset shown in blue, we split them up in a frequency of 2 years per train (green) and test (red). This is to ensure that all periodicity patterns within an entire year can be captured and trained, instead of cutting the datasets at random months of the year.</p><p>As such, the time-series cross validation will work as follows:</p><ol><li>Train on 2000 to 2001 samples to be tested on 2002–2003</li><li>Train on 2004 to 2005 samples to be tested on 2006–2007</li><li>Train on 2008 to 2009 samples to be tested on 2010–2011</li><li>Train on 2012 to 2013 samples to be tested on 2014–2015</li></ol><p>From here, we can obtain the best overall hyperparameter configurations for the model.</p><p>Note: The ‘get_xy’ function is to ensure that the <a href="https://machinelearningmastery.com/reshape-input-data-long-short-term-memory-networks-keras/">input</a> to the model follows that required by the standard LSTM architecture, with a time-step of 10 days, and features of 5.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66fe5b6add50e6e6c3b6f1d62e47efb6/href">https://medium.com/media/66fe5b6add50e6e6c3b6f1d62e47efb6/href</a></iframe><h3>Model Architecture</h3><p>Before going into how we performed our hyperparameter tuning process, let’s take a look our model architecture used — Seq2seq model using bidirectional LSTM and Luong attention mechanism.</p><p>Bidirectional LSTMs are an extension of traditional LSTMs that can improve model performance on sequence classification problems.</p><p>In problems where all timesteps of the input sequence are available, bidirectional LSTMs train two instead of one LSTMs on the input sequence. The first on the input sequence as-is and the second on a reversed copy of the input sequence. This can provide additional context to the network and result in faster and even fuller learning on the problem.</p><p>We know that focusing on the important information will improve the accuracy of the classification. Attention mechanism can therefore highlight the important information from the contextual information by setting different weights. The combination of Bi-LSTM and attention mechanism can further improve the sequence classification accuracy.</p><p>Our model summary and model plot are shown as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*cEPxlyjcl0utGRFAqHVEUQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*ZLK9OfRP_Dp85PKoUZak2A.png" /></figure><h3>Loss Function and Hyperparameter Tuning</h3><h4>Weighted MSE Loss</h4><p>For our loss function, we can implement a very simple weighted MSE loss that is based on the amplitude of y_true. Through our experiments, we found that a weight factor of 2 works the best.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TMb9LcYJpoViyjxnTYJ4dQ.png" /></figure><p>The python code to implement the custom loss function as shown above:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb459350b6b5eff145c6340a59ff3503/href">https://medium.com/media/cb459350b6b5eff145c6340a59ff3503/href</a></iframe><h4>Hyperparameter Tuning</h4><p>Now, we delve into how exactly we approach the hyperparameter tuning of our Seq2seq model.</p><p>For our model, there are different hyperparameters that can be tuned, such as activation functions, optimizers, loss functions, number of neurons for the LSTM layers, and so on. We can use GridSearchCV to loop through all combinations of the hyperparameters. In our experiment, we fixed the epochs to be 20 and batch_size to be 8 for all the cross validation process, which still give us a decent outcome. These fixed epochs and batch_size values will be used for all other hyperparameter space.</p><p>Do note that the final result may not be the most optimal solution, but it should be close to that with much lesser computational costs and time. For brevity, we are just going to refer them as ‘best result’ hereafter.</p><p>First, we can define a ‘mylstm’ class, where we initialize the hyperparameters. We then use self (for both static hyperparameters and hyperparameters to be optimized) to represent the instance of that class. Afterwards, we add in the full architecture of the model, and define some other functions that GridSearchCV may use of (i.e., fit, predict, and score).</p><p>Any future hyperparameter tuning process on complex models can make use of the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58b81d75238a151e7c600cee46f6ebb5/href">https://medium.com/media/58b81d75238a151e7c600cee46f6ebb5/href</a></iframe><h3>GridSearchCV Results and Best Result for Testing</h3><p>We will then set the full parameters space to search as shown in <em>line 2</em> below, and pass them through ‘clf.fit’ as shown in <em>line 5</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af4ebd3fda71ccc57486773166faa5c9/href">https://medium.com/media/af4ebd3fda71ccc57486773166faa5c9/href</a></iframe><p>The best tuning result, which happens to be ‘tanh’, 128 neuron, weight factor of 2 for MSE, and Adam optimizer, is then passed through the model again for the test dataset. We used epochs and batch_size of 160 and 64 respectively, which is exactly 8 times that used in the time-series cross validation process. This is because the samples are roughly 8 times more in the test dataset compared to the single cross validation split (train and test set in one split under time-series cross validation).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38da9eb924479864afaf56c21a6d7db7/href">https://medium.com/media/38da9eb924479864afaf56c21a6d7db7/href</a></iframe><h3>Results and Discussion</h3><p>We will use ‘model.predict’ to obtain the forecasted precipitation value for all 10 lead times. After that, we will perform inverse_transformation and inverse log-transformation to obtain back the original factor of the tp variable as shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dede732de2e73cd32a293922faed289e/href">https://medium.com/media/dede732de2e73cd32a293922faed289e/href</a></iframe><p>We have plotted the R2 score for all 10 lead times:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*uqh7Ip4zhepaMQzlp4YVlA.png" /></figure><h4>Multi-class Confusion Matrix</h4><p>We also test for the classification accuracy of the precipitation forecast to see whether the rainfall are predicted within the same categories. Here are the confusion matrix results for lead time of 1 day:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*lkdiB8mBmZ7EYlWPQQOu9w.png" /></figure><h3>Baseline Models</h3><p>As mentioned earlier, we also experimented with some other baseline models, such as single LSTM Seq2seq model, LightGBM, LSTM without attention mechanism, and so on. We left out the results for non-attention mechanism models because the attention mechanism helped significantly in improving the forecasting accuracy.</p><p>Therefore, we compared between 2 optimizers: Adam and <a href="https://arxiv.org/abs/1711.05101v3">AdamW</a>, single LSTM Seq2seq model with Luong attention and Bidirectional LSTM Seq2seq model with Luong attention, and lastly LightGBM model.</p><p>Here are the MAE, RMSE and R2 results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2PaxcQzRFwrO4kh1jnsskQ.png" /></figure><p>There is no single best model, but <em>Bidirectional-LSTM (Adam optimizer) with Luong attention mechanism, </em>the model that we go through above, seems to perform the best in both RMSE and R2, and around the second best in MAE score (losing to Bidirectional-LSTM (AdamW optimizer)). Perhaps, a more stringent hyperparameter search for learning rate and weight decay for AdamW optimizer might be more useful.</p><p>I hope this article gives you some understanding on the process of climate forecasting.</p><h3>References</h3><p>[1] <a href="https://levelup.gitconnected.com/building-seq2seq-lstm-with-luong-attention-in-keras-for-time-series-forecasting-1ee00958decb">https://levelup.gitconnected.com/building-seq2seq-lstm-with-luong-attention-in-keras-for-time-series-forecasting-1ee00958decb</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e9b23d8ba29" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Climate Downscaling using SRGAN with Multi-Task Learning]]></title>
            <link>https://medium.com/@jackswl/climate-downscaling-using-srgan-with-multi-task-learning-731c8257ef4d?source=rss-caf65b9a635e------2</link>
            <guid isPermaLink="false">https://medium.com/p/731c8257ef4d</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[climate-change]]></category>
            <dc:creator><![CDATA[Jack Shi Wei Lun]]></dc:creator>
            <pubDate>Wed, 14 Jun 2023 14:27:51 GMT</pubDate>
            <atom:updated>2024-07-07T14:12:21.389Z</atom:updated>
            <content:encoded><![CDATA[<h4>Pixels to Precipitation: Unraveling the complexities and importance of climate downscaling, and how to perform them using machine learning methods</h4><figure><img alt="Downscaling image" src="https://cdn-images-1.medium.com/max/702/1*Fut4gc1w0fKfNaRjhJuM1Q.png" /><figcaption>Source: <a href="https://www.engr.scu.edu/~emaurer/old/research.shtml">https://www.engr.scu.edu/~emaurer/old/research.shtml</a></figcaption></figure><p><strong>Acknowledgement</strong>: This article is an excerpt of my project during NUS Undergraduate Research Opportunity Programme, where I worked with Prof. <a href="https://scholar.google.com/citations?user=AWfzBLMAAAAJ&amp;hl=en">Xiaogang HE</a>, <a href="https://github.com/Zhanwei-Liu">Zhanwei LIU</a> and <a href="https://github.com/Hem-W">Huimin WANG</a>. Without them, the idea, research and codes provided in this article would not have been possible.</p><h4>Introduction</h4><p>With the recent advances in AI, inevitably, climate science can also be improved by using machine learning. An insightful <a href="https://arxiv.org/pdf/1906.05433.pdf">paper</a> recently authored by top machine learning experts provides a comprehensive review of potential machine learning applications in fighting climate change, and advocates for using machine learning to address this global challenge. Many articles on Medium also began to stress the importance of climate change and state how machine learning can help.</p><p>However, <em>none</em> of the climate articles on Medium provide a realistic in-depth technical overview of how to use machine learning specifically for climate downscaling, a crucial component within climate science. Furthermore, the majority of the technical articles only explained typical 1-D time-series or 2-D heat map analysis of some variables, or the usage of gradient boosting algorithms for tabular climate data.</p><p>Besides that, climate terminologies are often vague and confusing, with surprisingly few good explanations available online. Even with a vast amount of good climate data available, only a few people are willing to experiment with these data. That being said, experimenting with other data related to popular stock tickers or the latest craze regarding GPT-4 would probably excite these same people.</p><p>I do not blame them.</p><figure><img alt="A typical multidimensional gridded climate data from Xarray" src="https://cdn-images-1.medium.com/max/673/0*dShz9nZ1fBjjg0-g.png" /><figcaption>A typical multidimensional gridded climate data. Source: <a href="https://earth-env-data-science.github.io/lectures/xarray/xarray_intro.html">https://earth-env-data-science.github.io/lectures/xarray/xarray_intro.html</a></figcaption></figure><p>For one, climate data are just way more complex to work with. Scripting, extracting, and post-processing raw climate data take way too much effort compared to a stock ticker. Above the usual time-series analysis, almost all of these climate data are multi-dimensional. It would require some Python libraries like <a href="https://xarray.dev/">Xarray</a> to unpack instead of being able to visualize them nicely into rows and columns.</p><h4>What Is This Article About?</h4><p>The first half of this article aims to provide a <em>comprehensive</em> head start to readers venturing into climate science but feel lost in the vast amount of knowledge, or want to explore climate data using machine learning methods on their own. I have accumulated various resources that benefitted me along way and will be sharing them with you in this article.</p><p>Although many different cool topics within climate science may be tackled using machine learning (e.g., predictions of extreme weather events or CO2 emissions, climate change policy exploration using reinforcement learning), we shall focus specifically on <em>climate downscaling</em> in this article. Multi-task learning with the Super Resolution Generative Adversarial Network (SRGAN) architecture will be the method used to downscale coarse climate models [7] and improve weather forecasts. The reason for discussing this method is because I feel it nicely encapsulates the essence of having <em>novelty</em> while tackling two significant challenges in the field of climate science — <em>bias correction </em>and<em> downscaling</em>.</p><p>We will provide an overview of what exactly is climate downscaling and its importance, some of the methods used for climate downscaling, and discuss three crucial types of climate data that are commonly used as the input and ground truth for most machine learning models.</p><p>In the second half of this article, we will explain what are SRGAN and multi-task learning, and how they can be applied together for climate downscaling. We shall further dive into the study area and input data used, the explanation of loss functions for the two specific tasks, provide explanations and Python codes for the full architecture.</p><p>Feel free to skip to any main section by clicking on the respective link in the table of contents below. <strong>If you are only interested in the SRGAN part of this article, click </strong><a href="#95f0"><strong>here</strong></a><strong>.</strong></p><p><em>Disclaimer</em>: Before this article, the original ground truth data used for this project was slightly different than what was written in this article. Although the current ground truth data used will give much better results, I have currently no access to the computational resources required, so the .h5 models in the last section are not uploaded onto my <a href="https://github.com/jackswl/srganMedium">GitHub</a>. Nonetheless, I hope this article provides a decent overview on the topic of Climate Downscaling, and some insights to SRGAN with Multi-Task Learning.</p><h4>Table of Contents</h4><ul><li><a href="#b8fc">What is Climate Downscaling and Why is it Important?</a></li><li><a href="#1349">Traditional and Deep Learning Methods for Climate Downscaling</a></li><li><a href="#dcc3">Reforecast, Reanalysis, and Station Data</a></li><li><a href="#425e">Study Area and Input Data</a></li><li><a href="#cf50">Loss Functions</a></li><li><a href="#e9dc">Network Architecture</a></li><li><a href="#6595">Training Stage</a></li><li><a href="#13ad">References</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*kHk7W5f_KpdkiSg8.png" /><figcaption>Source: <a href="https://loca.ucsd.edu/">https://loca.ucsd.edu/</a></figcaption></figure><h3>What is Climate Downscaling and Why is it Important?</h3><p>Have you ever started watching a YouTube video, only to be frustrated by its initial blurriness, leading you to wonder why your internet is acting up? Then, as if by magic, the video suddenly becomes crystal clear. That’s basically what we are trying to do in this article (albeit intentionally) — obtaining high-resolution meteorological variables from coarse ones.</p><p>With the onset of global warming in recent years, temperature (including other meteorological fields) and the hydrological cycle are expected to escalate, exacerbating the impacts of extreme weather events such as heat waves droughts and flooding. These events have grim socio-economical consequences [4] on ruining communities, infrastructure, agriculture, and other human-environment systems.</p><p>Unfortunately, most of these crucial planning decisions have to be made based on the coarser resolution climate data, as the high-fidelity and high-resolution climate data are not readily available. These directly affect the usefulness of the policies and accuracy of any climate change impact assessments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/0*bUsiZugqmaRdebmi.jpg" /><figcaption>Forest fire in the Boise National Forest, Idaho, due to human-induced climate change. Source: <a href="https://education.nationalgeographic.org/resource/influence-climate-change-extreme-environmental-events/">https://education.nationalgeographic.org/resource/influence-climate-change-extreme-environmental-events/</a> and photograph by David R. Frazier.</figcaption></figure><p>Here is where <strong>climate downscaling</strong> comes into play.</p><p>It plays a critical role in assisting various applications, including agriculture, water resources management, and urban planning. For instance, agricultural planning necessitates knowledge of local climate conditions such as temperature, precipitation, and soil moisture to optimize crop yields and reduce crop failure risks. Furthermore, downscaled climate projections can provide vital information for designing resilient infrastructure that withstand future climate conditions.</p><p>Climate downscaling can also help policy-makers and decision-makers to evaluate the potential impacts of climate change at the regional level and plan adaptation measures accordingly. This accurate information can then inform government policies to hasten the resilience initiatives regarding climate change impacts, such as sea-level rise, drought, and extreme weather events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*JxS7hnEVXrdBqxwQPZRa-w.jpeg" /><figcaption>An example of the downscaling process for maximum recorded temperature, converting coarse data to a higher resolution. Source: <a href="https://databasin.org/">Databasin.org</a></figcaption></figure><p>In climate science, downscaling refers to the process of refining coarse-resolution global climate models (GCMs) to fine spatial scale ground station data [1, 2], as shown in the image above. Its main goal is to bring GCM data in closer agreement with station level data [3]. It is an essential tool for climate scientists to improve the accuracy of GCMs by providing more detailed information about regional climate patterns. The most common meteorological variables of interest to be downscaled are usually precipitation and temperature (although the former variable is much harder to downscale due to the chaotic behavior of its components and high intermittency in space and time). <em>In this article, we shall focus on downscaling precipitation.</em></p><p>Typically, climate downscaling is performed using either dynamical or statistical methods.</p><p><strong>Dynamical downscaling</strong> involves utilizing high-resolution regional climate models (RCMs) to better resolve finer features of climate variables at the surface, such as temperature, precipitation, and wind patterns. This method requires running the GCM output through a regional climate model with higher resolution and more detailed information about topography and land use. This process yields a more detailed understanding of regional climate patterns and their effects on local communities and ecosystems, but it necessitates significantly more computing power.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5k_vk45s87m6qo4BzuVAMQ.png" /><figcaption>Dynamical downscaling process. Source: By the author, with inspiration from <a href="https://www.gfdl.noaa.gov/climate-model-downscaling/">Geophysical Fluid Dynamics Laboratory</a>.</figcaption></figure><p><strong>Statistical downscaling, </strong>on the other hand, involves using statistical techniques to estimate local climate variables based on the relationship between large-scale and local climate variables. This method is computationally efficient and can be helpful for long-term projections of future climate change impacts.</p><figure><img alt="Statistical downscaling process. Z, T, Q represent geopotential height, air temperature and specific humidity respectively at different pressure levels. Various other predictors can also be used." src="https://cdn-images-1.medium.com/max/1024/0*PjGBKAvBy89Hpns3.png" /><figcaption>Statistical downscaling process. Z, T, Q represent geopotential height, air temperature and specific humidity respectively at different pressure levels. Various other predictors can also be used. Source: <a href="https://bookdown.org/floriandierickx/bookdown-demo/climate-data-discovery.html">https://bookdown.org/floriandierickx/bookdown-demo/climate-data-discovery.html</a></figcaption></figure><p>In the introduction section of this <a href="https://agupubs.onlinelibrary.wiley.com/doi/full/10.1002/2015JD023977">paper</a>, they explained further and provided other papers relevant to the comparison between dynamical and statistical downscaling methods.</p><p>Here are also some good resources on how climate models work, and the history of climate modeling:</p><ul><li><a href="https://www.carbonbrief.org/qa-how-do-climate-models-work/">Q&amp;A: How do climate models work? - Carbon Brief</a></li><li><a href="https://www.carbonbrief.org/timeline-history-climate-modelling/">Timeline: The history of climate modelling - Carbon Brief</a></li></ul><h3>Traditional and Deep Learning Methods for Climate Downscaling</h3><p>In this section, we look at some of the traditional and latest deep learning methods used for climate downscaling. For each method mentioned below, a link to a paper is provided. Do note that the methods are only explained in brevity, as an in-depth explanation of those methods is out of the scope of this article. One should also be aware that numerous downscaling methods are not mentioned below, such as transfer function models, long short-term memory networks, transformers, and <a href="https://journals.plos.org/water/article?id=10.1371/journal.pwat.0000046">many more</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*jyeSCqklg3n6K3XS.png" /><figcaption>Some statistical methods used for downscaling of GCMs. Source: <a href="https://ore.exeter.ac.uk/repository/handle/10871/17139">https://ore.exeter.ac.uk/repository/handle/10871/17139</a></figcaption></figure><h4>Weather Typing</h4><p>The process of <a href="https://hess.copernicus.org/articles/24/2671/2020/">weather typing</a> involves the classification of atmospheric circulation patterns into a finite number of categories. Stochastic models are then used to simulate weather types, while conditional probabilities establish the link between rainfall occurrence and weather type. The resulting weather types can be used to simulate precipitation and other hydro-meteorological processes.</p><p>One of the key benefits of this approach is that it considers the connection between climate at a large scale and weather at a local scale. Weather typing methods are objective, have sound physical basis, and can be used for multisite downscaling [11]. This method also has the potential to generate long sequences of daily precipitation data at a given site using limited historical data sets.</p><h4>Weather Generators</h4><p><a href="https://www.cambridge.org/core/books/statistical-downscaling-and-bias-correction-for-climate-research/weather-generators/4663D1FF8D440DC952EBB522E4042D16">Weather generators</a> (or stochastic rainfall models) are statistical models that generate synthetic sequences of weather variables that statistically resemble daily weather data at a specific location. The <a href="https://towardsdatascience.com/predicting-the-weather-with-markov-chains-a34735f0c4df#:~:text=Build%20a%20Markov%20chain%20based%20on%20historical%20weather%20data&amp;text=According%20to%20Wikipedia%2C,finite%20number%20of%20possible%20states.">Markov chain method</a> is one of the fundamental categories of daily weather generators. In the Markov chain approach, a random process determines the daily rainfall occurrence based on the state of the previous day, while the amount of rainfall is drawn from a probability distribution. The parameters of weather generators can be conditioned on large-scale states or relationships between large-scale and local-scale parameters for statistical downscaling. This conditioning can therefore increase spatial correlation and alleviate the underestimation of inter-annual variations in weather variables, and is a very inexpensive way to do so.</p><h4>Regional Climate Models</h4><p>A <a href="https://agupubs.onlinelibrary.wiley.com/doi/full/10.1029/2018JD030094">regional climate model</a> (RCM) is obtained through <em>dynamically downscaling</em> GCM as mentioned earlier. It is similar to a GCM in that it simulates the physical processes in the climate system. RCMs cover a limited area of the globe and are run at much finer spatial resolution (i.e., 1–50 km grid spacing as opposed to 100–300 km grid spacing in a GCM). Thus they can simulate the interactions between large-scale weather patterns (from a GCM) and the local terrain. How RCM is obtained is that, GCM output data are used to force the RCM at its boundaries and the RCM <em>dynamically downscales</em> the GCM by producing fine-scale weather patterns consistent with the coarse-resolution features in the GCM.</p><p>The disadvantages of a RCM are that it is computationally costly and cannot explicitly remove systematic differences (biases) between the GCM and observations as statistical methods can [5]. Thus, for many applications, some bias corrections are commonly applied to the results to remove the combined biases of the GCM and RCM.</p><h4>Convolutional Neural Networks</h4><p><a href="https://link.springer.com/article/10.1007/s00382-021-05847-0">Convolutional neural networks (CNNs</a>) have also been used as a promising tool for climate downscaling. They can extract relevant spatial and temporal features from large-scale climate data and predict local-scale climate variables with higher accuracy and spatial resolution. The ability of CNNs to capture complex spatiotemporal patterns in climate data can reproduce the fine-scale variability of local climate processes not resolved in GCMs.</p><p>However, like any machine learning approach, CNNs require large amounts of training data, and biases in the training data can affect their performance. Limited interpretability offered by these “black-box” CNN models [6] may also hinder extrapolation analysis, which limits their usefulness in certain applications. Nonetheless, CNNs offer a promising avenue for advancing climate downscaling research and improving our understanding of local-scale climate processes and their impacts on regional and global climate variability.</p><h3>Reforecast, Reanalysis, and Station Data</h3><p>In this section, we discuss three climate data commonly used as inputs, ground truth, or output validation for machine learning models.</p><p>Many different sources provide reforecasts and reanalyses data; you can find some of them here: <a href="https://journals.ametsoc.org/view/journals/mwre/150/1/MWR-D-21-0023.1.xml">GEFSv12 reanalysis</a>, <a href="https://noaa-gefs-retrospective.s3.amazonaws.com/index.html">GEFSv12 reforecast</a> (or <a href="https://registry.opendata.aws/noaa-gefs-reforecast/">here</a>), and <a href="https://cds.climate.copernicus.eu/cdsapp#!/dataset/reanalysis-era5-single-levels?tab=form">ERA5 reanalysis</a>. For our experiment in the second half of this article, we will make use of GEFSv12 reforecast (input) and GEFSv12 reanalysis (ground truth) as our datasets. More details on the data used will be explained later.</p><p>Usually, it can be expected that the reforecast data are used for inputs, and reanalysis data can be used for ground truth (not always the case!). Station data can then be used as ground truth as well, or to validate the final output of the model, since it is expected to be closest to the actual measured variables assuming no errors with the stations.</p><h4>Reforecast</h4><p>Reforecasts (also known as ‘retrospective forecasts’ or ‘hindcasts’) are forecasts run over past dates. In other words, they are produced today but starting from some point in the past [8]. They are normally used to assess the skill of a forecast system (i.e., predictability) or to develop tools for bias correction of the models. Like all forecasts, reforecasts require a set of appropriate initial conditions, which reanalysis can readily supply [8].</p><p>For example, the Global Ensemble Forecast System, version 12 (GEFSv12) that we will be using in our experiment for the next part of this article, uses 5‑member operational ensemble reforecasts that are initialized by the GEFSv12 reanalysis once per day from 00 UTC initial conditions, spanning the period 2000–2019. Once per week, an 11-member reforecast was generated, and these extend in lead time to +35 days [9], although we will not be using these. This in turn can be used to determine long-range forecast anomalies such as the weekly mean deviation of forecasted variables [8]. This would also be ideal as a input dataset for machine learning models.</p><p>Here is a journal explaining the importance of reforecast dataset:</p><p><a href="https://journals.ametsoc.org/view/journals/bams/87/1/bams-87-1-33.xml">Reforecasts: An Important Dataset for Improving Weather Predictions</a></p><h4>Reanalysis</h4><p>Have you ever wondered how are scientists able to obtain the temperature of the Earth’s system hundreds of years ago? Surely, they do not have the measuring tools to perform that back then. Even if there were observations as time progressed, they were usually scattered very far apart and distributed unevenly around the world. Today, our skies are littered with satellites, but a full and accurate picture of the Earth system is still not possible with those observations alone.</p><p>Therefore, reanalysis comes into play by assimilating various data sources of weather observations (explained in the next section) with model information. It will then fill in the gaps between those observed data, reconstruct, and develop a comprehensive record of how weather and climate change over time. Hence, they are globally complete and consistent in time, and are sometimes referred to as ‘maps without gaps’ [10]. This would also be ideal as a ground truth dataset for machine learning models.</p><p>Here are two interesting videos that compare reanalysis data to that of a football kick and a jigsaw puzzle:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fwww.youtube.com%2Fembed%2F7Vcm7WSpPAg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fwww.youtube.com%2Fwatch%3Fv%3D7Vcm7WSpPAg&amp;image=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fi.ytimg.com%2Fvi%2F7Vcm7WSpPAg%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/df6f1434f4ef9f983093c9df543eeffa/href">https://medium.com/media/df6f1434f4ef9f983093c9df543eeffa/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fwww.youtube.com%2Fembed%2FFAGobvUGl24%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fwww.youtube.com%2Fwatch%3Fv%3DFAGobvUGl24&amp;image=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fi.ytimg.com%2Fvi%2FFAGobvUGl24%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5f6615655866b85b25687736931a029/href">https://medium.com/media/c5f6615655866b85b25687736931a029/href</a></iframe><h4>Station/Observational</h4><p>As the name suggests, station data are places where physical properties such as weather conditions, wind speed, cloud cover, and temperature are recorded at a given reporting station. These stations include various sources such as meteorological satellites, drifting ocean buoys, ships, weather balloons, aircraft, and many more (these data can be assimilated for reanalysis). Station data is typically collected using standardized methods and instruments, ensuring high data quality and consistency. Quality control measures are often applied to identify and correct errors or biases in the data, making it a reliable source of climate information for scientific research and applications. Therefore, it is mainly used as a ground truth dataset in machine learning models.</p><p>However, do note that most station data are non-gridded in space, and you would probably have to transform (i.e., interpolate) them into gridded data for direct and accurate validation/comparison with the (likely) gridded output obtained from your machine learning models.</p><p>Here are some good resources on how to handle climate data:</p><ul><li><a href="https://xiaoganghe.github.io/python-climate-visuals/intro.html">Python Climate Visuals</a></li><li><a href="https://nordicesmhub.github.io/climate-data-tutorial/01-introduction/index.html">Introduction</a></li><li><a href="https://tutorial.xarray.dev/intro.html">Welcome to the Xarray Tutorial!</a></li><li><a href="https://towardsdatascience.com/xarray-recipes-for-earth-scientists-c12a10c6a293">Xarray Recipes for Earth Scientists</a></li></ul><p>Next, we give a brief description on how SRGAN and Multi-Task Learning work, and how they can be applied together in climate downscaling. Then, we will delve into the study area and data used, explanation of loss functions used for the two specific tasks, provide Python codes for the full architecture.</p><p><strong>For the full scripts and cleaned climate data files, please refer to my </strong><a href="https://github.com/jackswl/srganMedium"><strong>GitHub</strong></a><strong>. </strong>However, feel free to scrap your own GEFSv12 data for a study area of your own preference from NOAA; there are plenty of resources online showing you how to do that.</p><h3>What are Multi-Task Learning and SRGAN?</h3><p>As mentioned in the first part of the article, there are many ways to go about climate downscaling. In this second part, we shall focus on SRGAN with multi-task learning for climate downscaling.</p><p>Before we go into our full architecture used for climate downscaling, let’s look at what exactly are multi-task learning and SRGAN.</p><h4>Multi-Task Learning</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*G_Sk56BbY4ZxASXX-5oyzQ.png" /><figcaption>Multi-task learning with 2 specific tasks. Source: By the author</figcaption></figure><p>Multi-task learning (MTL) is a machine learning paradigm that enables the simultaneous learning of multiple related tasks using a shared model. Due to its ability to increase model performance and generalization, decrease overfitting, and increase efficiency, MTL has been gaining traction in the machine learning community. Currently, MTL already has a wide range of applications in natural language processing, computer vision (<a href="https://www.youtube.com/watch?v=IHH47nZ7FZU">Tesla’s autopilot</a> uses this approach), and speech recognition, among others.</p><p>One of the key benefits of MTL is the ability to transfer knowledge between somewhat related tasks. By leveraging shared representations across tasks, we hope that MTL can improve the performance of individual tasks. Additionally, MTL can help address the issue of domain shift, where the distribution of the data changes across different tasks or domains (e.g., an algorithm trained on newswires might have to adapt to a new dataset of biomedical documents [12]). By jointly learning across tasks, the model can learn to generalize better to new domains, leading to improved performance on unseen data.</p><p>Here are 2 medium articles that further explained how MTL works:</p><ul><li><a href="https://towardsdatascience.com/multi-task-learning-in-machine-learning-20a37c796c9c">Multi-task learning in Machine Learning</a></li><li><a href="https://medium.com/artificialis/multi-task-deep-learning-with-pytorch-8bf0787ce0e0">Multi-Task Deep Learning with Pytorch</a></li></ul><h4>Super Resolution Generative Adversarial Networks</h4><p>Super Resolution Generative Adversarial Networks (SRGAN) is a deep learning technique used to enhance the resolution and quality of low-resolution images. SRGAN is an extension of Generative Adversarial Networks (GANs), which are a type of deep neural network used for generating synthetic data. The goal of SRGAN is to generate high quality images with a higher resolution than the input images.</p><p>SRGAN works by using a generator network to upscale the low-resolution images and a discriminator network to distinguish between the generated high-resolution images and the real high-resolution images. The generator network learns to generate high-resolution images by minimizing the difference between the generated and real images, while the discriminator network learns to distinguish between the generated and real images.</p><p>One of the main advantages of SRGAN is its ability to generate photo-realistic images with high resolution. SRGAN has shown significant improvement over traditional interpolation-based methods, which only interpolate the pixel values of low-resolution images to create high-resolution images. SRGAN can also be used in a variety of applications, including medical imaging, satellite imaging, and video compression, among others.</p><p>Here are 2 medium articles that provided detailed explanations of how SRGAN works:</p><ul><li><a href="https://jonathan-hui.medium.com/gan-super-resolution-gan-srgan-b471da7270ec">GAN — Super Resolution GAN (SRGAN)</a></li><li><a href="https://medium.com/@ramyahrgowda/srgan-paper-explained-3d2d575d09ff">SRGAN Paper Explained</a></li></ul><h3>SRGAN with Multi-Task Learning for Climate Downscaling</h3><p><strong>Now, we have come to the essence of the article.</strong> So how can we combine SRGAN with MTL for climate downscaling applications? For the sake of brevity and simplicity, the rest of this section shall assume that we are downscaling <em>precipitation</em>. Let’s discuss SRGAN first.</p><h4>SRGAN in Climate Downscaling</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*orynbx967sIPrq6EYarrog.png" /><figcaption>Using only the generator network portion shown in the red box as our shared layers for MTL. Source: <a href="https://arxiv.org/pdf/1609.04802.pdf">https://arxiv.org/pdf/1609.04802.pdf</a></figcaption></figure><p>We can exploit just the generator network of the SRGAN architecture by treating it as the <em>shared network</em> prior to splitting into tasks. The multiple residual blocks in the generator network can extract fine spatial precipitation features while preventing degradation problems for the deep neural network through the usage of convolutional and batch normalization layers. Compared to normal CNN architectures, residual blocks can improve the performance of extensively deep networks without experiencing model accuracy saturation and degradation as residual blocks execute residual mapping and include skipping connections [7].</p><p>In this article, the way that <a href="https://www.analyticsvidhya.com/blog/2021/08/all-you-need-to-know-about-skip-connections/">skipping connection</a> skips layers and connects the next layers is through element-wise addition. A total number of 16 residual blocks were utilized in the SRGAN architecture, making the network extremely deep and capable of extracting fine spatial features.</p><h4>MTL in Climate Downscaling</h4><p>Downscaling of precipitation is composed of two main parts.</p><p><strong>First</strong>, we need to ensure that the precipitation variable is bias corrected. Direct output could be used, but these outputs are often not useful because of significant biases (e.g., rainfall can be consistently too high or low, the model does an incorrect simulation of the monsoon, the rains start too early or too late, and models tend to overestimate the number of days with rain and underestimate precipitation extremes [13]).</p><p><strong>Second </strong>— which is pretty obvious given that this is the whole purpose of downscaling — we need to ensure that the coarse precipitation input is downscaled into higher resolution output.</p><p>Can you see how this can be framed into two distinct (albeit similar) tasks?</p><p><strong>The first task</strong> (<em>task 1</em>) can be framed as a classification problem. We can classify precipitation into categories to bias correct them. For example, they can be classified under its absolute intensity (i.e., light rain for &lt; 2.5mm/h, moderate rain for 2.5mm-10mm/h, heavy rain for 10mm-50mm/h), or can be classified under various quantiles of the training dataset (i.e., 50th, 75th and 95th quantiles). The main purpose of this is to ensure that the rainfall is bias corrected within the right categories (i.e., heavy rain shouldn’t be wrongly classified/predicted as light rain)</p><p><strong>The second task</strong> (<em>task 2</em>)<strong> </strong>handles the downscaling (and intrinsically the bias correction due to the nature of the model) of precipitation. This can be done through the usage of <em>upsampling</em> blocks. Do note, confusingly, the term ‘upsampling’ in computer vision refers to the increase of the spatial resolution of an image, synonymous with the term ‘downscaling’ in climate science.</p><p>Combining the two tasks layers with the shared layers, the full architecture is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*_hQPdbbMAaljtJIne_KLlQ.png" /></figure><p>Without further ado, let’s dive right into the study.</p><h3>Study Area and Input Data</h3><h4>Study Area</h4><p>Our study area will be Singapore, a densely populated city-state with an area of around 721 km2 , is located off the southern end of Malay Peninsula. It is separated from Malaysia by the Straits of Johor to the north and from Indonesia’s Riau Islands by the Singapore Strait to the south. Singapore is situated one-and-a-half degree (137 km) north of the equator, and has a tropical climate with copious precipitation, high and consistent temperatures, and high humidity throughout the year.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5U94cq2HD6aVmMMT6-92KQ.png" /><figcaption>Study area of our postprocessed coarse GEFSv12 data. Each grid represents a data point. One can observe that Singapore is only surrounded by six grid points, which is often too coarse for usage. Source: By the author</figcaption></figure><h4>Input Data and Ground Truth</h4><p>For our coarse input data, we shall make use of GEFSv12 reforecast dataset. We will use GEFSv12 reanalysis dataset as the ground truth.</p><p>Since there are 2 ground truths required for 2 specific tasks, we will have y_class and y_hr, both coming from GEFSv12 reanalysis dataset. y_class will be the classification version of GEFSv12 reanalysis (grouped into 4 precipitation quantiles), whereas y_hr will be the bilinearly downscaled version of GEFSv12 reanalysis, using a total downscaled factor of 12 (3 upsampling blocks). Thus, the final resolution of precipitation will be 96 x 132.</p><p>Similar to how multiple features are usually used to predict a stock price, we can also use multiple meteorological variables to downscale 6-hourly precipitation. Do note that for total precipitation and precipitable water, we included all 5 members (1 control and 4 perturbed members) of the GEFSv12 reforecast data. For 2-meter temperature, convective inhibition and convective available potential energy, we selected only the c00 member.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*6GNXvKPbdWqlmtdeKrANtw.png" /><figcaption>Source: By the author. (The inspiration of what variables to choose from for our input data came from <a href="https://arxiv.org/abs/2203.12297">https://arxiv.org/abs/2203.12297</a>)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*DYGA7IrxUWu-gCMD7h4BTg.png" /><figcaption>Coarse input data of dimensions 8 x 11 x 13. 8 x 11 refers to the latitude and longitude respectively, and 13 refers to the number of variables. Source: By the author</figcaption></figure><h4>Postprocessing of Input Data</h4><p>The datasets are split into training, validation, and testing. The time frame for training is from 2000–01–01 T06 to 2014–01–01 T06, validation is from 2014–01–01 T12 to 2016–12–31 T12, and testing is from 2016–12–31 T18 to 2019–12–31 T18, with total of 20457, 4381, 4381 samples respectively.</p><p>Rainfall samples are all log-transformed to account for its strong non-Gaussian and right-skewed distribution. A pseudo-count of x+1 is applied to transform rainfall values that are 0 mm. Variables that are not rainfall (i.e., 2-meter temperature, convective available potential energy, and convective inhibition forecast) are not log-transformed. After that, a min-max normalization is applied to the training set only for all variables. This min-max normalization is then applied to the validation and test sets to prevent data leakage.</p><p>The input datasets (train, validation, and test) are then concatenated to form a dimension of n x 8 x 11 x 13 as shown below, where n is the sample size of each respective datasets.</p><pre>lst_train_ensemble = [apcp_train_p01, apcp_train_p02, apcp_train_p03, apcp_train_p04, apcp_train_c00,<br>                  pwat_train_p01, pwat_train_p02, pwat_train_p03, pwat_train_p04, pwat_train_c00,<br>                  cape_train_c00, t2m_train_c00, cin_train_c00]<br>                  <br>X_train_ensemble = np.stack((lst_train_ensemble), axis = -1) # stacking 13 variables into 1 single 4D array<br><br>lst_val_ensemble = [apcp_val_p01, apcp_val_p02, apcp_val_p03, apcp_val_p04, apcp_val_c00,<br>                  pwat_val_p01, pwat_val_p02, pwat_val_p03, pwat_val_p04, pwat_val_c00,<br>                  cape_val_c00, t2m_val_c00, cin_val_c00]<br>                  <br>X_val_ensemble = np.stack((lst_val_ensemble), axis = -1) # stacking 13 variables into 1 single 4D array<br><br>lst_test_ensemble = [apcp_test_p01, apcp_test_p02, apcp_test_p03, apcp_test_p04, apcp_test_c00,<br>                  pwat_test_p01, pwat_test_p02, pwat_test_p03, pwat_test_p04, pwat_test_c00,<br>                  cape_test_c00, t2m_test_c00, cin_test_c00]<br>                  <br>X_test_ensemble = np.stack((lst_test_ensemble), axis = -1) # stacking 13 variables into 1 single 4D array</pre><p>The concepts of log-transformation and min-max normalization are similar for the ground truth dataset as well. Do refer to the ‘notebooks’ folder in <a href="https://github.com/jackshiwl/srganMedium">GitHub</a> for more details.</p><h3>Loss Functions</h3><p>For our two specific tasks, we make use of 2 loss functions. The main objective is to…</p><blockquote>… minimize a linear combination of the individual tasks’ loss functions. Each task will have its own individual loss function L_i. So in (the training stage of) our multi-task model, we simply weight each loss function and minimize the sum of these weighted losses — Devin Soni in his Medium article, “<a href="https://towardsdatascience.com/multi-task-learning-in-machine-learning-20a37c796c9c#:~:text=The%20simplest%20approach%20is%20to,sum%20of%20these%20weighted%20losses.">Multi-task learning in Machine Learning</a>”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*IjDohUoAToa4DvIYxu3Oww.png" /><figcaption>Objective function for multi-task learning. Source: <a href="https://cs330.stanford.edu/lecture_slides/cs330_multitask_transfer_2022.pdf">https://cs330.stanford.edu/lecture_slides/cs330_multitask_transfer_2022.pdf</a></figcaption></figure><h4>Task 1: L_1 = Weighted Categorical Cross Entropy Loss</h4><p>The regular cross entropy loss function for classification task can result in underestimation of minority class. Thus, we can apply a weighted cross entropy as loss function for the classification task in order to penalize more towards heavy rain category (i.e. 95th quantile). Our weights for 4 different categories are 4, 19, 23 and 56 for &lt;50th quantile, 50th–75th quantile, 75th–95th quantile, and &gt;95th quantile respectively, which is the inverse percentage of quantiles classes (i.e., 4% dataset contains &gt;95th quantile, which shall be the numerical weight for &lt;50th quantile).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d8e8f9ecbcc4e2fed1bd7651ca2778c/href">https://medium.com/media/8d8e8f9ecbcc4e2fed1bd7651ca2778c/href</a></iframe><h4>Task 2: L_2 = Fraction Skill Score Loss</h4><p>Unlike traditional convolutional outputs where loss computations often revolve around pixel-to-pixel comparisons, our model utilizes a custom loss function that computes loss over an area.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*j3UYfWgsNhpwJ5Xe.png" /><figcaption>Source: <a href="https://jye-lim.github.io/weather_prediction_app/">https://jye-lim.github.io/weather_prediction_app/</a></figcaption></figure><p>The predicted grids with rain are only one grid away from the observed values. Using the built-in loss functions, such as Mean Squared Error (MSE) loss, would result in the model being penalized <strong>twice</strong> for what could be considered a reasonable prediction. The first penalty would be applied to the grid that has observed precipitation but no predicted precipitation, while the second would apply to the grid with predicted precipitation but no observed precipitation. This is despite the model having fairly accurately identified the areas experiencing precipitation.</p><p>To overcome this issue, we implement a custom loss function called the Fractions Skill Score loss [13]. The FSS loss scans an area of size <em>m</em> x <em>m</em> (where <em>m</em> refers to the user-defined mask size), calculating the average precipitation within that area, and then computing the losses between the true and predicted values. This approach better accommodates the spatial nature of our data and mitigates overly penalizing reasonable predictions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00dea8d05cfd912fdb92673537bcdaa6/href">https://medium.com/media/00dea8d05cfd912fdb92673537bcdaa6/href</a></iframe><h3>Network Architecture</h3><p>Here, we create the network architecture for the residual block and the generator. Prior to splitting off into two specific tasks, one convolutional layer (k3n256s1) follows the last element-wise addition operation to summarize feature maps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*orynbx967sIPrq6EYarrog.png" /><figcaption>Using only the generator network portion shown in the red box as our shared layers for MTL. Source: <a href="https://arxiv.org/pdf/1609.04802.pdf">https://arxiv.org/pdf/1609.04802.pdf</a></figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e88a5219dd70cc6d30c9ac1117f79294/href">https://medium.com/media/e88a5219dd70cc6d30c9ac1117f79294/href</a></iframe><p>We add on the two task specific layers after the k3n256s1 convolutional layer in line 27 (<em>task 1</em>) and line 32 (<em>task 2</em>).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/441a1b03c63cb25364d9f2469cf170f2/href">https://medium.com/media/441a1b03c63cb25364d9f2469cf170f2/href</a></iframe><h3>Training Stage</h3><p>After we are done with the full architecture, we can proceed to train the model.</p><p>Here is the code to load all the training and validation datasets:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc37425fd21f2512ce467fdbddefb739/href">https://medium.com/media/dc37425fd21f2512ce467fdbddefb739/href</a></iframe><p>I would like to highlight <strong>line 20</strong> of the code below. In that line, we are using class_loss for task 1, and make_FSS_loss for task 2. Remember, the output1 corresponds to that of task 1, and output2 corresponds to that of task 2.</p><p>We also set the loss weights to be 0.01 for w_1 and 1.0 for w_2, so that the magnitude of the two losses remain roughly the same throughout the training stage.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fc4b6f24fc34e9577731fc90cf43422/href">https://medium.com/media/8fc4b6f24fc34e9577731fc90cf43422/href</a></iframe><p>After running the codes, one can then decide which gen_model.h5 to use based on the losses.txt file to experiment on the test set. This .h5 model can then be used to downscale real-time reforecast GEFSv12 dataset to obtain high-resolution dataset for Singapore. In the future, .h5 models will be uploaded to <a href="https://github.com/jackswl/srganMedium">GitHub</a> as well.</p><p>I hope this article gives you some understanding on the process of climate downscaling. For further technical readings on other topics related to climate science, refer to this website:</p><p><a href="https://climate.copernicus.eu/e-learning-resources">E-learning resources</a></p><h3>References</h3><p>[1] J. Murphy, <a href="https://journals.ametsoc.org/view/journals/clim/12/8/1520-0442_1999_012_2256_aeosad_2.0.co_2.xml?tab_body=pdf">An evaluation of statistical and dynamical techniques for downscaling local climate</a> (1999). <em>Journal of Climate</em>, <em>12</em>(8), pp.2256–2284.</p><p>[2] H. J. Fowler, S. Blenkinsop and C. Tebaldi, <a href="https://rmets.onlinelibrary.wiley.com/doi/abs/10.1002/joc.1556">Linking climate change modelling to impacts studies: recent advances in downscaling techniques for hydrological modelling</a> (2007). <em>International Journal of Climatology: A Journal of the Royal Meteorological Society</em>, <em>27</em>(12), pp.1547–1578.</p><p>[3] Maraun et al, <a href="https://agupubs.onlinelibrary.wiley.com/doi/full/10.1029/2009RG000314">Precipitation downscaling under climate change: Recent developments to bridge the gap between dynamical models and the end user</a> (2010). <em>Reviews of geophysics</em>, <em>48</em>(3).</p><p>[4] T.T. Le et al, <a href="https://link.springer.com/chapter/10.1007/978-981-15-0802-8_191">Development of 48-hour precipitation forecasting model using nonlinear autoregressive neural network</a> (2020)<em>, Innovation for Sustainable Infrastructure: Proceedings of the 5th International Conference on Geotechnics, Civil Engineering Works and Structures</em> (pp. 1191–1196).</p><p>[5] E.P. Salathé, L.R. Leung, Y. Qian and Y. Zhang, <a href="https://cig.uw.edu/wp-content/uploads/sites/2/2020/12/wacciach2rcm643.pdf">Regional climate model projections for the State of Washington</a> (2010). <em>Climatic Change</em>, <em>102</em>, pp.51–75.</p><p>[6] J. Baño-Medina, R. Manzanas and J.M. Gutiérrez, <a href="https://gmd.copernicus.org/articles/13/2109/2020/">Configuration and intercomparison of deep learning neural models for statistical downscaling</a> (2020). <em>Geoscientific Model Development</em>, <em>13</em>(4), pp.2109–2124.</p><p>[7] F. Wang, D. Tian and M. Carroll, <a href="https://gmd.copernicus.org/articles/16/535/2023/">Customized deep learning for precipitation bias correction and downscaling</a> (2023). <em>Geoscientific Model Development</em>, <em>16</em>(2), pp.535–556.</p><p>[8] Frédéric Vitart et al, <a href="https://www.ecmwf.int/en/newsletter/161/meteorology/use-era5-reanalysis-initialise-re-forecasts-proves-beneficial">Use of ERA5 reanalysis to initialise re‑forecasts proves beneficial</a> (2019), ECMWF Newsletter Number 161 — Autumn 2019.</p><p>[9] National Oceanic and Atmospheric Administration, <a href="https://noaa-gefs-retrospective.s3.amazonaws.com/Description_of_reforecast_data.pdf">NOAA’s Global Ensemble Forecast System Version 12: Reforecast Data Storage Information</a></p><p>[10] ECMWF, <a href="https://www.ecmwf.int/sites/default/files/medialibrary/2020-06/ecmwf-fact-sheet-reanalysis.pdf">Fact sheet: Reanalysis</a> (2020).</p><p>[11] Urban Climate Downscaling Portal, <a href="http://ucdp.icwar.iisc.ac.in/downscaling/downscaling-methods/statistical-downscaling/weather-typing/">Weather Typing Methods</a>. Based off a book by Mujumdar &amp; Nagesh Kumar, Floods in a Changing Climate: Hydrologic Modeling.</p><p>[12] H. Daumé III, <a href="https://arxiv.org/abs/0907.1815">Frustratingly easy domain adaptation</a> (2009). <em>arXiv preprint arXiv:0907.1815</em>.</p><p>[13] Ebert-Uphoff et al, <a href="https://arxiv.org/abs/2106.09757">CIRA Guide to Custom Loss Functions for Neural Networks in Environmental Sciences — Version 1</a> (2021). <em>arXiv preprint arXiv:2106.09757</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=731c8257ef4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>