{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":19596,"databundleVersionId":1292430,"sourceType":"competition"},{"sourceId":1262046,"sourceType":"datasetVersion","datasetId":726424},{"sourceId":1264575,"sourceType":"datasetVersion","datasetId":725893}],"dockerImageVersionId":30635,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-01-13T08:32:48.942439Z","iopub.execute_input":"2024-01-13T08:32:48.943286Z","iopub.status.idle":"2024-01-13T08:33:00.619062Z","shell.execute_reply.started":"2024-01-13T08:32:48.943247Z","shell.execute_reply":"2024-01-13T08:33:00.618197Z"},"collapsed":true,"jupyter":{"outputs_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import librosa\nimport librosa.display\nimport soundfile as sf\nimport matplotlib.pyplot as plt\nimport IPython.display as ipd\nimport numpy as np\nimport matplotlib.pyplot as plt","metadata":{"execution":{"iopub.status.busy":"2024-01-13T08:33:17.588018Z","iopub.execute_input":"2024-01-13T08:33:17.588450Z","iopub.status.idle":"2024-01-13T08:33:17.594799Z","shell.execute_reply.started":"2024-01-13T08:33:17.588396Z","shell.execute_reply":"2024-01-13T08:33:17.593384Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"audio=[]\nsample=[]","metadata":{"execution":{"iopub.status.busy":"2024-01-13T08:33:30.616479Z","iopub.execute_input":"2024-01-13T08:33:30.616884Z","iopub.status.idle":"2024-01-13T08:33:30.622391Z","shell.execute_reply.started":"2024-01-13T08:33:30.616850Z","shell.execute_reply":"2024-01-13T08:33:30.620907Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#aldfly\na1_1,sr1_1 = librosa.load(\"/kaggle/input/birdsong-recognition/train_audio/aldfly/XC135454.mp3\")\na1_2,sr1_2 = librosa.load(\"/kaggle/input/birdsong-recognition/train_audio/aldfly/XC135455.mp3\")\naudio.append(a1_1)\nsample.append(sr1_1)\naudio.append(a1_2)\nsample.append(sr1_2)\n\n#ameavo\na1_3,sr1_3 = librosa.load(\"/kaggle/input/birdsong-recognition/train_audio/ameavo/XC133080.mp3\")\na1_4,sr1_4 = librosa.load(\"/kaggle/input/birdsong-recognition/train_audio/ameavo/XC139829.mp3\")\naudio.append(a1_3)\nsample.append(sr1_3)\naudio.append(a1_4)\nsample.append(sr1_4)\n#barswa\na1_5,sr1_5 = librosa.load(\"/kaggle/input/birdsong-recognition/train_audio/barswa/XC134349.mp3\")\na2_1,sr2_1 = librosa.load(\"/kaggle/input/birdsong-recognition/train_audio/barswa/XC139171.mp3\")\naudio.append(a1_5)\nsample.append(sr1_5)\naudio.append(a2_1)\nsample.append(sr2_1)\n#balori\na2_2,sr2_2 = librosa.load(\"/kaggle/input/birdsong-recognition/train_audio/balori/XC101614.mp3\")\na2_3,sr2_3 = librosa.load(\"/kaggle/input/birdsong-recognition/train_audio/balori/XC11476.mp3\")\naudio.append(a2_2)\nsample.append(sr2_2)\naudio.append(a2_3)\nsample.append(sr2_3)\n#ampeip\na2_4,sr2_4 = librosa.load(\"/kaggle/input/birdsong-recognition/train_audio/amepip/XC111043.mp3\")\na2_5,sr2_5 = librosa.load(\"/kaggle/input/birdsong-recognition/train_audio/amepip/XC113721.mp3\")\naudio.append(a2_4)\nsample.append(sr2_4)\naudio.append(a2_5)\nsample.append(sr2_5)","metadata":{"execution":{"iopub.status.busy":"2024-01-13T08:33:39.389127Z","iopub.execute_input":"2024-01-13T08:33:39.389537Z","iopub.status.idle":"2024-01-13T08:33:53.252285Z","shell.execute_reply.started":"2024-01-13T08:33:39.389504Z","shell.execute_reply":"2024-01-13T08:33:53.251097Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for a, sr in zip(audio, sample):\n    ipd.display(ipd.Audio(data=a, rate=sr))","metadata":{"execution":{"iopub.status.busy":"2024-01-13T08:34:11.866685Z","iopub.execute_input":"2024-01-13T08:34:11.867227Z","iopub.status.idle":"2024-01-13T08:34:12.242150Z","shell.execute_reply.started":"2024-01-13T08:34:11.867195Z","shell.execute_reply":"2024-01-13T08:34:12.240565Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"bird_names = [\"ALDFLY\", \"ALDFLY\", \"AMEAVO\", \"AMEAVO\", \"BARSWA\", \"BARSWA\", \"BALORI\", \"BALORI\", \"AMEPIP\", \"AMEPIP\"]\nplt.figure(figsize=(20, 12))\n\n\nfor i, (audio, sr, bird_name) in enumerate(zip(audio, sample, bird_names), start=1):\n    \n    subplot_index = i\n    plt.subplot(2, 5, subplot_index)\n    librosa.display.waveshow(audio, sr=sr)\n\n    plt.title(bird_name)\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-01-13T08:34:19.012659Z","iopub.execute_input":"2024-01-13T08:34:19.013133Z","iopub.status.idle":"2024-01-13T08:34:32.517826Z","shell.execute_reply.started":"2024-01-13T08:34:19.013096Z","shell.execute_reply":"2024-01-13T08:34:32.516589Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"audio","metadata":{"execution":{"iopub.status.busy":"2024-01-13T08:34:36.166271Z","iopub.execute_input":"2024-01-13T08:34:36.167360Z","iopub.status.idle":"2024-01-13T08:34:36.175985Z","shell.execute_reply.started":"2024-01-13T08:34:36.167308Z","shell.execute_reply":"2024-01-13T08:34:36.174713Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(20,30))\nspec1 = librosa.amplitude_to_db(np.abs(librosa.stft(a1_1)), ref=np.max)\nplt.subplot(5,2,1)\nlibrosa.display.specshow(spec1, sr=sr1_1, x_axis='time', y_axis='log')\nplt.colorbar(format='%+2.0f dB')\nplt.title(\"ALDFLY\")\n\nspec1 = librosa.amplitude_to_db(np.abs(librosa.stft(a1_2)), ref=np.max)\nplt.subplot(5,2,2)\nlibrosa.display.specshow(spec1, sr=sr1_2, x_axis='time', y_axis='log')\nplt.colorbar(format='%+2.0f dB')\nplt.title(\"ALDFLY\")\n\nspec1 = librosa.amplitude_to_db(np.abs(librosa.stft(a1_3)), ref=np.max)\nplt.subplot(5,2,3)\nlibrosa.display.specshow(spec1, sr=sr1_3, x_axis='time', y_axis='log')\nplt.colorbar(format='%+2.0f dB')\nplt.title(\"AMEAVO\")\n\nspec1 = librosa.amplitude_to_db(np.abs(librosa.stft(a1_4)), ref=np.max)\nplt.subplot(5,2,4)\nlibrosa.display.specshow(spec1, sr=sr1_4, x_axis='time', y_axis='log')\nplt.colorbar(format='%+2.0f dB')\nplt.title(\"AMEAVO\")\n\nspec1 = librosa.amplitude_to_db(np.abs(librosa.stft(a1_5)), ref=np.max)\nplt.subplot(5,2,5)\nlibrosa.display.specshow(spec1, sr=sr1_5, x_axis='time', y_axis='log')\nplt.colorbar(format='%+2.0f dB')\nplt.title(\"BARSWA\")\n\nspec2 = librosa.amplitude_to_db(np.abs(librosa.stft(a2_1)), ref=np.max)\nplt.subplot(5,2,6)\nlibrosa.display.specshow(spec2, sr=sr2_1, x_axis='time', y_axis='log')\nplt.colorbar(format='%+2.0f dB')\nplt.title(\"BARSWA\")\n\n\nspec2 = librosa.amplitude_to_db(np.abs(librosa.stft(a2_2)), ref=np.max)\nplt.subplot(5,2,7)\nlibrosa.display.specshow(spec2, sr=sr2_2, x_axis='time', y_axis='log')\nplt.colorbar(format='%+2.0f dB')\nplt.title(\"BALORI\")\n\n\nspec2 = librosa.amplitude_to_db(np.abs(librosa.stft(a2_3)), ref=np.max)\nplt.subplot(5,2,8)\nlibrosa.display.specshow(spec2, sr=sr2_3, x_axis='time', y_axis='log')\nplt.colorbar(format='%+2.0f dB')\nplt.title(\"BALORI\")\n\n\nspec2 = librosa.amplitude_to_db(np.abs(librosa.stft(a2_4)), ref=np.max)\nplt.subplot(5,2,9)\nlibrosa.display.specshow(spec2, sr=sr2_4, x_axis='time', y_axis='log')\nplt.colorbar(format='%+2.0f dB')\nplt.title(\"AMEPIP\")\n\n\nspec2 = librosa.amplitude_to_db(np.abs(librosa.stft(a2_5)), ref=np.max)\nplt.subplot(5,2,10)\nlibrosa.display.specshow(spec2, sr=sr2_5, x_axis='time', y_axis='log')\nplt.colorbar(format='%+2.0f dB')\nplt.title(\"AMEPIP\")\n\n","metadata":{"execution":{"iopub.status.busy":"2024-01-13T08:36:06.253555Z","iopub.execute_input":"2024-01-13T08:36:06.253961Z","iopub.status.idle":"2024-01-13T08:36:27.785200Z","shell.execute_reply.started":"2024-01-13T08:36:06.253919Z","shell.execute_reply":"2024-01-13T08:36:27.782773Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**MFCC**","metadata":{}},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport librosa.display\n\nplt.figure(figsize=(20,15))\n\nmfcc1 = librosa.feature.mfcc(y=a1_1, sr=sr1_1)\nplt.subplot(3, 2, 1)\nlibrosa.display.specshow(mfcc1)\nplt.title('MFCC for a1_1')\nplt.ylabel('MFCC')\nplt.xlabel('Time')\nplt.colorbar()\n\nmfcc2 = librosa.feature.mfcc(y=a1_2, sr=sr1_2)\nplt.subplot(3, 2, 2)\nlibrosa.display.specshow(mfcc2)\nplt.title('MFCC for a1_2')\nplt.ylabel('MFCC')\nplt.xlabel('Time')\nplt.colorbar()\n\nmfcc3 = librosa.feature.mfcc(y=a2_1, sr=sr2_1)\nplt.subplot(3, 2, 3)\nlibrosa.display.specshow(mfcc2)\nplt.title('MFCC for a2_1')\nplt.ylabel('MFCC')\nplt.xlabel('Time')\nplt.colorbar()\n\nmfcc4 = librosa.feature.mfcc(y=a2_2, sr=sr2_2)\nplt.subplot(3, 2, 4)\nlibrosa.display.specshow(mfcc4)\nplt.title('MFCC for a2_2')\nplt.ylabel('MFCC')\nplt.xlabel('Time')\nplt.colorbar()\n\nmfcc5 = librosa.feature.mfcc(y=a1_3, sr=sr1_3)\nplt.subplot(3, 2, 5)\nlibrosa.display.specshow(mfcc5)\nplt.title('MFCC for a1_3')\nplt.ylabel('MFCC')\nplt.xlabel('Time')\nplt.colorbar()\n\nmfcc6 = librosa.feature.mfcc(y=a2_3, sr=sr2_3)\nplt.subplot(3, 2, 6)\nlibrosa.display.specshow(mfcc6)\nplt.title('MFCC for a2_3')\nplt.ylabel('MFCC')\nplt.xlabel('Time')\nplt.colorbar()\n\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-01-13T08:36:48.758080Z","iopub.execute_input":"2024-01-13T08:36:48.758561Z","iopub.status.idle":"2024-01-13T08:36:52.516008Z","shell.execute_reply.started":"2024-01-13T08:36:48.758519Z","shell.execute_reply":"2024-01-13T08:36:52.514746Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**MFCC PLOTS**","metadata":{}},{"cell_type":"code","source":"import numpy as np\n\n\nplt.figure(figsize=(10, 20))\n\nplt.subplot(6, 1, 1)\nfor i in range(mfcc1.shape[0]):\n    plt.plot(mfcc1[i], label=f'MFCC {i+1}')\nplt.title('MFCC for a1_1')\n\n\nplt.subplot(6, 1, 2)\nfor i in range(mfcc2.shape[0]):\n    plt.plot(mfcc2[i], label=f'MFCC {i+1}')\nplt.title('MFCC for a1_2')\n\n\nplt.subplot(6, 1, 3)\nfor i in range(mfcc5.shape[0]):\n    plt.plot(mfcc5[i], label=f'MFCC {i+1}')\nplt.title('MFCC for a1_3')\n\n\n\nplt.subplot(6, 1, 4)\nfor i in range(mfcc3.shape[0]):\n    plt.plot(mfcc3[i], label=f'MFCC {i+1}')\nplt.title('MFCC for a2_1')\n\n\nplt.subplot(6, 1, 5)\nfor i in range(mfcc4.shape[0]):\n    plt.plot(mfcc4[i], label=f'MFCC {i+1}')\nplt.title('MFCC for a2_2')\n\n\nplt.subplot(6, 1, 6)\nfor i in range(mfcc6.shape[0]):\n    plt.plot(mfcc6[i], label=f'MFCC {i+1}')\nplt.title('MFCC for a2_3')\n\n\nplt.tight_layout()\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-01-13T08:37:25.352396Z","iopub.execute_input":"2024-01-13T08:37:25.352810Z","iopub.status.idle":"2024-01-13T08:37:27.398666Z","shell.execute_reply.started":"2024-01-13T08:37:25.352778Z","shell.execute_reply":"2024-01-13T08:37:27.397192Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"n0 = 1\nn1 = 10\nplt.figure(figsize=(20, 30))\nplt.subplot(5,2,1)\nzcr7_1 = librosa.feature.zero_crossing_rate(a1_1)\nzcr7_2 = librosa.feature.zero_crossing_rate(a1_2)\nplt.plot(a1_1[n0:n1], label='aldfly')\nplt.plot(a1_2[n0:n1], label='aldfly')\nplt.title(\"ZCR Comparision\")\nplt.legend()\nplt.grid()\n\n\nplt.subplot(5,2,2)\nzcr7_1 = librosa.feature.zero_crossing_rate(a1_3)\nzcr7_2 = librosa.feature.zero_crossing_rate(a1_4)\nplt.plot(a1_3[n0:n1], label='ameavo')\nplt.plot(a1_4[n0:n1], label='ameavo')\nplt.title(\"ZCR Comparision\")\nplt.legend()\nplt.grid()\n\nplt.subplot(5,2,3)\nzcr7_1 = librosa.feature.zero_crossing_rate(a1_5)\nzcr7_2 = librosa.feature.zero_crossing_rate(a2_1)\nplt.plot(a1_5[n0:n1], label='barswa')\nplt.plot(a2_1[n0:n1], label='barswa')\nplt.title(\"ZCR Comparision\")\nplt.legend()\nplt.grid()\n\nplt.subplot(5,2,4)\nzcr7_1 = librosa.feature.zero_crossing_rate(a2_2)\nzcr7_2 = librosa.feature.zero_crossing_rate(a2_3)\nplt.plot(a2_2[n0:n1], label='balori')\nplt.plot(a2_3[n0:n1], label='balori')\nplt.title(\"ZCR Comparision\")\nplt.legend()\nplt.grid()\n\nplt.subplot(5,2,5)\nzcr7_1 = librosa.feature.zero_crossing_rate(a1_1)\nzcr7_2 = librosa.feature.zero_crossing_rate(a1_2)\nplt.plot(a2_4[n0:n1], label='amepip')\nplt.plot(a2_5[n0:n1], label='amepip')\nplt.title(\"ZCR Comparision\")\nplt.legend()\nplt.grid()","metadata":{"execution":{"iopub.status.busy":"2024-01-13T08:46:24.337193Z","iopub.execute_input":"2024-01-13T08:46:24.337607Z","iopub.status.idle":"2024-01-13T08:46:26.240353Z","shell.execute_reply.started":"2024-01-13T08:46:24.337574Z","shell.execute_reply":"2024-01-13T08:46:26.239470Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import cv2\nimport audioread\nimport logging\nimport os\nimport random\nimport time\nimport warnings\nimport librosa\nimport numpy as np\nimport pandas as pd\nimport soundfile as sf\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.utils.data as data\nfrom contextlib import contextmanager\nfrom pathlib import Path\nfrom typing import Optional\nfrom fastprogress import progress_bar\nfrom sklearn.metrics import f1_score\nfrom torchvision import models","metadata":{"execution":{"iopub.status.busy":"2024-01-13T09:49:18.606419Z","iopub.execute_input":"2024-01-13T09:49:18.607054Z","iopub.status.idle":"2024-01-13T09:49:18.616683Z","shell.execute_reply.started":"2024-01-13T09:49:18.607017Z","shell.execute_reply":"2024-01-13T09:49:18.615583Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def set_seed(seed: int=42):\n        random.seed(seed)\n        np.random.seed(seed)\n        os.environ[\"PYTHONHASHSEED\"]=str(seed)\n        torch.manual_seed(seed)\n        torch.cuda.manual_seed(seed)\n        torch.backends.cudnn.deterministic = True\n        torch.backends.cudnn.benchmark= True","metadata":{"execution":{"iopub.status.busy":"2024-01-13T09:49:21.914966Z","iopub.execute_input":"2024-01-13T09:49:21.915407Z","iopub.status.idle":"2024-01-13T09:49:21.921400Z","shell.execute_reply.started":"2024-01-13T09:49:21.915363Z","shell.execute_reply":"2024-01-13T09:49:21.920549Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_logger(out_file=None):\n    logger= logging.getLogger()\n    formatter= logging.Formatter(\"%(asctime)s - %(levelname)s - %(message)s\")\n    logger.handlers = []\n    logger.setLevel(logging.INFO)\n    \n    handler = logging.StreamHandler()\n    handler.setFormatter(formatter)\n    handler.setLevel(logging.INFO)\n    logger.addHandler(handler)\n    \n    if out_file is not None:\n        fh= logging.FileHandler(out_file)\n        fh.setFormatter(formatter)\n        fh.setLevel(logging.INFO)\n        logger.addHandler(fh)\n    logger.info(\"logger set up\")\n    return logger\ndef get_logger(out_file=None):\n    logger= logging.getLogger()\n    formatter= logging.Formatter(\"%(asctime)s - %(levelname)s - %(message)s\")\n    logger.handlers = []\n    logger.setLevel(logging.INFO)\n    \n    handler = logging.StreamHandler()\n    handler.setFormatter(formatter)\n    handler.setLevel(logging.INFO)\n    logger.addHandler(handler)\n    \n    if out_file is not None:\n        fh= logging.FileHandler(out_file)\n        fh.setFormatter(formatter)\n        fh.setLevel(logging.INFO)\n        logger.addHandler(fh)\n    logger.info(\"logger set up\")\n    return logger\n\n@contextmanager #measure execution time\ndef timer(name: str, logger: Optional[logging.Logger]= None):\n    t0= time.time()\n    msg= f\"[{name}] start\"\n    if logger is None:\n        print(msg)\n    else:\n        logger.info(msg)    \n    yield\n    \n    msg=f\"[{name}] done in {time.time() - t0:.2f} s\"\n    if logger is None:\n        print(msg)\n    else:\n        logger.info(msg)   \n","metadata":{"execution":{"iopub.status.busy":"2024-01-13T09:49:50.997293Z","iopub.execute_input":"2024-01-13T09:49:50.997710Z","iopub.status.idle":"2024-01-13T09:49:51.011345Z","shell.execute_reply.started":"2024-01-13T09:49:50.997678Z","shell.execute_reply":"2024-01-13T09:49:51.009952Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"logger =get_logger(\"main.log\")\nset_seed(1213)","metadata":{"execution":{"iopub.status.busy":"2024-01-13T09:50:02.596083Z","iopub.execute_input":"2024-01-13T09:50:02.596544Z","iopub.status.idle":"2024-01-13T09:50:02.609654Z","shell.execute_reply.started":"2024-01-13T09:50:02.596506Z","shell.execute_reply":"2024-01-13T09:50:02.608286Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"TARGET_SR=32000\ntest=pd.read_csv(\"/kaggle/input/birdcall-check/test.csv\")\ntest_audio = \"/kaggle/input/birdcall-check/test_audio\"\ntest.head()","metadata":{"execution":{"iopub.status.busy":"2024-01-13T09:50:20.859101Z","iopub.execute_input":"2024-01-13T09:50:20.859541Z","iopub.status.idle":"2024-01-13T09:50:20.903151Z","shell.execute_reply.started":"2024-01-13T09:50:20.859506Z","shell.execute_reply":"2024-01-13T09:50:20.902339Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class ResNet(nn.Module): #base class\n    def __init__(self, base_model_name: str, pretrained=False, #constructor #weights \n                 num_classes=264): #constructor method\n        super().__init__()\n        base_model = models.__getattribute__(base_model_name)(\n              pretrained=pretrained)\n        layers= list(base_model.children())[:-2]\n        layers.append(nn.AdaptiveMaxPool2d(1))\n        self.encoder = nn.Sequential(*layers)\n        \n        in_features=base_model.fc.in_features  #number of input features\n        \n        self.classifier = nn.Sequential(\n          nn.Linear(in_features,1024), nn.ReLU(), nn.Dropout(p=0.2),\n          nn.Linear(1024,1024), nn.ReLU(), nn.Dropout(p=0.2),\n          nn.Linear(1024, num_classes))\n    def forward(self,x):\n        batch_size= x.size(0)\n        x= self.encoder(x).view(batch_size, -1)\n        x= self.classifier(x)\n        multiclass_proba = F.softmax(x, dim=1)\n        multilabel_proba = F.sigmoid(x)\n        \n        return {\n            \"logits\":x,\n            \"multiclass_proba\": multiclass_proba,\n            \"multilabel_proba\": multilabel_proba\n        }    ","metadata":{"execution":{"iopub.status.busy":"2024-01-13T09:50:34.483179Z","iopub.execute_input":"2024-01-13T09:50:34.483567Z","iopub.status.idle":"2024-01-13T09:50:34.494138Z","shell.execute_reply.started":"2024-01-13T09:50:34.483538Z","shell.execute_reply":"2024-01-13T09:50:34.492906Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_config ={\n    \"base_model_name\": \"resnet50\",\n    \"pretrained\": False,\n    \"num_classes\": 264   \n}\n\nmelspectrogram_parameters ={\n    \"n_mels\": 128,\n    \"fmin\": 0,\n    \"fmax\":12000\n}\nimport os\n\nweights_path = '/kaggle/input/birdcall-resnet50-init-weights/best.pth'","metadata":{"execution":{"iopub.status.busy":"2024-01-13T09:51:08.644123Z","iopub.execute_input":"2024-01-13T09:51:08.644562Z","iopub.status.idle":"2024-01-13T09:51:08.651165Z","shell.execute_reply.started":"2024-01-13T09:51:08.644528Z","shell.execute_reply":"2024-01-13T09:51:08.649913Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def mono_to_color(X:np.ndarray,mean=None,std=None,norm_max=None,norm_min= None,eps=1e-6):\n    X=np.stack([X,X,X],axis=-1)\n    \n    mean = mean or X.mean()\n    X=X-mean\n    std=std or X.std()\n    Xstd= X/(std+eps)\n    \n    _min,_max= Xstd.min(),Xstd.max()\n    norm_max= norm_max or _max\n    norm_min= norm_min or _min\n    \n    if(_max - _min)>eps:\n        V=Xstd\n        V[V<norm_min]=norm_min\n        V[V>norm_max]=norm_max\n        \n        V=255*(V-norm_min)/(norm_max - norm_min)\n        V=V.astype(np.uint8)\n    else:\n        V=np.zeroes_like(Xstd, dtype=np.uint8)\n    return V\nclass TestDataset(data.Dataset):\n    def __init__(self,df:pd.DataFrame, clip:np.array,img_size=224,melspectrogram_parameters={}):\n        self.df=df\n        self.clip=clip\n        self.img_size= img_size\n        self.melspectrogram_parameters = melspectrogram_parameters\n        \n    def __len__(self):\n        return len(self.df)\n    \n    def __getitem__(self, idx: int):\n        SR = 32000\n\n        sample = self.df.loc[idx, :]  # return row\n        site = sample.site\n        row_id = sample.row_id\n\n        if site == \"site_3\":\n            y = self.clip.astype(np.float32)\n            len_y = len(y)\n            start = 0\n            end = SR * 5\n\n            images = []\n            while len_y > start:\n                y_batch = y[start:end].astype(np.float32)\n\n                if len(y_batch) != (SR * 5):\n                    break\n                start = end\n                end = end + SR * 5\n\n                melspec = librosa.feature.melspectrogram(y=y_batch, sr=SR, **self.melspectrogram_parameters)\n                melspec = librosa.power_to_db(melspec).astype(np.float32)\n\n                image = mono_to_color(melspec)\n\n                height, width, _ =image.shape\n\n                image = cv2.resize(image, (int(width * self.img_size / height), self.img_size))\n\n                image = np.moveaxis(image, 2, 0)  # color channel axis to the first dimension\n\n                image = (image / 255.0).astype(np.float32)\n                images.append(image)\n\n            images = np.asarray(images)\n\n            return images, row_id, site\n\n        else:\n\n            end_seconds = int(sample.seconds)\n            start_seconds = int(end_seconds - 5)\n            start_index = SR * start_seconds\n            end_index = SR * end_seconds\n\n            y = self.clip[start_index:end_index].astype(np.float32)\n\n            melspec = librosa.feature.melspectrogram(y=y, sr=SR, **self.melspectrogram_parameters)\n\n            melspec = librosa.power_to_db(melspec).astype(np.float32)\n\n            image = mono_to_color(melspec)\n            height, width, _ =image.shape\n            image = cv2.resize(image,(int(width * self.img_size / height),self.img_size))\n            image = np.moveaxis(image, 2, 0)\n            image = (image / 255.0).astype(np.float32)\n            \n            return image, row_id, site\n        ","metadata":{"execution":{"iopub.status.busy":"2024-01-13T09:53:54.660540Z","iopub.execute_input":"2024-01-13T09:53:54.661049Z","iopub.status.idle":"2024-01-13T09:53:54.683591Z","shell.execute_reply.started":"2024-01-13T09:53:54.660985Z","shell.execute_reply":"2024-01-13T09:53:54.682775Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_model(config: dict, weights_path: str):\n    model = ResNet(**config)\n\n    # Load the checkpoint and map the tensors to the CPU if CUDA is not available\n    device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n    checkpoint = torch.load(weights_path, map_location=device)\n\n    # Load the model's learned parameters\n    model.load_state_dict(checkpoint[\"model_state_dict\"])\n\n    # Move the model to the specified device\n    model.to(device)\n\n    # Set the model to evaluation mode\n    model.eval()\n\n    return model","metadata":{"execution":{"iopub.status.busy":"2024-01-13T09:54:16.414725Z","iopub.execute_input":"2024-01-13T09:54:16.415239Z","iopub.status.idle":"2024-01-13T09:54:16.422424Z","shell.execute_reply.started":"2024-01-13T09:54:16.415200Z","shell.execute_reply":"2024-01-13T09:54:16.421284Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def prediction_for_clip(test_df: pd.DataFrame,\n                        clip: np.ndarray,\n                        model: ResNet,\n                        mel_params: dict,\n                        threshold=0.5):\n\n\n    dataset = TestDataset(df=test_df,\n                          clip=clip,\n                          img_size=224,\n                          melspectrogram_parameters=mel_params)\n\n    loader = data.DataLoader(dataset, batch_size=1, shuffle=False)\n\n    device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n    model.eval()\n\n    prediction_dict = {}\n\n    for image, row_id, site in progress_bar(loader):\n        site = site[0]\n        row_id = row_id[0]\n        if site in {\"site_1\", \"site_2\"}:\n            image = image.to(device)\n\n            with torch.no_grad():\n                prediction = model(image)\n                proba = prediction[\"multilabel_proba\"].detach().cpu().numpy().reshape(-1)\n                \n            events = proba >= threshold\n            labels = np.argwhere(events).reshape(-1).tolist()\n            \n        else:\n    # to avoid prediction on large batch\n            image = image.squeeze(0)\n            batch_size = 16\n            whole_size = image.size(0)\n\n            if whole_size % batch_size == 0:\n                n_iter = whole_size // batch_size\n            else:\n                n_iter = whole_size // batch_size + 1\n\n            all_events = set()\n\n            for batch_i in range(n_iter):\n                batch = image[batch_i * batch_size: (batch_i + 1) * batch_size]\n\n                if batch.ndim == 3:\n                    batch = batch.unsqueeze(0)\n                    \n                batch = batch.to(device)\n                with torch.no_grad():\n                    prediction = model(batch)\n\n                    proba = prediction[\"multilabel_proba\"].detach().cpu().numpy()\n                events = proba >= threshold\n\n                for i in range(len(events)):\n                    event = events[i, :]\n                    labels = np.argwhere(event).reshape(-1).tolist()\n\n                    for label in labels:\n                        all_events.add(label)\n\n            labels=list(all_events)\n            \n        if len(labels)==0:\n            prediction_dict[row_id]=\"nocall\"\n        else:\n            labels_str_list=list(map(lambda x: INV_BIRD_CODE[x], labels))\n            label_string=\" \".join(labels_str_list)\n            prediction_dict[row_id]= label_string\n            \n    return prediction_dict","metadata":{"execution":{"iopub.status.busy":"2024-01-13T09:56:45.380867Z","iopub.execute_input":"2024-01-13T09:56:45.381346Z","iopub.status.idle":"2024-01-13T09:56:45.400746Z","shell.execute_reply.started":"2024-01-13T09:56:45.381310Z","shell.execute_reply":"2024-01-13T09:56:45.399275Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def prediction(test_df: pd.DataFrame,\n              test_audio: Path,\n              model_config: dict,\n              mel_params: dict,\n              weights_path: str,\n              threshold=0.5):\n    \n    model = get_model(model_config, weights_path)\n    unique_audio_id = test_df.audio_id.unique()\n\n    warnings.filterwarnings(\"ignore\")\n\n    prediction_dfs = []\n\n    for audio_id in unique_audio_id:\n        with timer(f\"Loading {audio_id}\", logger):\n            clip, _ = librosa.load(test_audio + \"/\" + (audio_id + \".mp3\"),\n                                   sr=TARGET_SR,\n                                   mono=True,\n                                   res_type=\"scipy\")\n\n        test_df_for_audio_id = test_df.query(\n            f\"audio_id == '{audio_id}'\").reset_index(drop=True)\n        with timer(f\"Prediction on {audio_id}\", logger):\n            prediction_dict = prediction_for_clip(test_df_for_audio_id,\n                                                  clip=clip,\n                                                  model=model,\n                                                  mel_params=mel_params,\n                                                  threshold=threshold)\n        row_id = list(prediction_dict.keys())\n        birds = list(prediction_dict.values())\n\n        prediction_df = pd.DataFrame({\n           \"row_id\": row_id,\n           \"birds\": birds\n        })\n\n        prediction_dfs.append(prediction_df)\n\n    prediction_df = pd.concat(prediction_dfs, axis=0, sort=False).reset_index(drop=True)\n\n    return prediction_df\n","metadata":{"execution":{"iopub.status.busy":"2024-01-13T09:57:27.655928Z","iopub.execute_input":"2024-01-13T09:57:27.656342Z","iopub.status.idle":"2024-01-13T09:57:27.667342Z","shell.execute_reply.started":"2024-01-13T09:57:27.656309Z","shell.execute_reply":"2024-01-13T09:57:27.666157Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"BIRD_CODE = {\n    'aldfly': 0, 'ameavo': 1, 'amebit': 2, 'amecro': 3, 'amegfi': 4,\n    'amekes': 5, 'amepip': 6, 'amered': 7, 'amerob': 8, 'amewig': 9,\n    'amewoo': 10, 'amtspa': 11, 'annhum': 12, 'astfly': 13, 'baisan': 14,\n    'baleag': 15, 'balori': 16, 'banswa': 17, 'barswa': 18, 'bawwar': 19,\n    'belkin1': 20, 'belspa2': 21, 'bewwre': 22, 'bkbcuc': 23, 'bkbmag1': 24,\n    'bkbwar': 25, 'bkcchi': 26, 'bkchum': 27, 'bkhgro': 28, 'bkpwar': 29,\n    'bktspa': 30, 'blkpho': 31, 'blugrb1': 32, 'blujay': 33, 'bnhcow': 34,\n    'boboli': 35, 'bongul': 36, 'brdowl': 37, 'brebla': 38, 'brespa': 39,\n    'brncre': 40, 'brnthr': 41, 'brthum': 42, 'brwhaw': 43, 'btbwar': 44,\n    'btnwar': 45, 'btywar': 46, 'buffle': 47, 'buggna': 48, 'buhvir': 49,\n    'bulori': 50, 'bushti': 51, 'buwtea': 52, 'buwwar': 53, 'cacwre': 54,\n    'calgul': 55, 'calqua': 56, 'camwar': 57, 'cangoo': 58, 'canwar': 59,\n    'canwre': 60, 'carwre': 61, 'casfin': 62, 'caster1': 63, 'casvir': 64,\n    'cedwax': 65, 'chispa': 66, 'chiswi': 67, 'chswar': 68, 'chukar': 69,\n    'clanut': 70, 'cliswa': 71, 'comgol': 72, 'comgra': 73, 'comloo': 74,\n    'commer': 75, 'comnig': 76, 'comrav': 77, 'comred': 78, 'comter': 79,\n    'comyel': 80, 'coohaw': 81, 'coshum': 82, 'cowscj1': 83, 'daejun': 84,\n    'doccor': 85, 'dowwoo': 86, 'dusfly': 87, 'eargre': 88, 'easblu': 89,\n    'easkin': 90, 'easmea': 91, 'easpho': 92, 'eastow': 93, 'eawpew': 94,\n    'eucdov': 95, 'eursta': 96, 'evegro': 97, 'fiespa': 98, 'fiscro': 99,\n    'foxspa': 100, 'gadwal': 101, 'gcrfin': 102, 'gnttow': 103, 'gnwtea': 104,\n    'gockin': 105, 'gocspa': 106, 'goleag': 107, 'grbher3': 108, 'grcfly': 109,\n    'greegr': 110, 'greroa': 111, 'greyel': 112, 'grhowl': 113, 'grnher': 114,\n    'grtgra': 115, 'grycat': 116, 'gryfly': 117, 'haiwoo': 118, 'hamfly': 119,\n    'hergul': 120, 'herthr': 121, 'hoomer': 122, 'hoowar': 123, 'horgre': 124,\n    'horlar': 125, 'houfin': 126, 'houspa': 127, 'houwre': 128, 'indbun': 129,\n    'juntit1': 130, 'killde': 131, 'labwoo': 132, 'larspa': 133, 'lazbun': 134,\n    'leabit': 135, 'leafly': 136, 'leasan': 137, 'lecthr': 138, 'lesgol': 139,\n    'lesnig': 140, 'lesyel': 141, 'lewwoo': 142, 'linspa': 143, 'lobcur': 144,\n    'lobdow': 145, 'logshr': 146, 'lotduc': 147, 'louwat': 148, 'macwar': 149,\n    'magwar': 150, 'mallar3': 151, 'marwre': 152, 'merlin': 153, 'moublu': 154,\n    'mouchi': 155, 'moudov': 156, 'norcar': 157, 'norfli': 158, 'norhar2': 159,\n    'normoc': 160, 'norpar': 161, 'norpin': 162, 'norsho': 163, 'norwat': 164,\n    'nrwswa': 165, 'nutwoo': 166, 'olsfly': 167, 'orcwar': 168, 'osprey': 169,\n    'ovenbi1': 170, 'palwar': 171, 'pasfly': 172, 'pecsan': 173, 'perfal': 174,\n    'phaino': 175, 'pibgre': 176, 'pilwoo': 177, 'pingro': 178, 'pinjay': 179,\n    'pinsis': 180, 'pinwar': 181, 'plsvir': 182, 'prawar': 183, 'purfin': 184,\n    'pygnut': 185, 'rebmer': 186, 'rebnut': 187, 'rebsap': 188, 'rebwoo': 189,\n    'redcro': 190, 'redhea': 191, 'reevir1': 192, 'renpha': 193, 'reshaw': 194,\n    'rethaw': 195, 'rewbla': 196, 'ribgul': 197, 'rinduc': 198, 'robgro': 199,\n    'rocpig': 200, 'rocwre': 201, 'rthhum': 202, 'ruckin': 203, 'rudduc': 204,\n    'rufgro': 205, 'rufhum': 206, 'rusbla': 207, 'sagspa1': 208, 'sagthr': 209,\n    'savspa': 210, 'saypho': 211, 'scatan': 212, 'scoori': 213, 'semplo': 214,\n    'semsan': 215, 'sheowl': 216, 'shshaw': 217, 'snobun': 218, 'snogoo': 219,\n    'solsan': 220, 'sonspa': 221, 'sora': 222, 'sposan': 223, 'spotow': 224,\n    'stejay': 225, 'swahaw': 226, 'swaspa': 227, 'swathr': 228, 'treswa': 229,\n    'truswa': 230, 'tuftit': 231, 'tunswa': 232, 'veery': 233, 'vesspa': 234,\n    'vigswa': 235, 'warvir': 236, 'wesblu': 237, 'wesgre': 238, 'weskin': 239,\n    'wesmea': 240, 'wessan': 241, 'westan': 242, 'wewpew': 243, 'whbnut': 244,\n    'whcspa': 245, 'whfibi': 246, 'whtspa': 247, 'whtswi': 248, 'wilfly': 249,\n    'wilsni1': 250, 'wiltur': 251, 'winwre3': 252, 'wlswar': 253, 'wooduc': 254,\n    'wooscj2': 255, 'woothr': 256, 'y00475': 257, 'yebfly': 258, 'yebsap': 259,\n    'yehbla': 260, 'yelwar': 261, 'yerwar': 262, 'yetvir': 263\n}\n\nINV_BIRD_CODE = {v: k for k, v in BIRD_CODE.items()}","metadata":{"execution":{"iopub.status.busy":"2024-01-13T10:12:43.746100Z","iopub.execute_input":"2024-01-13T10:12:43.747306Z","iopub.status.idle":"2024-01-13T10:12:43.777452Z","shell.execute_reply.started":"2024-01-13T10:12:43.747248Z","shell.execute_reply":"2024-01-13T10:12:43.776228Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission = prediction(test_df=test,\n                        test_audio=test_audio,\n                        model_config=model_config,\n                        mel_params=melspectrogram_parameters,\n                        weights_path=weights_path,\n                        threshold=0.8)\n\nsubmission.to_csv(\"submission.csv\", index=False)","metadata":{"execution":{"iopub.status.busy":"2024-01-13T10:12:47.461322Z","iopub.execute_input":"2024-01-13T10:12:47.462055Z","iopub.status.idle":"2024-01-13T10:13:44.022942Z","shell.execute_reply.started":"2024-01-13T10:12:47.462019Z","shell.execute_reply":"2024-01-13T10:13:44.021863Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission","metadata":{"execution":{"iopub.status.busy":"2024-01-13T10:14:17.803762Z","iopub.execute_input":"2024-01-13T10:14:17.804235Z","iopub.status.idle":"2024-01-13T10:14:17.817308Z","shell.execute_reply.started":"2024-01-13T10:14:17.804198Z","shell.execute_reply":"2024-01-13T10:14:17.816339Z"},"trusted":true},"execution_count":null,"outputs":[]}]}