{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Training with Opensoundscape & Pytorch Lightning\n", "\n", "OpenSoundscape provides classes that support the use of Pytorch Lightning's Trainer class, which implements various training techniques, speedups, and utilities. To use Lightning, simply use the `opensoundscape.ml.lightning.LightningSpectrogramModule` class rather than the `opensoundscape.ml.cnn.SpectrogramClassifier` class (or `CNN` class, which is now an alias for `SpectrogramClassifier`). For the most part, the API and functionality is similar to the pure-pytorch classes, with a few major differences:\n", "- to train, call the `.fit_with_trainer()` method (\"train()\" method is reserved for other purposes when using Lightning). Pass any kwargs to lightning.Trainer()to customize the Lightning Trainer. \n", "- to predict, call `.predict_with_trainer()`, passing any kwargs for the lightning.Trainer init with `lightning_trainer_kwargs=dict(...)`\n", "- note that with the Lightning Trainer, you can use various logging platforms, while only Weights and Biases is currently supported in the pure PyTorch classes\n", "\n", "Check out the lightning.Trainer [docs](https://lightning.ai/docs/pytorch/stable/common/trainer.html) for the full set of implemented features." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# if this is a Google Colab notebook, install opensoundscape in the runtime environment\n", "if 'google.colab' in str(get_ipython()):\n", " %pip install \"opensoundscape==0.12.1\" \"jupyter-client<8,>=5.3.4\" \"ipykernel==6.17.1\"\n", " num_workers=0\n", "else:\n", " num_workers=4" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Setup" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Import needed packages" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "# the cnn module provides classes for training/predicting with various types of CNNs\n", "from opensoundscape import CNN\n", "\n", "#other utilities and packages\n", "import torch\n", "import pandas as pd\n", "from pathlib import Path\n", "import numpy as np\n", "import pandas as pd\n", "import random \n", "import subprocess\n", "from glob import glob\n", "import sklearn\n", "\n", "#set up plotting\n", "from matplotlib import pyplot as plt\n", "plt.rcParams['figure.figsize']=[15,5] #for large visuals\n", "%config InlineBackend.figure_format = 'retina'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Set random seeds\n", "\n", "Set manual seeds for Pytorch and Python. These essentially \"fix\" the results of any stochastic steps in model training, ensuring that training results are reproducible. You probably don't want to do this when you actually train your model, but it's useful for debugging." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "torch.manual_seed(0)\n", "random.seed(0)\n", "np.random.seed(0)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Download files\n", "\n", "Training a machine learning model requires some pre-labeled data. These data, in the form of audio recordings or spectrograms, are labeled with whether or not they contain the sound of the species of interest. \n", "\n", "These data can be obtained from online databases such as Xeno-Canto.org, or by labeling one's own ARU data using a program like Cornell's Raven sound analysis software. In this example we are using a set of annotated avian soundscape recordings that were annotated using the software Raven Pro 1.6.4 (Bioacoustics Research Program 2022):\n", "\n", "
An annotated set of audio recordings of Eastern North American birds containing frequency, time, and species information. Lauren M. Chronister, Tessa A. Rhinehart, Aidan Place, Justin Kitzes.\n", "https://doi.org/10.1002/ecy.3329 \n", "\n", "\n", "These are the same data that are used by the annotation and preprocessing tutorials, so you can skip this step if you've already downloaded them there." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Download example files\n", "Download a set of example audio files and Raven annotations:\n", "\n", "Option 1: run the cell below\n", "\n", "- if you get a 403 error, DataDryad suspects you are a bot. Use Option 2. \n", "\n", "Option 2:\n", "\n", "- Download and unzip both `annotation_Files.zip` and `mp3_Files.zip` from the https://datadryad.org/stash/dataset/doi:10.5061/dryad.d2547d81z \n", "- Move the unzipped contents into a subfolder of the current folder called `./annotated_data/`" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "# # Note: the \"!\" preceding each line below allows us to run bash commands in a Jupyter notebook\n", "# # If you are not running this code in a notebook, input these commands into your terminal instead\n", "# !wget -O annotation_Files.zip https://datadryad.org/stash/downloads/file_stream/641805;\n", "# !wget -O mp3_Files.zip https://datadryad.org/stash/downloads/file_stream/641807;\n", "# !mkdir annotated_data;\n", "# !unzip annotation_Files.zip -d ./annotated_data/annotation_Files;\n", "# !unzip mp3_Files.zip -d ./annotated_data/mp3_Files;" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Prepare training and validation data\n", "\n", "To prepare audio data for machine learning, we need to convert our annotated data into clip-level labels.\n", "\n", "These steps are covered in depth in other tutorials, so we'll just set our clip labels up quickly for this example.\n", "\n", "First, get exactly matched lists of audio files and their corresponding selection files:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/Users/SML161/opensoundscape/opensoundscape/annotations.py:300: FutureWarning: The behavior of DataFrame concatenation with empty or all-NA entries is deprecated. In a future version, this will no longer exclude empty or all-NA columns when determining the result dtypes. To retain the old behavior, exclude the relevant entries before the concat operation.\n", " all_annotations_df = pd.concat(all_file_dfs).reset_index(drop=True)\n" ] } ], "source": [ "# Set the current directory to where the dataset is downloaded\n", "dataset_path = Path(\"./annotated_data/\")\n", "\n", "# Make a list of all of the selection table files\n", "selection_files = glob(f\"{dataset_path}/annotation_Files/*/*.txt\")\n", "\n", "# Create a list of audio files, one corresponding to each Raven file\n", "# (Audio files have the same names as selection files with a different extension)\n", "audio_files = [\n", " f.replace(\"annotation_Files\", \"mp3_Files\").replace(\n", " \".Table.1.selections.txt\", \".mp3\"\n", " )\n", " for f in selection_files\n", "]\n", "\n", "# Next, convert the selection files and audio files to a `BoxedAnnotations` object, which contains\n", "# the time, frequency, and label information for all annotations for every recording in the dataset.\n", "\n", "from opensoundscape.annotations import BoxedAnnotations\n", "\n", "# Create a dataframe of annotations\n", "annotations = BoxedAnnotations.from_raven_files(\n", " raven_files=selection_files, audio_files=audio_files, annotation_column=\"Species\"\n", ")\n", "\n", "\n", "# Parameters to use for label creation\n", "clip_duration = 3\n", "clip_overlap = 0\n", "min_label_overlap = 0.25\n", "species_of_interest = [\"NOCA\", \"EATO\", \"SCTA\", \"BAWW\", \"BCCH\", \"AMCR\", \"NOFL\"]\n", "\n", "# Create dataframe of one-hot labels\n", "clip_labels = annotations.clip_labels(\n", " clip_duration=clip_duration,\n", " clip_overlap=clip_overlap,\n", " min_label_overlap=min_label_overlap,\n", " class_subset=species_of_interest, # You can comment this line out if you want to include all species.\n", ")\n", "\n", "from sklearn.model_selection import train_test_split\n", "\n", "train_df, val_df = train_test_split(clip_labels, test_size=0.2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Create Lightning-copmatible model" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, create a LightningSpectrogramModule object, which integrates OpenSoundscape with Pytorch Lightning's powerful Trainer class" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Create a CNN object designed to recognize 3-second samples\n", "from opensoundscape.ml.lightning import LightningSpectrogramModule\n", "\n", "# initializing it looks the same as for the CNN class.\n", "# Let's use resnet34 architecture and 3s clip duration\n", "model = LightningSpectrogramModule(\n", " architecture=\"resnet34\", classes=clip_labels.columns.tolist(), sample_duration=3\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Train with Lightning\n", "\n", "Lightning will take a bit of time to get things set up. After that, it can be substantially faster than training in pure PyTorch." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "GPU available: True (mps), used: True\n", "TPU available: False, using: 0 TPU cores\n", "HPU available: False, using: 0 HPUs\n", "/Users/SML161/miniconda3/envs/opso_dev/lib/python3.9/site-packages/lightning/pytorch/trainer/connectors/logger_connector/logger_connector.py:75: Starting from v1.9.0, `tensorboardX` has been removed as a dependency of the `lightning.pytorch` package, due to potential conflicts with other packages in the ML ecosystem. For this reason, `logger=True` will use `CSVLogger` as the default logger, unless the `tensorboard` or `tensorboardX` packages are found. Please `pip install lightning[extra]` or one of them to enable TensorBoard support by default\n", "/Users/SML161/miniconda3/envs/opso_dev/lib/python3.9/site-packages/lightning/pytorch/callbacks/model_checkpoint.py:654: Checkpoint directory /Users/SML161/opensoundscape/docs/tutorials exists and is not empty.\n", "/Users/SML161/miniconda3/envs/opso_dev/lib/python3.9/site-packages/lightning/pytorch/core/optimizer.py:377: Found unsupported keys in the optimizer configuration: {'scheduler'}\n", "\n", " | Name | Type | Params | Mode \n", "----------------------------------------------------------\n", "0 | network | ResNet | 21.3 M | train\n", "1 | loss_fn | BCEWithLogitsLoss_hot | 0 | train\n", "----------------------------------------------------------\n", "21.3 M Trainable params\n", "0 Non-trainable params\n", "21.3 M Total params\n", "85.128 Total estimated model params size (MB)\n", "117 Modules in train mode\n", "0 Modules in eval mode\n" ] }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "3fcb2deddf7a49bdac24bcf873101c1d", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Sanity Checking: | | 0/? [00:00, ?it/s]" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stderr", "output_type": "stream", "text": [ "/Users/SML161/miniconda3/envs/opso_dev/lib/python3.9/site-packages/lightning/pytorch/trainer/connectors/data_connector.py:419: Consider setting `persistent_workers=True` in 'val_dataloader' to speed up the dataloader worker initialization.\n", "/Users/SML161/miniconda3/envs/opso_dev/lib/python3.9/site-packages/torchmetrics/functional/classification/precision_recall_curve.py:798: UserWarning: MPS: nonzero op is supported natively starting from macOS 13.0. Falling back on CPU. This may have performance implications. (Triggered internally at /Users/runner/work/pytorch/pytorch/pytorch/aten/src/ATen/native/mps/operations/Indexing.mm:334.)\n", " unique_mapping = unique_mapping[unique_mapping >= 0]\n", "/Users/SML161/miniconda3/envs/opso_dev/lib/python3.9/site-packages/torchmetrics/functional/classification/average_precision.py:308: UserWarning: MPS: no support for int64 for sum_out_mps, downcasting to a smaller data type (int32/float32). Native support for int64 has been added in macOS 13.3. (Triggered internally at /Users/runner/work/pytorch/pytorch/pytorch/aten/src/ATen/native/mps/operations/ReduceOps.mm:157.)\n", " weights=(state[1] == 1).sum(dim=0).float() if thresholds is None else state[0][:, 1, :].sum(-1),\n", "/Users/SML161/miniconda3/envs/opso_dev/lib/python3.9/site-packages/lightning/pytorch/trainer/connectors/data_connector.py:419: Consider setting `persistent_workers=True` in 'train_dataloader' to speed up the dataloader worker initialization.\n" ] }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "1aa762c4cb074f8db39be0cce5a3579b", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Training: | | 0/? [00:00, ?it/s]" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "38438d1dcb6d49c1a86c5a610edf306b", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Validation: | | 0/? [00:00, ?it/s]" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "377c2e3d802a4ff6bb9c0a014c5c724c", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Validation: | | 0/? [00:00, ?it/s]" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "e114210a375c43bc8bdefc9eb5f310ec", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Validation: | | 0/? [00:00, ?it/s]" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "a7c72b7dda2b46c4ac5cf91998eae4de", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Validation: | | 0/? [00:00, ?it/s]" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stderr", "output_type": "stream", "text": [ "`Trainer.fit` stopped: `max_epochs=4` reached.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Training complete\n", "Best model with score 0.181 is saved to /Users/SML161/opensoundscape/docs/tutorials/epoch=3-step=388.ckpt\n", "0 of 6160 total training samples failed to preprocess\n" ] }, { "data": { "text/plain": [ "
| \n", " | \n", " | \n", " | NOCA | \n", "EATO | \n", "SCTA | \n", "BAWW | \n", "BCCH | \n", "AMCR | \n", "NOFL | \n", "
|---|---|---|---|---|---|---|---|---|---|
| file | \n", "start_time | \n", "end_time | \n", "\n", " | \n", " | \n", " | \n", " | \n", " | \n", " | \n", " |
| annotated_data/mp3_Files/Recording_1/Recording_1_Segment_26.mp3 | \n", "123.0 | \n", "126.0 | \n", "-1.150377 | \n", "0.549135 | \n", "-2.138953 | \n", "-2.694704 | \n", "-0.467310 | \n", "4.545997 | \n", "-4.263886 | \n", "
| annotated_data/mp3_Files/Recording_2/Recording_2_Segment_11.mp3 | \n", "132.0 | \n", "135.0 | \n", "-1.627193 | \n", "-2.231425 | \n", "-0.292491 | \n", "-3.995329 | \n", "-2.961541 | \n", "4.214307 | \n", "-4.755819 | \n", "
| annotated_data/mp3_Files/Recording_4/Recording_4_Segment_23.mp3 | \n", "138.0 | \n", "141.0 | \n", "3.111156 | \n", "1.366953 | \n", "-3.114839 | \n", "-4.208912 | \n", "-2.098067 | \n", "-3.920546 | \n", "-4.175481 | \n", "
| annotated_data/mp3_Files/Recording_4/Recording_4_Segment_06.mp3 | \n", "18.0 | \n", "21.0 | \n", "3.195024 | \n", "6.508092 | \n", "-6.060542 | \n", "-5.502892 | \n", "-3.900456 | \n", "-3.240862 | \n", "-5.377626 | \n", "
| annotated_data/mp3_Files/Recording_1/Recording_1_Segment_02.mp3 | \n", "36.0 | \n", "39.0 | \n", "-5.511728 | \n", "-3.187492 | \n", "-6.659735 | \n", "-6.191207 | \n", "-6.031331 | \n", "-5.297669 | \n", "-6.563343 | \n", "
| ... | \n", "... | \n", "... | \n", "... | \n", "... | \n", "... | \n", "... | \n", "... | \n", "... | \n", "... | \n", "
| annotated_data/mp3_Files/Recording_4/Recording_4_Segment_05.mp3 | \n", "267.0 | \n", "270.0 | \n", "5.829832 | \n", "2.170767 | \n", "-3.095157 | \n", "-4.235296 | \n", "-3.209671 | \n", "-1.694019 | \n", "-3.902274 | \n", "
| annotated_data/mp3_Files/Recording_4/Recording_4_Segment_21.mp3 | \n", "141.0 | \n", "144.0 | \n", "6.042611 | \n", "3.894333 | \n", "-3.956448 | \n", "-4.595656 | \n", "-2.281978 | \n", "-2.939838 | \n", "-4.280013 | \n", "
| annotated_data/mp3_Files/Recording_1/Recording_1_Segment_23.mp3 | \n", "183.0 | \n", "186.0 | \n", "-3.594249 | \n", "-1.777073 | \n", "-5.218874 | \n", "-4.250111 | \n", "-2.707364 | \n", "-4.353728 | \n", "-5.437796 | \n", "
| annotated_data/mp3_Files/Recording_1/Recording_1_Segment_25.mp3 | \n", "144.0 | \n", "147.0 | \n", "-3.061894 | \n", "-0.626145 | \n", "-4.435275 | \n", "-2.705727 | \n", "0.509345 | \n", "7.063011 | \n", "-5.337906 | \n", "
| annotated_data/mp3_Files/Recording_2/Recording_2_Segment_14.mp3 | \n", "159.0 | \n", "162.0 | \n", "-2.488947 | \n", "-0.996913 | \n", "-0.150189 | \n", "-3.829111 | \n", "-3.008179 | \n", "4.803464 | \n", "-3.589157 | \n", "
1540 rows × 7 columns
\n", "