{"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":"gpu","dataSources":[{"sourceId":21669,"databundleVersionId":1692278,"sourceType":"competition"}],"dockerImageVersionId":30587,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import torch.nn as nn\nimport numpy as np\nimport torch\nimport librosa\nimport os\nimport torchvision\n\nfrom torch.utils.data import Dataset, DataLoader\nfrom sklearn.model_selection import KFold","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-12-06T14:02:24.880138Z","iopub.execute_input":"2023-12-06T14:02:24.881181Z","iopub.status.idle":"2023-12-06T14:02:24.886679Z","shell.execute_reply.started":"2023-12-06T14:02:24.881133Z","shell.execute_reply":"2023-12-06T14:02:24.885679Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"device = 'cuda:0' if torch.cuda.is_available() else 'cpu'\nprint(device)","metadata":{"execution":{"iopub.status.busy":"2023-12-06T14:02:24.888998Z","iopub.execute_input":"2023-12-06T14:02:24.889715Z","iopub.status.idle":"2023-12-06T14:02:24.898464Z","shell.execute_reply.started":"2023-12-06T14:02:24.889678Z","shell.execute_reply":"2023-12-06T14:02:24.897393Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from skimage.transform import resize\nfrom skimage.filters import gaussian\nfrom skimage.color import rgb2gray\nfrom skimage import exposure, util","metadata":{"execution":{"iopub.status.busy":"2023-12-06T14:02:24.899530Z","iopub.execute_input":"2023-12-06T14:02:24.899811Z","iopub.status.idle":"2023-12-06T14:02:24.907225Z","shell.execute_reply.started":"2023-12-06T14:02:24.899787Z","shell.execute_reply":"2023-12-06T14:02:24.906377Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def spec_to_image(spec):\n    spec = resize(spec, (224, 400))\n    spec_norm = (spec - spec.mean()) / (spec.std() + 1e-6)\n    spec_scaled = 255 * (spec_norm - spec_norm.min()) / (spec_norm.max() - spec_norm.min())\n    return np.asarray(spec_scaled.astype(np.uint8))","metadata":{"execution":{"iopub.status.busy":"2023-12-06T14:02:24.908537Z","iopub.execute_input":"2023-12-06T14:02:24.908804Z","iopub.status.idle":"2023-12-06T14:02:24.916542Z","shell.execute_reply.started":"2023-12-06T14:02:24.908777Z","shell.execute_reply":"2023-12-06T14:02:24.915684Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def addChannels(img):\n    return np.stack((img, img, img))","metadata":{"execution":{"iopub.status.busy":"2023-12-06T14:02:24.919151Z","iopub.execute_input":"2023-12-06T14:02:24.919416Z","iopub.status.idle":"2023-12-06T14:02:24.926189Z","shell.execute_reply.started":"2023-12-06T14:02:24.919393Z","shell.execute_reply":"2023-12-06T14:02:24.925208Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def addNoisy(img):\n    return addChannels(util.random_noise(img))","metadata":{"execution":{"iopub.status.busy":"2023-12-06T14:02:24.927368Z","iopub.execute_input":"2023-12-06T14:02:24.927904Z","iopub.status.idle":"2023-12-06T14:02:24.936788Z","shell.execute_reply.started":"2023-12-06T14:02:24.927879Z","shell.execute_reply":"2023-12-06T14:02:24.935695Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def contrast_stretching(img):\n    return addChannels(exposure.rescale_intensity(img))","metadata":{"execution":{"iopub.status.busy":"2023-12-06T14:02:24.937828Z","iopub.execute_input":"2023-12-06T14:02:24.938112Z","iopub.status.idle":"2023-12-06T14:02:24.949735Z","shell.execute_reply.started":"2023-12-06T14:02:24.938090Z","shell.execute_reply":"2023-12-06T14:02:24.948896Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def randomGaussian(img):\n    return addChannels(gaussian(img))","metadata":{"execution":{"iopub.status.busy":"2023-12-06T14:02:24.950748Z","iopub.execute_input":"2023-12-06T14:02:24.950992Z","iopub.status.idle":"2023-12-06T14:02:24.959987Z","shell.execute_reply.started":"2023-12-06T14:02:24.950970Z","shell.execute_reply":"2023-12-06T14:02:24.959041Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def grayScale(img):\n    return addChannels(rgb2gray(img))","metadata":{"execution":{"iopub.status.busy":"2023-12-06T14:02:24.960988Z","iopub.execute_input":"2023-12-06T14:02:24.961228Z","iopub.status.idle":"2023-12-06T14:02:24.970538Z","shell.execute_reply.started":"2023-12-06T14:02:24.961206Z","shell.execute_reply":"2023-12-06T14:02:24.969638Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def randomGamma(img):\n    return addChannels(exposure.adjust_gamma(img))","metadata":{"execution":{"iopub.status.busy":"2023-12-06T14:02:24.971486Z","iopub.execute_input":"2023-12-06T14:02:24.971716Z","iopub.status.idle":"2023-12-06T14:02:24.980160Z","shell.execute_reply.started":"2023-12-06T14:02:24.971696Z","shell.execute_reply":"2023-12-06T14:02:24.979172Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\n\nsr = 48000\nlength = 10 * sr\ndata = pd.read_csv(\"../input/rfcx-species-audio-detection/train_tp.csv\")\n\nfmin = sr / 2\nfmax = 0\nfor i in range(0, len(data)):\n    if fmin > float(data.iloc[i]['f_min']):\n        fmin = float(data.iloc[i]['f_min'])\n    if fmax < float(data.iloc[i]['f_max']):\n        fmax = float(data.iloc[i]['f_max'])\n        \nfmin = int(fmin * 0.9)\nfmax = int(fmax * 1.1)","metadata":{"execution":{"iopub.status.busy":"2023-12-06T14:02:24.981544Z","iopub.execute_input":"2023-12-06T14:02:24.981846Z","iopub.status.idle":"2023-12-06T14:02:25.146865Z","shell.execute_reply.started":"2023-12-06T14:02:24.981823Z","shell.execute_reply":"2023-12-06T14:02:25.145991Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\n\nlabel_list = []\ndata_list = []\naudio_data = {}\nfor i in range(0, len(data)):\n    recording_id = data.recording_id.values[i]\n    species_id = int(data.species_id.values[i])\n    data_list.append(recording_id)\n    label_list.append(species_id)\n\n    wav, sr = librosa.load('../input/rfcx-species-audio-detection/train/' + recording_id + '.flac', sr=None)\n    t_min = float(data.t_min.values[i]) * sr\n    t_max = float(data.t_max.values[i]) * sr\n    center = np.round((t_min + t_max) / 2)\n    beginning = center - length / 2\n    if beginning < 0:\n        beginning = 0\n    ending = beginning + length\n    if ending > len(wav):\n        ending = len(wav)\n        beginning = ending - length\n    slice = wav[int(beginning):int(ending)]\n    \n    spec=librosa.feature.melspectrogram(y=slice, sr=sr, fmin=fmin, fmax=fmax)\n    spec_db=librosa.power_to_db(spec, top_db=80)\n    \n    audio_data[recording_id] = spec_to_image(spec_db)","metadata":{"execution":{"iopub.status.busy":"2023-12-06T14:02:25.147866Z","iopub.execute_input":"2023-12-06T14:02:25.148116Z","iopub.status.idle":"2023-12-06T14:07:11.722443Z","shell.execute_reply.started":"2023-12-06T14:02:25.148095Z","shell.execute_reply":"2023-12-06T14:07:11.720944Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import copy\nfrom tqdm import tqdm\n\nlearning_rate = 1e-4\nepochs = 20\nloss_fn = nn.CrossEntropyLoss()\n\ndef train(model, loss_fn, train_loader, valid_loader, epochs, optimizer, scheduler):\n    best_model_wts = copy.deepcopy(model.state_dict())\n    best_acc = 0.0\n    train_losses = []\n    valid_losses = []\n    \n    for epoch in range(1,epochs+1):\n        model.train()\n        batch_losses=[]\n        for _, data in enumerate(tqdm(train_loader)):\n            x, y = data\n            optimizer.zero_grad()\n            x = x.to(device, dtype=torch.float32)\n            y = y.to(device, dtype=torch.long)\n            y_hat = model(x)\n            loss = loss_fn(y_hat, y)\n            loss.backward()\n            batch_losses.append(loss.item())\n            optimizer.step()\n        train_losses.append(batch_losses)\n\n        model.eval()\n        batch_losses=[]\n        trace_y = []\n        trace_yhat = []\n        \n        for _, data in enumerate(valid_loader):\n            x, y = data\n            x = x.to(device, dtype=torch.float32)\n            y = y.to(device, dtype=torch.long)\n            y_hat = model(x)\n            loss = loss_fn(y_hat, y)\n            trace_y.append(y.cpu().detach().numpy())\n            trace_yhat.append(y_hat.cpu().detach().numpy())      \n            batch_losses.append(loss.item())\n        valid_losses.append(batch_losses)\n        trace_y = np.concatenate(trace_y)\n        trace_yhat = np.concatenate(trace_yhat)\n        accuracy = np.mean(trace_yhat.argmax(axis=1)==trace_y)\n        \n        print(\"epoch = %d, val_accuracy = %.5f\" % (epoch, accuracy))\n\n        scheduler.step(np.mean(valid_losses[-1]))\n        if accuracy > best_acc:\n            best_acc = accuracy\n            best_model_wts = copy.deepcopy(model.state_dict())\n\n    model.load_state_dict(best_model_wts)\n    return model","metadata":{"execution":{"iopub.status.busy":"2023-12-06T14:07:11.724475Z","iopub.execute_input":"2023-12-06T14:07:11.725293Z","iopub.status.idle":"2023-12-06T14:07:11.753656Z","shell.execute_reply.started":"2023-12-06T14:07:11.725221Z","shell.execute_reply":"2023-12-06T14:07:11.752320Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import random\n\nclass RainforestAudioDataset(Dataset):\n    def __init__(self, X, y, is_train):\n        self.data = []\n        self.labels = []\n        self.augs = [addNoisy, contrast_stretching,randomGaussian,randomGamma,addChannels,addChannels]\n        self.is_train=is_train\n        for i in range(0, len(X)):\n            recording_id = X[i]\n            label = y[i]\n            mel_spec = audio_data[recording_id]\n            self.data.append(mel_spec)\n            self.labels.append(label)\n                \n    def __len__(self):\n        return len(self.data)\n\n    def __getitem__(self, idx):\n        if self.is_train:\n            data = random.choice(self.augs)(self.data[idx])\n        else:\n            data = addChannels(self.data[idx])\n        return data, self.labels[idx]","metadata":{"execution":{"iopub.status.busy":"2023-12-06T14:07:11.759415Z","iopub.execute_input":"2023-12-06T14:07:11.760230Z","iopub.status.idle":"2023-12-06T14:07:11.781601Z","shell.execute_reply.started":"2023-12-06T14:07:11.760180Z","shell.execute_reply":"2023-12-06T14:07:11.780180Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fold_num = 5\nskf = KFold(n_splits=fold_num, shuffle=True, random_state=32)\n\nfor fold_id, (train_index, val_index) in enumerate(skf.split(data_list, label_list)):\n    X_train = np.take(data_list, train_index)\n    y_train = np.take(label_list, train_index, axis = 0)\n    X_val = np.take(data_list, val_index)\n    y_val = np.take(label_list, val_index, axis = 0)\n\n    train_data = RainforestAudioDataset(X_train, y_train, True)\n    valid_data = RainforestAudioDataset(X_val, y_val, False)\n    train_loader = DataLoader(train_data, batch_size=8, shuffle=True, drop_last=True)\n    valid_loader = DataLoader(valid_data, batch_size=8, shuffle=True, drop_last=True)\n\n    model = torchvision.models.resnet34(weights=torchvision.models.ResNet34_Weights.DEFAULT)\n    model.fc = torch.nn.Linear(512, 24)\n    model.to(device);\n    \n    optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate)\n    scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'min', patience=3)\n    model = train(model, loss_fn, train_loader, valid_loader, epochs, optimizer, scheduler)\n    torch.save(model.state_dict(), \"./resnet_\" + str(fold_id) + \".pt\")\n    \n    del train_data, valid_data, train_loader, valid_loader, model, X_train, X_val, y_train, y_val","metadata":{"execution":{"iopub.status.busy":"2023-12-06T14:07:11.788591Z","iopub.execute_input":"2023-12-06T14:07:11.790257Z","iopub.status.idle":"2023-12-06T14:07:55.362792Z","shell.execute_reply.started":"2023-12-06T14:07:11.790204Z","shell.execute_reply":"2023-12-06T14:07:55.361811Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def load_test_file(f):\n    wav, sr = librosa.load('../input/rfcx-species-audio-detection/test/' + f, sr=None)\n\n    segments = len(wav) / length\n    segments = int(np.ceil(segments))\n    \n    mel_array = []\n    \n    for i in range(0, segments):\n        if (i + 1) * length > len(wav):\n            slice = wav[len(wav) - length:len(wav)]\n        else:\n            slice = wav[i * length:(i + 1) * length]\n        \n        spec=librosa.feature.melspectrogram(y=slice, sr=sr, fmin=fmin, fmax=fmax)\n        spec_db=librosa.power_to_db(spec,top_db=80)\n\n        img = spec_to_image(spec_db)\n        mel_spec = np.stack((img, img, img))\n        mel_array.append(mel_spec)\n    \n    return mel_array","metadata":{"execution":{"iopub.status.busy":"2023-12-06T14:07:55.364353Z","iopub.execute_input":"2023-12-06T14:07:55.364721Z","iopub.status.idle":"2023-12-06T14:07:55.374854Z","shell.execute_reply.started":"2023-12-06T14:07:55.364686Z","shell.execute_reply":"2023-12-06T14:07:55.373853Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"members = []\nfor i in range(fold_num):\n    model = torchvision.models.resnet34(weights=torchvision.models.ResNet34_Weights.DEFAULT)\n    model.fc = torch.nn.Linear(512, 24)\n    model.to(device);\n    model.load_state_dict(torch.load('./resnet_'+str(i)+'.pt'))\n    model.eval()\n    members.append(model)\n    \nos.remove('./resnet_0.pt') \nos.remove('./resnet_1.pt')\nos.remove('./resnet_2.pt') \nos.remove('./resnet_3.pt')\nos.remove('./resnet_4.pt')","metadata":{"execution":{"iopub.status.busy":"2023-12-06T14:07:55.375900Z","iopub.execute_input":"2023-12-06T14:07:55.376273Z","iopub.status.idle":"2023-12-06T14:07:57.678610Z","shell.execute_reply.started":"2023-12-06T14:07:55.376222Z","shell.execute_reply":"2023-12-06T14:07:57.677554Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import csv\n\nwith open('submission.csv', 'w', newline='') as csvfile:\n    submission_writer = csv.writer(csvfile, delimiter=',')\n    submission_writer.writerow(['recording_id','s0','s1','s2','s3','s4','s5','s6','s7','s8','s9','s10','s11',\n                               's12','s13','s14','s15','s16','s17','s18','s19','s20','s21','s22','s23'])\n    \n    test_files = os.listdir('../input/rfcx-species-audio-detection/test/')\n    print(len(test_files))\n    \n    for i in range(0, len(test_files)):\n        data = load_test_file(test_files[i])\n        data = torch.tensor(data)\n        data = data.float()\n        if torch.cuda.is_available():\n            data = data.cuda()\n\n        output_list = []\n        for m in members:\n            output = m(data)\n            maxed_output = torch.max(output, dim=0)[0]\n            maxed_output = maxed_output.cpu().detach()\n            output_list.append(maxed_output)\n        avg_maxed_output = torch.mean(torch.stack(output_list), dim=0)\n        \n        file_id = str.split(test_files[i], '.')[0]\n        write_array = [file_id]\n        \n        for out in avg_maxed_output:\n            write_array.append(out.item())\n    \n        submission_writer.writerow(write_array)","metadata":{"execution":{"iopub.status.busy":"2023-12-06T14:07:57.679868Z","iopub.execute_input":"2023-12-06T14:07:57.680210Z"},"trusted":true},"execution_count":null,"outputs":[]}]}