{ "cells": [ { "cell_type": "markdown", "id": "61ea077b", "metadata": { "id": "61ea077b" }, "source": [ "# Exploring TC PRIMED, Chapter 3: Pixel-Based Neural Network Application\n", "- Creators: Naufal Razin1, Kathy Haynes1, and Chris Slocum2\n", "- Affiliation:\n", " - 1Cooperative Institute for Research in the Atmosphere, Colorado State University, Fort Collins, CO\n", " - 2NOAA/NESDIS Center for Satellite Applications and Research, Fort Collins, CO\n", "- History:\n", " - August 15th, 2024: Modified for TC PRIMED v01r01\n", " - November 13th, 2026: Updated\n", " - code to use `tcprimedapi` and new package download routine\n", " - code to transition from TensorFlow to PyTorch\n", "\n", "---\n", "\n", "## Overview\n", "TC PRIMED contains passive microwave observations in their original swath structure. One of the ways in which users can apply a machine learning method to TC PRIMED swath data is by training a machine learning model for individual pixels. In this notebook, we will explore one way to pre-process TC PRIMED passive microwave data and apply a pixel-based machine learning method.\n", "\n", "## Prerequisites\n", "To successfully navigate and use this notebook, you should be familiar with:\n", "- the basics of Python programming such as loading modules, assigning variables, and list/array indexing\n", "- NetCDF files and NetCDF groups (Chapter 1a of this Learning Journey)\n", "- plotting data using `matplotlib`\n", "- TC PRIMED overpass file data structure (Chapter 1b of this Learning Journey)\n", "- basic performance metrics like mean squared error and mean absolute error\n", "\n", "## Learning Outcomes\n", "By working through this notebook, you will learn how to:\n", "- develop a pre-processing step for TC PRIMED passive microwave data for a pixel-based machine learning application\n", "- apply a pixel-based machine learning method to TC PRIMED passive microwave data\n", "\n", "## Time Estimate\n", "- Estimated text reading time: 15 to 29 min\n", "- Estimated code reading time: 11 to 21 min\n", "- Estimated total reading time: 26 to 50 min" ] }, { "cell_type": "markdown", "id": "c97852f4-fdae-4722-9f29-37c112189477", "metadata": { "id": "a4c87fdb" }, "source": [ "## Background\n", "The Tropical Cyclone Precipitation, Infrared, Microwave, and Environmental Dataset (TC PRIMED) is a dataset centered around satellite passive microwave observations of tropical cyclones. TC PRIMED contains data from consistent sources, making it suitable for machine learning applications. For example, the passive microwave brightness temperature data in TC PRIMED has been corrected for any instrument drift and bias such that the observed brightness temperatures are consistent throughout the multiple years each satellite has been in orbit (Berg et al. 2016). Therefore, the differences in observed brightness temperatures are mainly due to differences in the characteristics of the different sensors in TC PRIMED.\n", "\n", "When developing any machine learning model, your dataset would usually consist of input feature(s) and target label(s). The input feature(s) is the input you would use to make your prediction and the target label(s) is what you want to predict. Since TC PRIMED stores passive microwave brightness temperature data in its original swath format, users can take one of two approaches to apply a machine learning model to the TC PRIMED swath data:\n", "- process the swath data (like brightness temperature) into a more uniform data structure and use that as the input feature to predict a storm-scale phenomenon (the target label, e.g., is there a hurricane eye in the passive microwave image?)\n", "- make pixel-based predictions by using the brightness temperature values at each pixel as the input feature to predict the target label within the same pixel (e.g., is there convective or stratiform precipitation in the passive microwave pixel?)\n", "\n", "In this notebook, we will go through an example of the second approach. And, in contrast to the *classification* examples provided above, we will employ a machine learning *regression*. In particular, we will use passive microwave brightness temperature observations from the Global Precipitation Measurement mission (GPM) satellite's Microwave Imager (GMI) sensor as our input feature to predict/regress the target label, which we have chosen to be the surface precipitation rate, at each pixel. Using GMI observations simplifies our example since:\n", "- it makes observations using a conical-scanning sensor, which ensures a constant resolution across the swath\n", "- its observations in the 10.65 GHz through 89.0 GHz frequencies are located on the same swath\n", "\n", "For our surface precipitation rate, we will use the NASA Goddard PROFiling algorithm (GPROF; Kummerow et al. 2015), also included in TC PRIMED. GPROF contains a surface precipitation rate variable that is available on the same swath as the passive microwave observations in the 10.65 through 89.0 GHz frequencies. The GPROF surface precipitation rate variable is in a unit of mm/hour.\n", "\n", "To recap, we will use the GPM passive microwave observations as our input features to predict/regress the surface precipitation rate at each pixel using GPROF as our target label. Note, however, GPROF uses a Bayesian approach, ancillary data such as reanalysis fields, and the passive microwave brightness temperature observations to obtain a precipitation profile within the passive microwave pixel. Therefore, **GPROF is not completely independent from the passive microwave observations.** We are simply using GPROF in this example to avoid additional layers of data pre-processing. Users can use their own independent dataset for a pixel-based prediction by regridding the dataset (e.g., observation from the GPM dual-frequency precipitation radar) onto the passive microwave swath. Figure 1 shows an example of the passive microwave brightness temperature observations and GPROF surface precipitation rate from Hurricane Irma (2017)." ] }, { "cell_type": "markdown", "id": "cbe439f0-9781-4f8d-b12c-f14d2eaded64", "metadata": { "id": "a4c87fdb" }, "source": [ "
\n", "\"Hurricane\n", "\n", "
Figure 1. Example of 36.64 GHz and 89.0 GHz brightness temperatures with GPROF surface precipitation rates from a GPM observation of Hurricane Irma (2017).
\n", " \n", "
" ] }, { "cell_type": "markdown", "id": "231d72d8", "metadata": { "id": "231d72d8" }, "source": [ "## Software\n", "This tutorial uses the Python programming language and packages. We will use:\n", "- `tcprimedapi` to query and retrieve TC PRIMED files from the Amazon Web Service S3 bucket\n", "- `netCDF4` to read in the TC PRIMED file\n", "- `numpy` for simple array operations\n", "- `torch` for meachine learning operations\n", "- `matplotlib` to plot the data" ] }, { "cell_type": "markdown", "id": "bd650713-3740-430b-a489-915292ec950a", "metadata": {}, "source": [ "
\n", " This Learning Journey assumes that the user is running the notebook in a clean conda environment. If the user runs this notebook in an existing environment, it may install a different version of an existing package, and the user would need to restart the kernel after the required package version is installed.\n", "
\n", "
\n", " Users should also note that support for particular packages may not be available for the newest Python versions. If the install code below produces the following error message:\n", "
\n",
    "        ERROR: Could not find a version that satisfies the requirement [package] (from versions: none)\n",
    "        ERROR: No matching distribution found for [package]\n",
    "    
\n", " users will want downgrade their Python version to a version supported by [package].\n", "
" ] }, { "cell_type": "markdown", "id": "e73087dd", "metadata": { "id": "e73087dd" }, "source": [ "### Install Packages\n", "Let's first check if we have the necessary Python packages to run this notebook. If we don't, let's install them." ] }, { "cell_type": "code", "execution_count": null, "id": "de81d429-9a6b-4f3d-acf2-70c1dab5d374", "metadata": {}, "outputs": [], "source": [ "# platform provides access to system hardware, OS, and interpreter\n", "import platform\n", "\n", "# sys provides access to system level information (i.e., the executable for the Python installation)\n", "import sys\n", "\n", "# Different systems can have different Python and package version requirements\n", "# Check the system on which this notebook is running and specify the appropriate\n", "# package versions\n", "system = platform.system()\n", "machine = platform.machine()\n", "python_version = sys.version_info[:2]\n", "\n", "# If system is an Intel-based Mac\n", "if system == \"Darwin\" and machine == \"x86_64\":\n", "\n", " # The Python version needs to be 3.12\n", " # at the latest\n", " required_version = (3, 12)\n", "\n", " # If the Python version is not 3.12, print message\n", " if python_version != required_version:\n", " \n", " print(\"####################################################\")\n", " print(\"You are running this notebook on an Intel-based Mac.\")\n", " print(\"The latest torch version supported for the system \")\n", " print(\"is 2.2.2. The latest Python version to support \")\n", " print(\"torch 2.2.2 is Python 3.12. \")\n", " print(\"Please run this notebook in Python 3.12. \")\n", " print(\"####################################################\")\n", "\n", " # If Python version is 3.12, provide package, distribution name, and version\n", " # to install\n", " else:\n", "\n", " PACKAGES = {\"matplotlib\": {\"distribution_name\": None, \"version\": \"3.11.2\"},\n", " \"numpy\": {\"distribution_name\": None, \"version\": \"1.26.4\"},\n", " \"netCDF4\": {\"distribution_name\": None, \"version\": \"1.7.5.1.post1\"},\n", " \"tcprimedapi\": {\"distribution_name\": None, \"version\": None},\n", " \"torch\": {\"distribution_name\": None, \"version\": \"2.2.2\"}}\n", "\n", "# If system is not an Intel-based Mac\n", "# provide package, distribution name, and version to install\n", "else:\n", "\n", " PACKAGES = {\"matplotlib\": {\"distribution_name\": None, \"version\": None},\n", " \"numpy\": {\"distribution_name\": None, \"version\": None},\n", " \"netCDF4\": {\"distribution_name\": None, \"version\": None},\n", " \"tcprimedapi\": {\"distribution_name\": None, \"version\": None},\n", " \"torch\": {\"distribution_name\": None, \"version\": None}}" ] }, { "cell_type": "code", "execution_count": null, "id": "9503695a-ac10-48b9-a8e6-ae1595161a7c", "metadata": {}, "outputs": [], "source": [ "# subprocess makes system level calls\n", "import subprocess\n", "\n", "# json allows us to query text stored in json format\n", "import json\n", "\n", "# version allows us to check package version\n", "from importlib.metadata import version\n", "\n", "restart_kernel_flag = 0\n", "\n", "# Loop through each package to import\n", "for package in PACKAGES:\n", "\n", " # Get distribution name to use for install\n", " dist_name = package if PACKAGES[package][\"distribution_name\"] is None else PACKAGES[package][\"distribution_name\"]\n", " \n", " try:\n", " \n", " # First, attempt to import the package\n", " __import__(package)\n", "\n", " # Then, obtain the installed package version, the required version, and the\n", " # latest version\n", " installed_version = version(dist_name)\n", " required_version = PACKAGES[package][\"version\"]\n", "\n", " output = subprocess.check_output([sys.executable, '-m', 'pip', 'index', 'versions', '--pre', dist_name, '--json'], text=True)\n", " latest_version = json.loads(output)['latest']\n", "\n", " # Specify the version we require based on required version or latest version\n", " required_version = latest_version if required_version is None else required_version\n", "\n", " # If the required version and doesn't match the installed version\n", " if installed_version != required_version:\n", "\n", " # Get distribution version to use for install\n", " dist_version = \"==\".join([dist_name, required_version])\n", "\n", " # Force reinstall the required distribution version using pip\n", " print('############################################################################')\n", " print(package)\n", " subprocess.check_call([sys.executable, '-m', 'pip', 'install', '--no-cache-dir', '--force-reinstall', dist_version])\n", "\n", " restart_kernel_flag = 1\n", " \n", " except (ImportError, ModuleNotFoundError):\n", "\n", " # Obtain the required package version\n", " required_version = PACKAGES[package][\"version\"]\n", "\n", " # Obtain the latest version\n", " output = subprocess.check_output([sys.executable, '-m', 'pip', 'index', 'versions', '--pre', dist_name, '--json'], text=True)\n", " latest_version = json.loads(output)['latest']\n", "\n", " # Specify the version we require based on required version or latest version\n", " required_version = latest_version if required_version is None else required_version\n", "\n", " # Get distribution version to use for install\n", " dist_version = \"==\".join([dist_name, required_version])\n", "\n", " # Install the distribution version using pip\n", " print('############################################################################')\n", " print(package)\n", " subprocess.check_call([sys.executable, '-m', 'pip', 'install', '--no-cache-dir', dist_version])\n", "\n", "if restart_kernel_flag == 1:\n", " \n", " print('###############################################################')\n", " print('NEW PACKAGE VERSION INSTALLED. RESTART JUPYTER NOTEBOOK KERNEL!')\n", " print('###############################################################')" ] }, { "cell_type": "markdown", "id": "9A1KpT1vQhO2", "metadata": { "id": "9A1KpT1vQhO2" }, "source": [ "Now, let's load the modules in the packages (e.g., `Dataset`) or load the packages and assign a shorter object name for the packages (e.g., `import numpy as np`) for a cleaner use throughout the notebook." ] }, { "cell_type": "code", "execution_count": null, "id": "e5d3acb7", "metadata": { "id": "e5d3acb7" }, "outputs": [], "source": [ "import tcprimedapi\n", "from netCDF4 import Dataset\n", "import numpy as np\n", "import torch\n", "import torch.nn as nn\n", "import matplotlib.pyplot as plt\n", "plt.rcParams['pcolor.shading'] = 'auto'" ] }, { "cell_type": "markdown", "id": "2f8eff2d-cabe-435e-8501-bda75eef04f4", "metadata": {}, "source": [ "## Learning Journey Outline\n", "This Learning Journey walks user through the full machine learning development pipeline using the `torch` (also known as PyTorch) framework and TC PRIMED as the demonstrative dataset. The pipeline is divided into three main sections. They are: Preparing the Data, Building the Model, and Training the Model, with the following subsections:\n", "- Preparing the Data\n", " - Splitting Data into Training, Validation, and Testing Sets\n", " - Retrieving the data from TC PRIMED\n", " - Selecting Input Features and Target Labels\n", " - Normalizing the Data\n", " - Creating a `torch` `Dataset`\n", " - Loading the `Dataset` onto a `torch` `DataLoader`\n", "- Building the Model\n", " - An Introduction to Artificial Neural Networks\n", " - Selecting the Model Hyperparameters\n", " - Identifying and Selecting an Accelerator\n", "- Training the Model\n", " - Selecting the Training Parameters\n", "\n", "Let's begin!" ] }, { "cell_type": "markdown", "id": "0c52ff2a-1afb-410f-9bc6-6be79d64452b", "metadata": {}, "source": [ "## Preparing the Data\n", "Data preparation is often the biggest and most important step in developing a machine learning model. How we prepare the data affects:\n", "- what data our model uses as input and produces as output\n", "- whether our data is optimized to use with the selected framework (in this case, `torch`)\n", "- our model performance\n", "\n", "Often, users prepare their data in the following order:\n", "- selecting the input features and target labels\n", "- normalizing the data\n", "- splitting our data into training, validation, and testing sets\n", "\n", "However, for the purposes of this notebook, we will prepare our data in the following order:\n", "- splitting our data into training, validation, and testing sets\n", "- selecting the input features and target labels\n", "- normalizing the data\n", "\n", "Then, we will proceed with preparing the data for the `torch` framework by creating a `torch` `Dataset` and loading the `Dataset` onto a `DataLoader`.\n", "\n", "Let's begin!" ] }, { "cell_type": "markdown", "id": "6779a4f9", "metadata": { "id": "6779a4f9" }, "source": [ "### Splitting Data Into Training, Validation, and Testing Sets\n", "As we have mentioned in the [background](#Background), your dataset would usually consist of input feature(s) and target label(s). To develop a good machine learning model, this pair of input feature(s) and target label(s) should also be separated into [training, validation, and testing sets](https://mlu-explain.github.io/train-test-validation/). In essence:\n", "- The training set is the dataset you would use to train your model.\n", "- The validation set is the dataset you would use to validate the performance of your trained model. By assessing the performance of the trained model on your validation set, you could decide to tweak the model hyperparameters to try to increase the model skill and/or reduce effects of underfitting or overfitting.\n", "- The testing set is the dataset used to evaluate the final model. The testing set should be completely independent from the training and validation process. **Only evaluate the model on the testing set as a final step, once you are happy with your model performance based on the validation set.**\n", "\n", "Typically, the training set encompasses 60% - 80% of your overall data, while the validation set encompasses 20% - 30% of your data. Equally important, the training, validation, and testing sets should not be from the same sample. In other words, if you want your model to predict tropical cyclone intensification and you use the intensity data from Hurricane Michael to train your model, neither your validation nor testing sets should have any intensity data from Hurricane Michael.\n", "\n", "With these criteria in mind, let's obtain the training, validation, and testing sets from TC PRIMED. When developing a machine learning model, we typically would want to maximize the number of samples that we use. However, for this notebook, we will use only a subset of TC PRIMED data for computing efficiency. Therefore,\n", "- for the training set, we will use a subset of GPM observations from Hurricane Jose (2017).\n", "- for the validation set, we will use a subset of GPM observations from Hurricane Maria (2017).\n", "- for the testing set, we will use a subset of GPM observations from Hurricane Irma (2017)" ] }, { "cell_type": "markdown", "id": "lBu7dk2IdwN0", "metadata": { "id": "lBu7dk2IdwN0" }, "source": [ "#### Read Files Online\n", "Let's retrieve information from the TC PRIMED files that we will use in this example and for the storms that we have listed above. We will retrieve the TC PRIMED files from the [Amazon Web Service (AWS) S3 bucket](https://noaa-nesdis-tcprimed-pds.s3.amazonaws.com/index.html) as part of the [NOAA Open Data Dissemination program (NODD)](https://www.noaa.gov/information-technology/open-data-dissemination). The TC PRIMED team provides a Python package to query and retrieve TC PRIMED files from the AWS S3 bucket called [`tcprimedapi`](https://pypi.org/project/tcprimedapi/). Usually, we will query the available files from the S3 bucket and retrieve the data for those files. However, for computing efficiency in this notebook, we have pre-selected a subset of data that we will use." ] }, { "cell_type": "code", "execution_count": null, "id": "9e765d0a-1eba-42b1-bfe5-5880a4c06a8c", "metadata": {}, "outputs": [], "source": [ "# Specify the names of the files we will use for our training dataset\n", "TRAIN_FILE_NAMES = [\n", " \"v01r01/final/2017/AL/12/TCPRIMED_v01r01-final_AL122017_GMI_GPM_020015_20170906043445.nc\",\n", " \"v01r01/final/2017/AL/12/TCPRIMED_v01r01-final_AL122017_GMI_GPM_020053_20170908155053.nc\",\n", " \"v01r01/final/2017/AL/12/TCPRIMED_v01r01-final_AL122017_GMI_GPM_020062_20170909050741.nc\",\n", " \"v01r01/final/2017/AL/12/TCPRIMED_v01r01-final_AL122017_GMI_GPM_020084_20170910153816.nc\",\n", " \"v01r01/final/2017/AL/12/TCPRIMED_v01r01-final_AL122017_GMI_GPM_020093_20170911045828.nc\",\n", " \"v01r01/final/2017/AL/12/TCPRIMED_v01r01-final_AL122017_GMI_GPM_020124_20170913044940.nc\",\n", " \"v01r01/final/2017/AL/12/TCPRIMED_v01r01-final_AL122017_GMI_GPM_020130_20170913143556.nc\",\n", " \"v01r01/final/2017/AL/12/TCPRIMED_v01r01-final_AL122017_GMI_GPM_020139_20170914035721.nc\",\n", " \"v01r01/final/2017/AL/12/TCPRIMED_v01r01-final_AL122017_GMI_GPM_020170_20170916034806.nc\"\n", " ]\n", "\n", "# Initialize dictionary to store the training data\n", "TRAIN_DS = {}\n", "\n", "# Create an instance of a Client\n", "tcpc_train = tcprimedapi.Client()\n", "\n", "# Specify the files we want to pull using the Client\n", "tcpc_train.object_keys = TRAIN_FILE_NAMES\n", "\n", "# Loop through each file\n", "for object_key, memory in tcpc_train.inmemory():\n", "\n", " # Read the data from each file and store them in the dictionary\n", " TRAIN_DS[object_key] = Dataset(object_key, memory=memory)" ] }, { "cell_type": "code", "execution_count": null, "id": "2cd15866", "metadata": { "id": "2cd15866" }, "outputs": [], "source": [ "# Specify the names of the files we will use for our validation dataset\n", "VAL_FILE_NAMES = [\n", " \"v01r01/final/2017/AL/15/TCPRIMED_v01r01-final_AL152017_GMI_GPM_020200_20170918020233.nc\",\n", " \"v01r01/final/2017/AL/15/TCPRIMED_v01r01-final_AL152017_GMI_GPM_020253_20170921122621.nc\",\n", " \"v01r01/final/2017/AL/15/TCPRIMED_v01r01-final_AL152017_GMI_GPM_020284_20170923121507.nc\",\n", " \"v01r01/final/2017/AL/15/TCPRIMED_v01r01-final_AL152017_GMI_GPM_020345_20170927101954.nc\",\n", " ]\n", "\n", "# Initialize dictionary to store the validation data\n", "VAL_DS = {}\n", "\n", "# Create an instance of a Client\n", "tcpc_val = tcprimedapi.Client()\n", "\n", "# Specify the files we want to pull using the Client\n", "tcpc_val.object_keys = VAL_FILE_NAMES\n", "\n", "# Loop through each file\n", "for object_key, memory in tcpc_val.inmemory():\n", "\n", " # Read the data from each file and store them in the dictionary\n", " VAL_DS[object_key] = Dataset(object_key, memory=memory)" ] }, { "cell_type": "code", "execution_count": null, "id": "35f015fd", "metadata": { "id": "35f015fd" }, "outputs": [], "source": [ "# Specify the names of the files we will use for our validation dataset\n", "TEST_FILE_NAMES = [\n", " \"v01r01/final/2017/AL/11/TCPRIMED_v01r01-final_AL112017_GMI_GPM_019929_20170831162933.nc\",\n", " \"v01r01/final/2017/AL/11/TCPRIMED_v01r01-final_AL112017_GMI_GPM_019938_20170901054652.nc\",\n", " \"v01r01/final/2017/AL/11/TCPRIMED_v01r01-final_AL112017_GMI_GPM_020007_20170905165142.nc\",\n", " \"v01r01/final/2017/AL/11/TCPRIMED_v01r01-final_AL112017_GMI_GPM_020038_20170907164046.nc\",\n", " ]\n", "\n", "# Initialize dictionary to store the training data\n", "TEST_DS = {}\n", "\n", "# Create an instance of a Client\n", "tcpc_test = tcprimedapi.Client()\n", "\n", "# Specify the files we want to pull using the Client\n", "tcpc_test.object_keys = TEST_FILE_NAMES\n", "\n", "# Loop through each file\n", "for object_key, memory in tcpc_test.inmemory():\n", "\n", " # Read the data from each file and store them in the dictionary\n", " TEST_DS[object_key] = Dataset(object_key, memory=memory)" ] }, { "cell_type": "markdown", "id": "395ba67e", "metadata": { "id": "395ba67e" }, "source": [ "### Selecting Input Features and Target Labels\n", "Recall again that we want to predict the surface precipitation rate at each passive microwave pixel. To select the input features and target label, we have to be mindful of two things:\n", "- Land surfaces have varying microwave brightness temperature signatures due to varying land surface types. The subset of observations we have selected above is not big enough to sufficiently capture all the possible surface types, which would affect our model's ability to make predictions. Therefore, for this notebook, we will focus our model on predicting the surface precipitation rates over the more homogeneous ocean surface.\n", "- The passive microwave brightness temperature fields and GPROF surface precipitation rate field may have masked values. When training the model, we must exclude the masked values and only train the model when the selected passive microwave brightness temperature fields *and* the GPROF surface precipitation rate fields contain valid, non-masked values.\n", "\n", "Let's create a function to help us select our input features and target labels. The function will:\n", "- load the appropriate passive microwave brightness temperature fields as our input features\n", "- load the surface type variable included in TC PRIMED for the passive microwave brightness temperature fields, which identifies whether the pixel is located over the land or the ocean\n", "- load the GPROF surface precipitation field as our target label\n", "- find the pixels over the ocean that have valid, non-masked values for **all** our input features and target label\n", "- combine the input features and target label from all TC PRIMED files into their respective input features and target label arrays" ] }, { "cell_type": "code", "execution_count": null, "id": "9aebed67", "metadata": { "id": "9aebed67" }, "outputs": [], "source": [ "def generate_features_and_labels(FILE_DICT, FILE_NAMES, frequencies):\n", " \"\"\"\n", " Generate input features and target labels from a set of TC PRIMED GPM\n", " overpass files\n", "\n", " Parameters\n", " ----------\n", " FILE_DICT : dictionary\n", " dictionary containing the NetCDF instances for each file in FILE_NAMES\n", " FILE_NAMES: array-like\n", " list of TC PRIMED GPM file names from which we want to generate the input\n", " features and target labels\n", " frequencies : array-like\n", " list of GPM observation frequencies we want to use as the input\n", " features\n", "\n", " Returns\n", " -------\n", " features : array-like\n", " array of passive microwave brightness temperatures at each pixel as\n", " our input features\n", " labels : array-like\n", " array of GPROF surface precipitation rate at each pixel as our target\n", " labels\n", " \"\"\"\n", " # Value to replace masked data and to ignore when generating input\n", " # features and target labels\n", " _FillValue = -999.0\n", "\n", " # Since we don't usually know the size of our sample, we will generate an\n", " # empty array and continuously append values\n", "\n", " # Generate a dictionary of emtpy array to store brightness temperature\n", " # values for each observing frequency.\n", " feature_lists = {}\n", " for frequency in frequencies:\n", " feature_lists[frequency] = np.array([])\n", "\n", " # Generate empty array to store GPROF surface precipitation rate\n", " labels = np.array([])\n", "\n", " # Loop through each TC PRIMED GPM file\n", " for FILE_NAME in FILE_NAMES:\n", "\n", " # Load the latitude and longitude values of the observation pixels\n", " # and their corresponding surface type (a.k.a. land/ocean mask)\n", " latitude = FILE_DICT[FILE_NAME][\"passive_microwave/S1/latitude\"][:]\n", " longitude = FILE_DICT[FILE_NAME][\"passive_microwave/S1/longitude\"][:]\n", " surface_type = FILE_DICT[FILE_NAME][\"passive_microwave/S1/surface_type\"][:]\n", "\n", " # Load the surface precipitation rate from GPROF\n", " # Replace the masked value with the specified _FillValue\n", " surfaceprecip = FILE_DICT[FILE_NAME][\"GPROF/S1/surfacePrecipitation\"][:].filled(_FillValue)\n", "\n", " # Find the indices of the pixels that are over the ocean\n", " # In TC PRIMED, ocean and lake surfaces have a flag value of 0\n", " select_idx = np.argwhere(surface_type == 0)\n", "\n", " # Find the indices of the GPROF surface precipitation rate with a valid\n", " # value that is not the _FillValue. Append the indices to the indices of\n", " # pixels over the ocean\n", " select_idx = np.append(select_idx, np.argwhere(surfaceprecip != _FillValue), axis=0)\n", "\n", " # Find all unique indices\n", " # Select the unique indices only if there are more than one in the\n", " # original array (indicating an overlap between the indices for pixels\n", " # over the ocean and GPROF pixels that are not _FillValue)\n", " unique_idx, count_idx = np.unique(select_idx, axis=0, return_counts=True)\n", " select_idx = unique_idx[count_idx > 1]\n", "\n", " # Initialize dictionary to store brightness temperature fields\n", " TB = {}\n", "\n", " # Loop through each observation frequency we want to use as our\n", " # input feature\n", " for frequency in frequencies:\n", "\n", " # Load the brightness temperature field\n", " # Replace the masked value with the specified _FillValue\n", " TB[frequency] = FILE_DICT[FILE_NAME][\"passive_microwave/S1/TB_\" + frequency][:].filled(_FillValue)\n", "\n", " # Append indices of brightness temperature values that are not\n", " # _FillValue to the indices we have already selected above\n", " select_idx = np.append(select_idx, np.argwhere(TB[frequency] != _FillValue), axis=0)\n", "\n", " # Repeat the steps above\n", " # Iteratively select indices for pixels that are over the ocean,\n", " # have GPROF pixels that are not _FillValue, have brightness\n", " # temperature pixels that are not _FillValue, etc.\n", " unique_idx, count_idx = np.unique(select_idx, axis=0, return_counts=True)\n", " select_idx = unique_idx[count_idx > 1]\n", "\n", " # Loop through each index we have selected\n", " for idx in select_idx:\n", "\n", " # Append the value of GPROF surface precipitation rate into our\n", " # target label array\n", " labels = np.append(labels, surfaceprecip[idx[0],idx[1]])\n", "\n", " # Loop through each observation frequency\n", " for frequency in frequencies:\n", "\n", " # Append the value of the brightness temperature into our\n", " # input feature array\n", " feature_lists[frequency] = np.append(feature_lists[frequency], TB[frequency][idx[0],idx[1]])\n", "\n", " # Now, convert dictionary of input feature arrays into a 2-D array\n", " # of input features\n", " for frequency in frequencies:\n", "\n", " if frequency == frequencies[0]:\n", "\n", " features = feature_lists[frequency]\n", "\n", " else:\n", "\n", " features = np.vstack((features, feature_lists[frequency]))\n", "\n", " return np.transpose(features), labels" ] }, { "cell_type": "markdown", "id": "5ab8e8e9", "metadata": { "id": "5ab8e8e9" }, "source": [ "Now that we have a function to select our input features and target labels, let's generate the input features and target labels for our training, validation, and testing sets. During this process, we need to apply our understanding of the physical processes behind our dataset. Our target label is the surface precipitation rate. In order to predict our target label with some skill, we must use the input features that would provide the best information to make the prediction.\n", "\n", "For example, if we want to predict the maximum daily temperature at any time of the year, one of our input features may be the daily minimum solar zenith angle. Low solar zenith angle means that the sun is almost directly overhead. Therefore, the intensity of solar radiation would be stronger and we can expect the maximum daily temperature to be higher. The relationship between the daily minimum solar zenith angle and the maximum daily temperature is based on solid physical understanding of the system we want to predict, and should lead to a machine learning model with some skill. However, if we use a different input feature that is not based on solid physical understanding of the factors that affect the maximum daily temperature — say, the number of times your cat pushes your cup off of your coffee table in a day — then our model will not have any skill.\n", "\n", "NASA briefly describes how the [different GMI observation frequencies](https://gpm.nasa.gov/missions/GPM/GMI) relate to the different types of atmospheric processes. The following list shows the GMI observation frequencies we can use in this notebook:\n", "- 10.65V\n", "- 10.65H\n", "- 18.7V\n", "- 18.7H\n", "- 23.8V\n", "- 36.64V\n", "- 36.64H\n", "- 89.0V\n", "- 89.0H\n", "\n", "To start, let's use the 36.64 GHz and 89.0 GHz observation frequencies as our input features. The 89.0 GHz observation frequency is sensitive to the scattering of Earth radiation by large precipitation-sized ice particles in deep convection. The 36.64 GHz observation frequency is generally sensitive to emission of radiation by liquid precipitation, but can also be affected by scattering processes of large ice particles." ] }, { "cell_type": "code", "execution_count": null, "id": "535da41c", "metadata": { "id": "535da41c" }, "outputs": [], "source": [ "# Select the observing frequencies to use as our\n", "# input features\n", "frequencies = [\"36.64V\", \"36.64H\", \"89.0V\", \"89.0H\"]" ] }, { "cell_type": "markdown", "id": "121302f3", "metadata": { "id": "121302f3" }, "source": [ "Generate the input features and target labels for our trainining, validation, and test sets. **These will take a while to run.**" ] }, { "cell_type": "code", "execution_count": null, "id": "f22d160d", "metadata": { "id": "f22d160d" }, "outputs": [], "source": [ "train_features, train_labels = generate_features_and_labels(TRAIN_DS, TRAIN_FILE_NAMES, frequencies)" ] }, { "cell_type": "code", "execution_count": null, "id": "db1575da", "metadata": { "id": "db1575da" }, "outputs": [], "source": [ "val_features, val_labels = generate_features_and_labels(VAL_DS, VAL_FILE_NAMES, frequencies)" ] }, { "cell_type": "code", "execution_count": null, "id": "cdd7c4d0", "metadata": { "id": "cdd7c4d0" }, "outputs": [], "source": [ "test_features, test_labels = generate_features_and_labels(TEST_DS, TEST_FILE_NAMES, frequencies)" ] }, { "cell_type": "markdown", "id": "obi5T1LxOlCH", "metadata": { "id": "obi5T1LxOlCH" }, "source": [ "### Normalizing the Data\n", "The range of values for our data may vary by the data type. For our input features, brightness temperatures in the 89.0 GHz observation frequency may have a larger spread of possible values (for example, from 50 to 310 K) compared to the brightness temperature in the 36.64 GHz observation frequency. The large range of values in the data, and the varying range of values between the data types, can influence the [speed and stability of our model training](https://machinelearningmastery.com/how-to-improve-neural-network-stability-and-modeling-performance-with-data-scaling/), particularly for deep learning neural networks (as opposed to, say, a random forest model).\n", "\n", "Therefore, we must compress the large range of values in our data and put them on the same scale. The two most common ways to do so are by normalizing or standardizing our data. In this notebook, we will normalize our *input features* before we feed them to our model. Data normalization takes the form of:\n", "$$ x' = \\frac{x - min(x)}{max(x) - min(x)}$$\n", "Here, $x'$ is the normalized value of $x$, and $min(x)$ and $max(x)$ are the respective minimum value and maximum value of $x$. By normalizing the data, we constrain the values of each of our input features to be between zero and one. Typically, the values of $min(x)$ and $max(x)$ come from domain knowledge. But, in this notebook, we will simply obtain them from the training, validation, and testing sets. Let's generate a function to obtain the minimum and maximum values for *each* of our input features." ] }, { "cell_type": "code", "execution_count": null, "id": "FG1rFP_sdLiR", "metadata": { "id": "FG1rFP_sdLiR" }, "outputs": [], "source": [ "def obtain_feature_min_max(frequencies, train_features, val_features, test_features):\n", " \"\"\"\n", " Obtain min and max values of input features from the training, validation,\n", " and testing sets\n", "\n", " Parameters\n", " ----------\n", " frequencies : array-like\n", " list of GPM observation frequencies we want to use as the input\n", " features\n", " train_features : array-like\n", " 2-D array of input features from the training set\n", " val_features : array-like\n", " 2-D array of input features from the validation set\n", " test_features : array-like\n", " 2-D array of input features from the testing set\n", "\n", " Returns\n", " -------\n", " feature_min : dict\n", " dictionary containing the minimum value of each observation frequency\n", " in the input features\n", " feature_max : dict\n", " dictionary containing the maximum value of each observation frequency\n", " in the input features\n", " \"\"\"\n", "\n", " feature_min = {}\n", " feature_max = {}\n", "\n", " for freq_idx, frequency in enumerate(frequencies):\n", "\n", " all_features = np.hstack((train_features[:,freq_idx],\n", " val_features[:,freq_idx],\n", " test_features[:,freq_idx]))\n", "\n", " feature_min[frequency] = np.min(all_features)\n", " feature_max[frequency] = np.max(all_features)\n", "\n", " return feature_min, feature_max" ] }, { "cell_type": "markdown", "id": "-c1cfNlekB6h", "metadata": { "id": "-c1cfNlekB6h" }, "source": [ "Let's obtain the minimum and maximum values of each of our input features using the function we have generated. Then, let's just look at the range of values of the input features." ] }, { "cell_type": "code", "execution_count": null, "id": "FUKOrolEkL_T", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 141, "status": "ok", "timestamp": 1686607951161, "user": { "displayName": "Naufal Razin", "userId": "00945304052336708650" }, "user_tz": 360 }, "id": "FUKOrolEkL_T", "outputId": "7e2aa9c8-44f3-432d-af99-b13d2dd7eff5" }, "outputs": [], "source": [ "feature_min, feature_max = obtain_feature_min_max(frequencies, train_features, val_features, test_features)\n", "\n", "for frequency in frequencies:\n", "\n", " print(\"Observation frequency: \", frequency)\n", " print(\"Minimum value: \", feature_min[frequency])\n", " print(\"Maximum value: \", feature_max[frequency])\n", " print(\" \")" ] }, { "cell_type": "markdown", "id": "fjy8R_sokYR3", "metadata": { "id": "fjy8R_sokYR3" }, "source": [ "Now that we have the minimum and maximum value for each input feature, let's generate a function to normalize the input features." ] }, { "cell_type": "code", "execution_count": null, "id": "huBM39Q_kXwH", "metadata": { "id": "huBM39Q_kXwH" }, "outputs": [], "source": [ "def normalize_input_features(frequencies, input_features, feature_min, feature_max):\n", " \"\"\"\n", " Normalize input features\n", "\n", " Parameters\n", " ----------\n", " frequencies : array-like\n", " list of GPM observation frequencies we want to use as the input\n", " features\n", " input_features : array-like\n", " 2-D array of input features\n", " feature_min : dict\n", " dictionary containing minimum value for each observing frequency\n", " feature_max : dict\n", " dictionary containing maximum value for each observing frequency\n", "\n", " Returns\n", " -------\n", " norm_input_features : array-like\n", " array of input features that have been normalized\n", " \"\"\"\n", "\n", " norm_input_features = np.zeros(input_features.shape)\n", "\n", " for freq_idx, frequency in enumerate(frequencies):\n", "\n", " norm_input_features[:,freq_idx] = (input_features[:,freq_idx] - feature_min[frequency]) / (feature_max[frequency] - feature_min[frequency])\n", "\n", " return norm_input_features" ] }, { "cell_type": "markdown", "id": "a-JzGls8qCAT", "metadata": { "id": "a-JzGls8qCAT" }, "source": [ "Finally, let's obtain the normalized input features for our training, validation, and testing sets." ] }, { "cell_type": "code", "execution_count": null, "id": "GqeZMwBHqKpy", "metadata": { "id": "GqeZMwBHqKpy" }, "outputs": [], "source": [ "norm_train_features = normalize_input_features(frequencies, train_features, feature_min, feature_max)" ] }, { "cell_type": "code", "execution_count": null, "id": "CB-mqJRUqeDd", "metadata": { "id": "CB-mqJRUqeDd" }, "outputs": [], "source": [ "norm_val_features = normalize_input_features(frequencies, val_features, feature_min, feature_max)" ] }, { "cell_type": "code", "execution_count": null, "id": "7x65ylqlqhgI", "metadata": { "id": "7x65ylqlqhgI" }, "outputs": [], "source": [ "norm_test_features = normalize_input_features(frequencies, test_features, feature_min, feature_max)" ] }, { "cell_type": "markdown", "id": "853dfeb8-3de6-40d3-88f9-62bc83d5ccdb", "metadata": {}, "source": [ "### Creating a `torch` `Dataset`\n", "Now that we have normalized our input features, let's merge the features and labels into a `torch` `Dataset`. This step is specific to the `torch` framework. A `torch` `Dataset` allows easier data access by `torch`, including for specifying and calling the data in batches during model training (see [here](https://docs.pytorch.org/tutorials/beginner/basics/data_tutorial.html) for more details). In addition, while building the `torch` `Dataset`, we will also convert our input features and target labels into `torch` `tensors` (see [here](https://docs.pytorch.org/tutorials/beginner/blitz/tensor_tutorial.html) for more details). In essence, `torch` `tensors` allows `torch` to train the model on specialized hardware, like a GPU.\n", "\n", "To create a `torch` `Dataset`, we will have to create a [class](https://en.wikipedia.org/wiki/Class_(programming)). Within the class, we will convert our input features and target labels into `torch` `tensors`. Let's build this class." ] }, { "cell_type": "code", "execution_count": null, "id": "840eda8a-9f79-4d32-9664-46b68f085014", "metadata": {}, "outputs": [], "source": [ "# Create a class called tcprimed_dataset that inherits\n", "# functionality from torch's Dataset class\n", "class tcprimed_dataset(torch.utils.data.Dataset):\n", "\n", " # This step initiates the model whenever we call\n", " # the class. Here, we require the model be initiated\n", " # with the input features and output labels we've\n", " # generated above\n", " def __init__(self, features, labels):\n", "\n", " # Convert the target labels to torch tensors and\n", " # specify them as the targets attribute of the class\n", " self.targets = torch.tensor(labels, dtype=torch.float32)\n", "\n", " # Convert the input features to torch tensors and\n", " # specify them as the predictors attribute of the class\n", " self.predictors = torch.tensor(features, dtype=torch.float32)\n", "\n", " # This step simply returns the total number of samples\n", " # in the dataset\n", " def __len__(self):\n", " return len(self.targets)\n", "\n", " # This step helps fetch a data sample\n", " def __getitem__(self, idx):\n", " return (self.predictors[idx]), (self.targets[idx])" ] }, { "cell_type": "markdown", "id": "b59282f5-790a-42f8-8708-5c327809b06e", "metadata": {}, "source": [ "Now that we have a `Dataset` class, let's generate a `Dataset` for our training and validation sets." ] }, { "cell_type": "code", "execution_count": null, "id": "48260908-8dd5-4533-9a5f-759df7b7f060", "metadata": {}, "outputs": [], "source": [ "train_dataset = tcprimed_dataset(norm_train_features, train_labels)\n", "val_dataset = tcprimed_dataset(norm_val_features, val_labels)" ] }, { "cell_type": "markdown", "id": "e06dfa06-2f35-439f-912e-f6add8f7dcb4", "metadata": {}, "source": [ "### Loading the `Dataset` onto a `torch` `DataLoader`\n", "Finally, let's load our `Dataset` onto a `torch` `DataLoader`. The `DataLoader` helps split our dataset into batches for model training in `torch` (see [here](https://docs.pytorch.org/tutorials/beginner/basics/data_tutorial.html#preparing-your-data-for-training-with-dataloaders) for more details). A batch is a subset of your whole training data. During model training, the model will update its weights and biases based on its performance on the batch, rather than on the whole dataset. Training using batches can help with [a more efficient memory utilization and model generalization](https://wiki.cloudfactory.com/docs/mp-wiki/training-parameters/everything-you-need-to-know-about-batches-in-machine-learning).\n", "\n", "For the purposes of this learning journey, let's load our `Dataset` onto a `torch` `DataLoader` with a batch size of 5000." ] }, { "cell_type": "code", "execution_count": null, "id": "c79e2183-4599-484e-8867-80fad2c1a790", "metadata": {}, "outputs": [], "source": [ "train_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=5000)\n", "val_dataloader = torch.utils.data.DataLoader(val_dataset, batch_size=5000)" ] }, { "cell_type": "markdown", "id": "01cb8792-b200-4de1-b913-fe75a269003d", "metadata": {}, "source": [ "Great! Our data is now ready! Let's proceed to building the model." ] }, { "cell_type": "markdown", "id": "bf397788", "metadata": { "id": "bf397788" }, "source": [ "## Building the Model\n", "### An Introduction to Artificial Neural Network\n", "Here, we provide a basic description of the [artificial neural network](https://www.ibm.com/topics/neural-networks). In *very* simplified terms, the artificial neural network is similar to linear regression but with additional non-linear steps. Let's briefly take a look at the linear regression as an analogy. A linear regression model takes the form of:\n", "$$y = mx + b$$\n", "Where $y$ is your predicted value, $x$ is your input value, $m$ is the weight, and $b$ is the bias. Now, let's say you have an artificial neural network model with two hidden layers. In the first hidden layer, the model takes the input values ($x$) and generates multiple subsets of linear regression models that each produce a predicted value ($y$). The number of linear regression models depends on the number of nodes in the first hidden layer, which is specified by the user. At this point, the model adds non-linearity by applying an activation function to the predicted values from the first hidden layer. This activation function is also specified by the user.\n", "\n", "After the activation function is applied to the predicted values from the first hidden layer, the predicted values become the input values for the next hidden layer, and the process repeats. In the final layer, no activation function is applied and the model linearly regresses the predicted values from the last hidden layer to the target label. During training, the artificial neural network finds the weight ($m$) and bias ($b$) values for each subset of linear regression models by minimizing a loss function (e.g., mean squared error).\n", "\n", "### Selecting the Model Hyperparameters\n", "From the basic description of the artificial neural network model above, you have a few basic [model hyperparameters](https://www.youtube.com/watch?v=h291CuASDno) to choose when building the model:\n", "- the number of hidden layers\n", "- the number of nodes in each hidden layer\n", "- the activation function\n", "\n", "In addition, there are a few other hyperparameters that are more pertinent to model training, such as:\n", "- the loss function\n", "- the optimizer\n", "- the number of epochs\n", "\n", "We will briefly discuss them later, when we train the model. For now, let's look at how to build the model using `torch`. As we have done above, we will create a class for our model. In the class, we specify the model hyperparameters like the number of layers, the number of nodes in each layer, and the activation function. Normally, these hyperparameters are hard-coded. However, we will instead build a class that allows us to easily change the hyperparameters. Let's proceed." ] }, { "cell_type": "code", "execution_count": null, "id": "64cbddd6-5b50-492e-abbb-d2f8a627f661", "metadata": {}, "outputs": [], "source": [ "# Create a class called NeuralNetwork that inherits\n", "# functionality from torch's Module class\n", "class NeuralNetwork(nn.Module):\n", "\n", " # This step initiates the model whenever we call the class\n", " # Here, we require the model to be initiated with the\n", " # hyperparameters that we provide\n", " def __init__(self, input_size, hidden_layers_nodes, activation):\n", "\n", " # Initialize the class using nn.Module\n", " super().__init__()\n", "\n", " # Since we want to have flexibility on the number of\n", " # layers we have in the model, we store all of the layers\n", " # in a list using nn.ModuleList()\n", " self.layers = nn.ModuleList()\n", "\n", " # Create a dictionary with activation functions\n", " # which we will call\n", " self.activation = {\n", " \"relu\": nn.ReLU(),\n", " \"leaky_relu\": nn.LeakyReLU(),\n", " \"tanh\": nn.Tanh(),\n", " \"sigmoid\": nn.Sigmoid()\n", " }[activation]\n", "\n", " # For our first layer, use our input feature size to specify\n", " # the number of input nodes. We will update this as we loop\n", " # through each hidden layer with our specified number of nodes\n", " previous_nodes = input_size\n", "\n", " # Loop through and append each hidden layer with their\n", " # specified number of nodes and our activation function\n", " for nodes in hidden_layers_nodes:\n", "\n", " # Append the layer with specified input and output\n", " # nodes\n", " self.layers.append(\n", " nn.Linear(previous_nodes, nodes)\n", " )\n", "\n", " # Append the activation function for this layer\n", " self.layers.append(self.activation)\n", "\n", " # Update the number of input nodes from the previous\n", " # output nodes\n", " previous_nodes = nodes\n", "\n", " # For the last layer, we will not add an activation function\n", " # and have only one ouput node, for our one predictor\n", " self.layers.append(\n", " nn.Linear(previous_nodes, 1)\n", " )\n", "\n", " # In this step, we define how information travels through our\n", " # model\n", " def forward(self, x):\n", "\n", " # Since we stored the model architecture in specific layers,\n", " # loop through each layer and apply it to our data x\n", " for layer in self.layers:\n", " x = layer(x)\n", "\n", " return x" ] }, { "cell_type": "markdown", "id": "99cb7e68-9add-413e-ae7d-e66e9cd6fe0d", "metadata": {}, "source": [ "From the class we have defined above, there are several things you need to supply:\n", "- The number of input data. Recall, this is the number of observing frequencies we have specified above (e.g., `frequencies = [\"36.64V\", \"36.64H\", \"89.0V\", \"89.0H\"]`. So, this will simply be `len(frequencies)`.\n", "- The number of hidden layers and nodes. We represent these numbers in the form of a list. The number of elements in the list represents the number of hidden layers, while the value for each element represents the number of nodes in that layer. For example, `hidden_layers_nodes = [128, 256]` means that we will have a model with two hidden layers. The first layer will contain 128 nodes, while the second layer will contain 256 nodes.\n", "- The activation function. Notice from the class we've defined, these are simply one of the following\n", " - `\"relu\"` for the [ReLU activation function](https://docs.pytorch.org/docs/2.15/generated/torch.nn.ReLU.html#torch.nn.ReLU)\n", " - `\"leaky_relu\"` for the [Leaky ReLU activation function](https://docs.pytorch.org/docs/2.15/generated/torch.nn.LeakyReLU.html#torch.nn.LeakyReLU)\n", " - `\"tanh\"` for the [Tanh activation function](https://docs.pytorch.org/docs/2.15/generated/torch.nn.Tanh.html#torch.nn.Tanh)\n", " - `\"sigmoid\"` for the [Sigmoid activation function](https://docs.pytorch.org/docs/2.15/generated/torch.nn.Sigmoid.html#torch.nn.Sigmoid)\n", "\n", "### Identifying and Selecting an Accelerator\n", "When we build our model with the hyperparameters above, let's also identify if your local machine has a Graphics Processing Unit (GPU) that we can use to train the model. [GPUs are specialized hardware that can help accelerate model training](https://cloud.google.com/discover/gpu-for-ai). While GPUs are important for heavy computing in complex machine learning models, we don't necessarily need them for this learning journey. Hence, if your local machine does not have a GPU, we will use the [Central Processing Unit (CPU)](https://en.wikipedia.org/wiki/Central_processing_unit) instead. Once we have identified the GPU or CPU (which we will call `device` here), we will transfer our model (which we will call `model`) to it using the `.to(device)` function." ] }, { "cell_type": "code", "execution_count": null, "id": "24a64664-5e2d-4f99-9174-ac107e0c2031", "metadata": {}, "outputs": [], "source": [ "# First, select model hyperparameters\n", "\n", "# Input size based on the number of inputs\n", "# we've selected above\n", "input_size = len(frequencies)\n", "\n", "# Let's create a three-layer model with\n", "# 128, 256, and 128 nodes, respectively\n", "hidden_layers_nodes = [128, 256, 128]\n", "\n", "# Let's use the ReLu activation function\n", "activation = \"relu\"\n", "\n", "# Check and specify accelerator\n", "# If the local machine has nvidia cuda, select that\n", "if torch.cuda.is_available():\n", " device = \"cuda\"\n", "# If the local machine has a Mac accelerator, select that\n", "elif torch.backends.mps.is_available():\n", " device = \"mps\"\n", "# Else, use the CPU\n", "else:\n", " device = \"cpu\"\n", "\n", "# Create the model and transfer the model to\n", "# the accelerator\n", "model = NeuralNetwork(input_size = input_size,\n", " hidden_layers_nodes = hidden_layers_nodes,\n", " activation = activation).to(device)" ] }, { "cell_type": "markdown", "id": "c16cee25-70fb-4b55-92aa-c75d328422fd", "metadata": {}, "source": [ "Great! We've created our model. Let's proceed to traing the model\n", "\n", "## Traing the Model\n", "### Selecting the Training Parameters\n", "There are a few things that we need to specify to train our model.\n", "- The loss function. For our regression problem, two simple loss functions that we can use are the L1Loss (also known as mean absolute error; `nn.L1Loss`) or the mean squared error (`nn.MSELoss`). Let's use the mean squared error loss.\n", "- The optimizer. Which is a function that determines how the weights and biases are modified. For the purpose of this notebook, we'll go with an Adam optimizer with a learning rate of `1e-3`.\n", "- The number of epochs. Which determines how many times we train the model using the full training set. Let's train the model with 100 epochs." ] }, { "cell_type": "code", "execution_count": null, "id": "b281285d-cb5a-4f5c-b2b0-6f76253a1178", "metadata": {}, "outputs": [], "source": [ "# Specify loss function\n", "loss_function = nn.MSELoss()\n", "\n", "# Specify the optimizer\n", "optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)\n", "\n", "# Specify the number of epochs\n", "epochs = 100" ] }, { "cell_type": "markdown", "id": "c8cd32a8-a54c-4a4b-ab84-7239fb7f268e", "metadata": {}, "source": [ "Now we are finally ready to train the model! The code block below will run the model training and validation. During training, the code will perform the following steps:\n", "- Loop through each epoch\n", "- Tell the model that we are training it (`model.train()`).\n", "- Within each epoch, loop through each batch and obtain our training input features (`X`) and target label (`y`).\n", "- Clear our gradients (`optimizer.zero_grad()). For more detail on why this step is needed, see [here](https://www.geeksforgeeks.org/deep-learning/why-do-we-need-to-call-zerograd-in-pytorch/).\n", "- Transfer our training input features and target label to the accelerator (e.g., `X = X.to(device)`).\n", "- Make a prediction on the training input feature using the model (`pred = model(X)`).\n", "- Calculate the model prediction (`pred`) error against our target label (`y`) using the loss function we have selected above (`loss = loss_function(pred.squeeze(), y)`, where `pred.squeeze()` collapses an extra dimension in the model prediction output.\n", "- Calculate the gradients (`loss.backward()`) and update the model biases and weights (`optimizer.step()`). For more detail on these steps, see [here](https://www.geeksforgeeks.org/deep-learning/why-do-we-need-to-call-zerograd-in-pytorch/).\n", "- Calculate the model training loss for all batches. Note that `torch`'s loss function automatically provides the mean of the loss for the batch. Hence, to get the total loss, we will need to multiple the mean loss for the batch by the total batch size (`cumulative_train_loss += loss.item() * X.size(0)`).\n", "- Calculate the average training loss for the epoch (`epoch_train_loss = cumulative_train_loss / len(train_dataset)`) and append it to an array (`train_loss = np.append(train_loss, epoch_train_loss)`)\n", "\n", "The validation step is similar to the training step, except:\n", "- We tell the model that we are evaluating it (`model.eval()`).\n", "- We disable the gradient calculation (`torch.no_grad()`)." ] }, { "cell_type": "code", "execution_count": null, "id": "f7807911-c6ee-4a9e-9c2f-5a3818c9f7de", "metadata": {}, "outputs": [], "source": [ "# Initialize empty arrays to store training and\n", "# validation loss\n", "train_loss = np.array([])\n", "val_loss = np.array([])\n", "\n", "# Loop through each epoch\n", "for epoch in range(epochs):\n", "\n", " # Tell the model that we are training\n", " model.train()\n", "\n", " # Initialize variable to store total training\n", " # loss from all batches in the epoch\n", " cumulative_train_loss = 0.0\n", "\n", " # Load batch of input features and target label\n", " # from the training dataloader\n", " for X, y in train_dataloader:\n", "\n", " # Clear our gradients\n", " optimizer.zero_grad()\n", "\n", " # Transfer input features and target label\n", " # to accelerator\n", " X = X.to(device)\n", " y = y.to(device)\n", "\n", " # Make a prediction using the model\n", " pred = model(X)\n", "\n", " # Calculate the loss for the batch\n", " loss = loss_function(pred.squeeze(), y)\n", "\n", " # Calculate the gradients\n", " loss.backward()\n", "\n", " # Update the weights and biases\n", " optimizer.step()\n", "\n", " # Calculate the total loss across all batches\n", " cumulative_train_loss += loss.item() * X.size(0)\n", "\n", " # Calculate the mean training loss for the epoch\n", " epoch_train_loss = cumulative_train_loss / len(train_dataset)\n", "\n", " # Append the training loss for the epoch to array\n", " train_loss = np.append(train_loss, epoch_train_loss)\n", "\n", " # Tell the model that we are evaluating\n", " model.eval()\n", "\n", " # Initialize variable to store total validation\n", " # loss from all batches in the epoch\n", " cumulative_val_loss = 0.0\n", "\n", " # Disable gradient calculation\n", " with torch.no_grad():\n", "\n", " # Load batch of input features and target label\n", " # from the validation dataloader\n", " for X, y in val_dataloader:\n", "\n", " # Transfer input features and target label\n", " # to accelerator\n", " X = X.to(device)\n", " y = y.to(device)\n", "\n", " # Make a prediction using the model\n", " pred = model(X)\n", "\n", " # Calculate the loss for the batch\n", " loss = loss_function(pred.squeeze(), y)\n", "\n", " # Calculate the total loss across all batches\n", " cumulative_val_loss += loss.item() * X.size(0)\n", "\n", " # Calculate the mean validation loss for the epoch\n", " epoch_val_loss = cumulative_val_loss / len(val_dataset)\n", "\n", " # Append the validation loss for the epoch to array\n", " val_loss = np.append(val_loss, epoch_val_loss)\n", "\n", " # Print information on epoch and training and validation loss\n", " print(f\"Epoch [{epoch+1}/{epochs}], \"\n", " f\"Training Loss: {epoch_train_loss:.6f}, \"\n", " f\"Validation Loss: {epoch_val_loss:.6f}\")" ] }, { "cell_type": "markdown", "id": "42d7cc2f", "metadata": { "id": "42d7cc2f" }, "source": [ "Congratulations! You've successfully trained your own neural network model! Note that if you re-run the cell directly above, the model will continue to be trained. In other words, training the model with 50 epochs twice means the model will be trained with 100 epochs.\n", "\n", "## Analyzing Model Convergence\n", "From running the cell above, you will notice that we've printed out the training and validation loss values at each epoch. Typically, a good model should *eventually* have similar training and validation loss values. In other words, after some number of epochs, a good model should have training and validation loss values that converge. This convergence generally means that the model is generalized enough that it performs just as well on the validation data (data it hasn't seen) as it does on the training data (data it has seen). But, we have also saved the training and validation loss. So, we can plot the evolution of the training and validation loss ourselves. Let's do that!" ] }, { "cell_type": "code", "execution_count": null, "id": "SZQHliTMcO9d", "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 466 }, "executionInfo": { "elapsed": 565, "status": "ok", "timestamp": 1686608045868, "user": { "displayName": "Naufal Razin", "userId": "00945304052336708650" }, "user_tz": 360 }, "id": "SZQHliTMcO9d", "outputId": "b3f7c312-4b44-4cfd-b505-44663cd74bf7" }, "outputs": [], "source": [ "# Plot the training and validation loss values\n", "plt.plot(train_loss, label='Training')\n", "plt.plot(val_loss, label='Validation')\n", "plt.legend()\n", "plt.xlabel('Epoch')\n", "plt.ylabel('MSE')" ] }, { "cell_type": "markdown", "id": "6-FMyW_Wc8Fu", "metadata": { "id": "6-FMyW_Wc8Fu" }, "source": [ "From the plot of loss values above, you can see that the loss values do not converge. This pattern of loss values indicates that our model is overfitting on the training data—it \"memorizes\" the training data instead of learning a general pattern that also applies to the validation data. At this stage, you would want to go back and change the model hyperparameters to constrain the model and prevent it from overfitting. But, since this is just an example exercise, we will proceed and discuss various aspects of the model setup along the way." ] }, { "cell_type": "markdown", "id": "klgrnhOZv4I9", "metadata": { "id": "klgrnhOZv4I9" }, "source": [ "## Analyzing Model Prediction\n", "Now, what does the relationship between the predicted surface precipitation rate values and the actual surface precipitation rate values look like? Let's make a prediction on the training and validation data using the model. Then, let's plot a scatter plot of the values." ] }, { "cell_type": "code", "execution_count": null, "id": "08aaf83d-35f9-4d40-8c46-7f721fc0b67d", "metadata": {}, "outputs": [], "source": [ "# Disable gradient calculation\n", "with torch.no_grad():\n", "\n", " # Make a prediction on the training dataset\n", " # Here, we call the training Dataset predictors and\n", " # transfer them to the accelerator before we run the\n", " # model\n", " train_pred = model(train_dataset.predictors.to(device))\n", "\n", " # Make a prediction on the validation dataset\n", " # Here, we call the validation Dataset predictors and\n", " # transfer them to the accelerator before we run the\n", " # model\n", " val_pred = model(val_dataset.predictors.to(device))" ] }, { "cell_type": "code", "execution_count": null, "id": "0fc1a4cc", "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 504 }, "executionInfo": { "elapsed": 1098, "status": "ok", "timestamp": 1686608067267, "user": { "displayName": "Naufal Razin", "userId": "00945304052336708650" }, "user_tz": 360 }, "id": "0fc1a4cc", "outputId": "1a247d63-0857-4037-ca52-23defce47397" }, "outputs": [], "source": [ "# Plot a scatter plot for the training and validation predictions\n", "plt.figure(figsize=[12,6])\n", "\n", "# For the training set\n", "# Transfer the model prediction from the accelerator\n", "# to the CPU and convert it the a numpy array\n", "# Compare the model prediction against the training\n", "# dataset\n", "plt.subplot(1,2,1)\n", "plt.scatter(train_pred.cpu().numpy(), train_dataset.targets, marker=\"+\", color=\"k\")\n", "\n", "# Plot a one-to-one line\n", "plt.plot([0,100], [0,100], color=\"red\", lw=2)\n", "\n", "plt.xlabel(\"Neural Network\\n Surface Precipitation Rate (mm/hr)\")\n", "plt.ylabel(\"GPROF Surface Precipitation Rate (mm/hr)\")\n", "\n", "plt.title(\"Training Set\")\n", "\n", "# For the validation set\n", "# Transfer the model prediction from the accelerator\n", "# to the CPU and convert it the a numpy array\n", "# Compare the model prediction against the validation\n", "# dataset\n", "plt.subplot(1,2,2)\n", "plt.scatter(val_pred.cpu().numpy(), val_dataset.targets, marker=\"+\", color=\"k\")\n", "\n", "# Plot a one-to-one line\n", "plt.plot([0, 100], [0, 100], color=\"red\", lw=2)\n", "\n", "plt.xlabel(\"Neural Network\\n Surface Precipitation Rate (mm/hr)\")\n", "\n", "plt.title(\"Validation Set\")" ] }, { "cell_type": "markdown", "id": "d3a8ec8a", "metadata": { "id": "d3a8ec8a" }, "source": [ "From the scatter plots, you can see that the neural network model under-predicts surface precipitation rates at the higher end of the surface precipitation rate distribution. In other words, when the actual surface precipitation rates are above 40 mm/hour, the model predicts surface precipitation of only around 20 mm/hour. There are a multitude of factors that may explain the model's skill here. Some of them include:\n", "- the training set that we have used here is not sufficiently big. Recall that we used observations from only nine overpasses of one storm. The sample size is insufficient to properly represent all possible distributions of surface precipitation rates.\n", "- we used only two observation frequencies on which to train the model, the 36.64 and 89.0 GHz. While the 36.64 and 89.0 GHz observation frequencies are important in predicting the surface precipitation rates, other observation frequencies may provide additional independent observations that can help improve the model skill.\n", "- we have not tuned the model hyperparameters to try to get the best model skill.\n", "\n", "Nonetheless, the examples thus far should provide you with a good baseline on which to train a machine learning model for pixel-based applications with TC PRIMED overpass files." ] }, { "cell_type": "markdown", "id": "249819ed", "metadata": { "id": "249819ed" }, "source": [ "### A Thought Experiment\n", "Look at the GPROF surface precipitation field in Figure 1. If you were to guess the *most common* surface precipitation rate value, what would it be? Since precipitation regions occupy only a small portion of the image, the most common surface precipitation rate value would be 0 mm/hour.\n", "\n", "Now, think about our chosen loss value—the mean squared error. If the model is trained on minimizing the mean squared error, how does the *most common* surface precipitation rate value affect the *mean* model error during training? Since most surface precipitation rate values are at or near 0 mm/hour, the model does not do well in predicting cases of really high surface precipitation rate events (e.g., above 30 mm/hour). The choice of the loss function explains, at least partly, the reason behind the model's under-prediction.\n", "\n", "This simple thought experiment highlight the importance of selecting the appropriate model loss function that best suits your purpose." ] }, { "cell_type": "markdown", "id": "jkdKZhKuWCs6", "metadata": { "id": "jkdKZhKuWCs6" }, "source": [ "
\n", "

Exercise 1

Continue to add one observation frequency at a time in the model training. How did adding more observation frequency impact the model skill?\n", "
" ] }, { "cell_type": "markdown", "id": "db69d48f", "metadata": {}, "source": [ "
\n", "

Exercise 2

Up to this point, we have not played around with the testing dataset. Rightly so. The testing dataset should not be touched until you have a final model! However, if you're curious about the model prediction on the testing dataset, repeat the steps above. Do the figures confirm what we understand about the model's deficiencies?\n", "
" ] }, { "cell_type": "markdown", "id": "e4b0114a", "metadata": { "id": "e4b0114a" }, "source": [ "## Applying the Artificial Neural Network Model to a TC PRIMED Overpass\n", "Let's say that you've trained the model, you're happy with the validation scores, and—as the very last step—confirmed your validation scores against the testing set. Congratulations! You have a working model! But now, how do you apply the model to a TC PRIMED overpass? Recall that:\n", "- our model only takes input features in the form of a two-dimensional array.\n", "- we trained the model to only make predictions over the ocean.\n", "- while we have taken care to exclude masked values in training our model, we cannot simply ignore missing values if we want to keep our data in its original shape and format.\n", "\n", "We would have to perform the following steps:\n", "- find the indices of all pixels over land\n", "- replace the masked value in the input features with a \\_FillValue\n", "- find the indices of all \\_FillValue in the input features\n", "- format the input features into a two-dimensional array\n", "- normalize the input features using the min and max values we have obtained above\n", "- run the model on the input features to make predictions, including on the \\_FillValue\n", "- re-format the model predictions to be consistent with the input format\n", "- use the indices of all pixels over land and \\_FillValue in the input features to replace the model predictions with a \\_FillValue\n", "\n", "Let's perform the steps on one overpass from our testing set above, which is an observation of Hurricane Irma (2017)." ] }, { "cell_type": "code", "execution_count": null, "id": "5aa8fc94", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 5595, "status": "ok", "timestamp": 1686608090260, "user": { "displayName": "Naufal Razin", "userId": "00945304052336708650" }, "user_tz": 360 }, "id": "5aa8fc94", "outputId": "66c8eef1-d13f-4630-b108-835013950254" }, "outputs": [], "source": [ "# Retrieve a particular netCDF object from the test sample\n", "DS = TEST_DS[TEST_FILE_NAMES[2]]\n", "\n", "# Load the latitude and longitude values of the observation pixels\n", "# and their corresponding surface type (a.k.a. land/ocean mask)\n", "latitude = DS[\"passive_microwave/S1/latitude\"][:]\n", "longitude = DS[\"passive_microwave/S1/longitude\"][:]\n", "surface_type = DS[\"passive_microwave/S1/surface_type\"][:]\n", "\n", "# Get the shape of the input\n", "input_shape = latitude.shape\n", "\n", "# Find the indices of the pixels that are over land\n", "# In TC PRIMED, land surface has a flag value of 1\n", "select_idx = np.argwhere(surface_type == 1)\n", "\n", "# Initialize array for input features\n", "test_features = []\n", "\n", "# Loop through each observation frequency\n", "for frequency in frequencies:\n", "\n", " # Load the brightness temperature field\n", " # Replace the masked value with -999.0\n", " TB = DS[\"passive_microwave/S1/TB_\" + frequency][:].filled(-999.0)\n", "\n", " # Append indices of brightness temperature values that are\n", " # _FillValue to the indices we have already selected above\n", " select_idx = np.append(select_idx, np.argwhere(TB == -999.0), axis=0)\n", "\n", " # Get only unique indices\n", " select_idx = np.unique(select_idx, axis=0)\n", "\n", " # Put the input features into an array\n", " if frequency == frequencies[0]:\n", "\n", " test_features = TB.flatten()\n", "\n", " else:\n", "\n", " test_features = np.vstack((test_features, TB.flatten()))\n", "\n", "# Transpose the input feature array for model ingest\n", "test_features = np.transpose(test_features)\n", "\n", "# Normalize test features\n", "norm_test_features = normalize_input_features(frequencies, test_features, feature_min, feature_max)\n", "\n", "# Put our test input features and target labels into a torch Dataset\n", "test_dataset = tcprimed_dataset(norm_test_features, test_labels)\n", "\n", "# Load the x, y, and GPROF surface precipitation rates for plotting and\n", "# to compare with the model predictions\n", "# Use NaN value to replace masked value in GPROF surface precipitation\n", "# rate variable, for plotting\n", "x = DS[\"passive_microwave/S1/x\"][:]\n", "y = DS[\"passive_microwave/S1/y\"][:]\n", "GPROF_surfaceprecip = DS[\"GPROF/S1/surfacePrecipitation\"][:].filled(np.nan)\n", "\n", "# Make a prediction with the model\n", "# Disable gradient calculation\n", "with torch.no_grad():\n", " # Make a prediction on the test input dataset\n", " # Here, we call the test Dataset predictors and\n", " # transfer them to the accelerator before we run the\n", " # model\n", " model_surfaceprecip = model(test_dataset.predictors.to(device))\n", "\n", "# Transfer the model prediction from the accelerator\n", "# to the CPU and convert it the a numpy array\n", "# Then, reformat the output to match the input size\n", "model_surfaceprecip = model_surfaceprecip.cpu().numpy().reshape(input_shape)\n", "\n", "# Loop through each index with land pixels or masked value in any of\n", "# the input features\n", "# Replace the model prediction with NaN for plotting\n", "for idx in select_idx:\n", "\n", " model_surfaceprecip[idx[0], idx[1]] = np.nan" ] }, { "cell_type": "code", "execution_count": null, "id": "53a1de2c", "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 621 }, "executionInfo": { "elapsed": 1171, "status": "ok", "timestamp": 1686608094703, "user": { "displayName": "Naufal Razin", "userId": "00945304052336708650" }, "user_tz": 360 }, "id": "53a1de2c", "outputId": "66c2be00-80a4-481a-8e55-5d317804fbe3" }, "outputs": [], "source": [ "# Set figure size\n", "plt.figure(figsize=[12,8])\n", "\n", "# For the model surface precipitation prediction\n", "plt.subplot(1,2,1)\n", "plt.pcolormesh(x, y, model_surfaceprecip, vmin=0, vmax=50, cmap=\"viridis_r\")\n", "plt.colorbar(orientation=\"horizontal\", pad=0.13, label=\"ANN Surface Precipitation Rates (mm/hr)\")\n", "\n", "plt.xlim(-500, 500)\n", "plt.xlabel(\"Zonal Distance from Tropical Cyclone Center (km)\")\n", "plt.ylim(-500, 500)\n", "plt.ylabel(\"Meridional Distance from Tropical Cyclone Center (km)\")\n", "\n", "# For the GPROF surface precipitation field\n", "plt.subplot(1,2,2)\n", "plt.pcolormesh(x, y, GPROF_surfaceprecip, vmin=0, vmax=50, cmap=\"viridis_r\")\n", "plt.colorbar(orientation=\"horizontal\", pad=0.13, label=\"GPROF Surface Precipitation Rates (mm/hr)\")\n", "\n", "plt.xlim(-500, 500)\n", "plt.xlabel(\"Zonal Distance from Tropical Cyclone Center (km)\")\n", "plt.ylim(-500, 500)" ] }, { "cell_type": "markdown", "id": "754ab78f", "metadata": { "id": "754ab78f" }, "source": [ "As we can see from above, our artifical neural network model does really well at capturing the general structure of Hurricane Irma's precipitation field. However, as we have discussed above, the model could not capture the magnitude of the surface precipitation rates, when compared to GPROF. In addition, our model field contains a few areas with missing values. These areas correspond to pixels located over the islands of the Lesser Antilles. Since the pixels are over land and we trained our model to predict the surface precipitation rates over the ocean, we have replaced the model's prediction here with NaN. Finally, note that the GPROF swath is slightly narrower than the microwave swath, due to the algorithm design which we will not discuss." ] }, { "cell_type": "markdown", "id": "K96FAtHubeLI", "metadata": { "id": "K96FAtHubeLI" }, "source": [ "## Close the File\n", "When loading data from a NetCDF file, **always remember to close the file**. A best practice would be to close the file immediately after loading the variable or attribute of interest. However, since we're loading various variables throughout this notebook, we will close the files at the end of this notebook using the command below." ] }, { "cell_type": "code", "execution_count": null, "id": "2qnk0eVBbt4F", "metadata": { "id": "2qnk0eVBbt4F" }, "outputs": [], "source": [ "for train_file_name in TRAIN_FILE_NAMES:\n", " TRAIN_DS[train_file_name].close()\n", "\n", "for val_file_name in VAL_FILE_NAMES:\n", " VAL_DS[val_file_name].close()\n", "\n", "for test_file_name in TEST_FILE_NAMES:\n", " TEST_DS[test_file_name].close()" ] }, { "cell_type": "markdown", "id": "a425d438", "metadata": { "id": "a425d438" }, "source": [ "## Final Thoughts\n", "The example shown here demonstrates one way in which you can use TC PRIMED for machine learning applications—a pixel-based approach. More complex approaches, as we have noted above, require more data pre-processing such as re-gridding the observations onto a common, equidistant grid. We explore one method for re-gridding TC PRIMED in another notebook.\n", "\n", "In this tutorial, you learned to pre-process TC PRIMED overpass data for a pixel-based machine learning application. Subsequently, you learned how to set up your artificial neural network model and train it on your dataset. Then, you learned how to apply the model to a TC PRIMED overpass.\n", "\n", "The simple approaches adopted in this tutorial is meant to demonstrate a machine learning application. For greater success, you should include more data in training your model and experiment with the model hyperparameters that would get you the best model skill while not underfitting or overfitting on your data." ] }, { "cell_type": "markdown", "id": "77ce50a9", "metadata": { "id": "77ce50a9" }, "source": [ "## Data Statement\n", "- Razin, Muhammad Naufal; Slocum, Christopher J.; Knaff, John A.; Brown, Paula J. 2023. Tropical Cyclone PRecipitation, Infrared, Microwave, and Environmental Dataset (TC PRIMED). v01r01. NOAA National Centers for Environmental Information. https://doi.org/10.25921/dmy1-0595." ] }, { "cell_type": "markdown", "id": "afbad221", "metadata": { "id": "afbad221" }, "source": [ "## References\n", "- Berg, W., and Coauthors, 2016: Intercalibration of the GPM microwave radiometer constellation. J. Atmos. Oceanic Technol., 33, 2639–2654, https://doi.org/10.1175/JTECH-D-16-0100.1\n", "- Kummerow, C. D., D. L. Randel, M. Kulie, N.-Y. Wang, R. Ferraro, S. J. Munchak, and V. Petkovic, 2015: The evolution of the Goddard profiling algorithm to a fully parametric scheme. J. Atmos. Oceanic Technol., 32, 165–176, https://doi.org/10.1175/JTECH-D-15-0039.1" ] }, { "cell_type": "markdown", "id": "cb3e4863", "metadata": { "id": "cb3e4863" }, "source": [ "## Metadata\n", "- Language / package(s)\n", " - Python\n", " - tcprimedapi\n", " - netCDF4\n", " - numpy\n", " - torch\n", " - matplotlib\n", "- Domain\n", " - NOAA\n", " - NASA\n", "- Application keywords\n", " - Satellite passive microwave\n", " - NASA Goddard PROFiling Algorithm\n", "- Geophysical keywords\n", " - Tropical cyclones\n", " - Surface precipitation rate\n", "- AI keywords\n", " - Data pre-processing\n", " - Artificial Neural Network" ] }, { "cell_type": "markdown", "id": "c13316a3", "metadata": { "id": "afacdc60" }, "source": [ "## Disclaimer\n", "\n", "This Jupyter notebook is a scientific product and is not official communication of the National Oceanic and Atmospheric Administration, or the United States Department of Commerce. All NOAA Jupyter notebooks are provided on an 'as is' basis and the user assumes responsibility for its use. Any claims against the Department of Commerce or Department of Commerce bureaus stemming from the use of this Jupyter notebook will be governed by all applicable Federal law. Any reference to specific commercial products, processes, or services by service mark, trademark, manufacturer, or otherwise does not constitute or imply their endorsement, recommendation or favoring by the Department of Commerce. The Department of Commerce seal and logo, or the seal and logo of a DOC bureau, shall not be used in any manner to imply endorsement of any commercial product or activity by DOC or the United States Government." ] }, { "cell_type": "code", "execution_count": null, "id": "2c0aefe2", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "colab": { "provenance": [] }, "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.11" }, "toc": { "base_numbering": 1, "nav_menu": {}, "number_sections": true, "sideBar": true, "skip_h1_title": false, "title_cell": "Table of Contents", "title_sidebar": "Contents", "toc_cell": false, "toc_position": {}, "toc_section_display": true, "toc_window_display": true } }, "nbformat": 4, "nbformat_minor": 5 }