{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":21669,"databundleVersionId":1692278,"sourceType":"competition"}],"dockerImageVersionId":31089,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"## Import","metadata":{}},{"cell_type":"code","source":"!pip install torcheval","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-05T08:55:57.999932Z","iopub.execute_input":"2025-08-05T08:55:58.000515Z","iopub.status.idle":"2025-08-05T08:56:01.019039Z","shell.execute_reply.started":"2025-08-05T08:55:58.000491Z","shell.execute_reply":"2025-08-05T08:56:01.018085Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport os\nimport shutil\nimport csv\nimport librosa\nimport librosa.display\nimport random\nimport matplotlib.pyplot as plt\nimport IPython.display as ipd\nfrom PIL import Image\nimport soundfile as sf\nimport warnings\nimport torch\nimport torch.nn as nn\nfrom torch.optim import Adam\nfrom torch.utils.data import DataLoader\nfrom torcheval.metrics import MultilabelAccuracy\nfrom glob import glob\nimport keras\nfrom keras.preprocessing import image_dataset_from_directory\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, BatchNormalization, Input\nfrom keras.optimizers import Adam\nfrom keras.callbacks import EarlyStopping, ReduceLROnPlateau\nfrom sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay, multilabel_confusion_matrix, classification_report\nfrom sklearn.utils.class_weight import compute_class_weight\nfrom sklearn.model_selection import train_test_split","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-05T08:56:01.021175Z","iopub.execute_input":"2025-08-05T08:56:01.021444Z","iopub.status.idle":"2025-08-05T08:56:01.027820Z","shell.execute_reply.started":"2025-08-05T08:56:01.021419Z","shell.execute_reply":"2025-08-05T08:56:01.027160Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Beállítások","metadata":{}},{"cell_type":"code","source":"seed=100\nlength=10\nsr=48000\n#slice_length=length*sr\nimage_height=128\nimage_width=400\ndevice=torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nmetric=MultilabelAccuracy(threshold=0.5, criteria='hamming').to(device)\nbatch_size=16\nepochs=30\n\nsave='/kaggle/working/spectrograms'\nos.makedirs(save, exist_ok=True) # Kaggle-ben felesleges, amúgy is van working mappa","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-05T08:56:01.028525Z","iopub.execute_input":"2025-08-05T08:56:01.028719Z","iopub.status.idle":"2025-08-05T08:56:01.049058Z","shell.execute_reply.started":"2025-08-05T08:56:01.028704Z","shell.execute_reply":"2025-08-05T08:56:01.048500Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"warnings.filterwarnings(\"ignore\", category=UserWarning)\nwarnings.filterwarnings(\"ignore\", category=FutureWarning)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-05T08:56:01.050686Z","iopub.execute_input":"2025-08-05T08:56:01.050858Z","iopub.status.idle":"2025-08-05T08:56:01.066639Z","shell.execute_reply.started":"2025-08-05T08:56:01.050844Z","shell.execute_reply":"2025-08-05T08:56:01.066003Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Elérés","metadata":{}},{"cell_type":"code","source":"input='/kaggle/input/rfcx-species-audio-detection'\ntrain_path=os.path.join(input, 'train')\ntest_path=os.path.join(input, 'test')\nfp_csv=os.path.join(input, 'train_fp.csv')\ntp_csv=os.path.join(input, 'train_tp.csv')\ntp_df=pd.read_csv(tp_csv)\nfp_df=pd.read_csv(fp_csv)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-05T08:56:01.067218Z","iopub.execute_input":"2025-08-05T08:56:01.067424Z","iopub.status.idle":"2025-08-05T08:56:01.098580Z","shell.execute_reply.started":"2025-08-05T08:56:01.067408Z","shell.execute_reply":"2025-08-05T08:56:01.097781Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Random audio\n### Lejátszás","metadata":{}},{"cell_type":"code","source":"# flac_files=[f for f in os.listdir(train_path) if f.endswith('.flac')]\n# random_file=random.choice(flac_files)\n# random_file_path=os.path.join(train_path, random_file)\n# print(\"flac_files hossza: \", len(flac_files))\n# print('\\nHang: ', random_file)\n# recording_id=random_file.replace('.flac', '')\n# print(\"Id:\", recording_id)\n# record=tp_df[tp_df['recording_id']==recording_id]\n# y, sr=sf.read(random_file_path) # sr - sampling rate of y\n\n# print(f\"Sample rate: {sr}\")\n# if len(record)==0:\n#     print(\"False positive.\")\n# else:\n#     for _, row in record.iterrows():\n#         print(f\"Faj: {row['species_id']}\")\n#         print(f\"Típus: {row['songtype_id']}\")\n#         print(f\"Időtartam: {row['t_min']} - {row['t_max']}\")\n#         print(f\"Frekvencia: {row['f_min']} - {row['f_max']}\\n\")\n    \n# ipd.Audio(y, rate=sr)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-05T08:56:01.099379Z","iopub.execute_input":"2025-08-05T08:56:01.099571Z","iopub.status.idle":"2025-08-05T08:56:01.103373Z","shell.execute_reply.started":"2025-08-05T08:56:01.099555Z","shell.execute_reply":"2025-08-05T08:56:01.102546Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Spectrogram","metadata":{}},{"cell_type":"code","source":"# S=librosa.feature.melspectrogram(y=y, sr=sr)\n# fig, ax=plt.subplots()\n# S_db=librosa.power_to_db(S, ref=np.max)\n# image=librosa.display.specshow(S_db, sr=sr, x_axis='time', y_axis='mel', ax=ax)\n# fig.colorbar(image, ax=ax)\n# ax.set(title='Spectrogram')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-05T08:56:01.104065Z","iopub.execute_input":"2025-08-05T08:56:01.104290Z","iopub.status.idle":"2025-08-05T08:56:01.117564Z","shell.execute_reply.started":"2025-08-05T08:56:01.104275Z","shell.execute_reply":"2025-08-05T08:56:01.116964Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Spectrogram - training","metadata":{}},{"cell_type":"code","source":"def spectrogram_gen(\n    file_path,\n    save,\n    recording_id,\n    species_id,\n    time_min=None,\n    time_max=None,\n    sr=48000,\n    length=10,\n    image_height=128,\n    image_width=400,\n):\n    slice_length=length*sr\n    audio, _=librosa.load(file_path, sr=sr)\n\n    center=(time_min+time_max)/2*sr\n    start=max(center-slice_length//2, 0)\n    end=start+slice_length\n    if end>len(audio):\n        end=len(audio)\n        start=end-slice_length\n    sliced_audio=audio[int(start):int(end)]\n\n    S=librosa.feature.melspectrogram(y=sliced_audio, sr=sr)\n    S_db=librosa.power_to_db(S, ref=np.max)\n    S_norm=(S_db-S_db.min())/(S_db.max()-S_db.min())\n    S_norm=(S_norm*255).astype(np.uint8)\n    S_image=Image.fromarray(S_norm)\n    S_image=S_image.resize((image_width, image_height))\n\n    species_path=os.path.join(save, species_id)\n    os.makedirs(species_path, exist_ok=True)\n\n    filename=f'{species_id}_{recording_id}_{center}.bmp' # {center} kell, hátha ugyanolyan nevű file keletkezne\n    save_path=os.path.join(species_path, filename)\n    S_image.save(save_path)\n    \n    return save_path # későbbi visszanézésre","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-05T08:56:01.118375Z","iopub.execute_input":"2025-08-05T08:56:01.118630Z","iopub.status.idle":"2025-08-05T08:56:01.133293Z","shell.execute_reply.started":"2025-08-05T08:56:01.118591Z","shell.execute_reply":"2025-08-05T08:56:01.132527Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## True positive","metadata":{}},{"cell_type":"code","source":"#tp_df=pd.read_csv(tp_csv)\nufiles=tp_df['recording_id'].nunique()\nprint(f\"True Positive - fájlok száma (egyedi): {ufiles}\")\nprint(f\"True Positive - fájlok száma (összes): {len(tp_df)}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-05T08:56:01.134059Z","iopub.execute_input":"2025-08-05T08:56:01.134704Z","iopub.status.idle":"2025-08-05T08:56:01.152487Z","shell.execute_reply.started":"2025-08-05T08:56:01.134686Z","shell.execute_reply":"2025-08-05T08:56:01.151769Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"with open(tp_csv) as f:\n    reader=csv.reader(f)\n    next(reader) # fejlécet átugorjuk\n    for i, row in enumerate(reader):\n        recording_id=row[0]\n        species_id=row[1]\n        time_min=float(row[3])\n        time_max=float(row[5])\n        file_path=os.path.join(train_path, recording_id + '.flac')\n        audio, _=librosa.load(file_path, sr=sr)\n\n        spectrogram_gen(\n            file_path=file_path,\n            save=save,\n            recording_id=recording_id,\n            species_id=species_id,\n            time_min=time_min,\n            time_max=time_max,\n            sr=sr,\n            length=length,\n            image_height=image_height,\n            image_width=image_width\n        )\n\n        if i%100==0:\n            print(f'{i} file feldolgozva.')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-05T08:56:01.154896Z","iopub.execute_input":"2025-08-05T08:56:01.155089Z","iopub.status.idle":"2025-08-05T08:59:27.839463Z","shell.execute_reply.started":"2025-08-05T08:56:01.155074Z","shell.execute_reply":"2025-08-05T08:59:27.838650Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"species=len([f for f in os.listdir(save) if os.path.isdir(os.path.join(save, f))])\nprint(f\"Fajok száma: {species}\")\n\nsum_files=0\nprint(\"Fájlok száma az egyes species mappákban:\")\nfor f in os.listdir(save):\n    path=os.path.join(save, f)\n    if os.path.isdir(path):\n        files=len([name for name in os.listdir(path) if os.path.isfile(os.path.join(path, name))])\n        sum_files+=files\n        print(f\"{f}:\\t{files}\")\nprint(f\"Összes file: {sum_files}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-05T08:59:27.840353Z","iopub.execute_input":"2025-08-05T08:59:27.840575Z","iopub.status.idle":"2025-08-05T08:59:27.855432Z","shell.execute_reply.started":"2025-08-05T08:59:27.840556Z","shell.execute_reply":"2025-08-05T08:59:27.854763Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Mappa törlése","metadata":{}},{"cell_type":"code","source":"# # Mappa törlése\n# if os.path.exists(save):\n#     shutil.rmtree(save)\n#     print(\"Mappa törölve.\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-05T08:59:27.856313Z","iopub.execute_input":"2025-08-05T08:59:27.856563Z","iopub.status.idle":"2025-08-05T08:59:27.865007Z","shell.execute_reply.started":"2025-08-05T08:59:27.856542Z","shell.execute_reply":"2025-08-05T08:59:27.864436Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## False positive","metadata":{}},{"cell_type":"code","source":"# #fp_df=pd.read_csv(fp_csv)\n# ufiles=fp_df['recording_id'].nunique()\n# print(f\"False Positive - fájlok száma (egyedi): {ufiles}\")\n# print(f\"False Positive - fájlok száma (összes): {len(fp_df)}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-05T08:59:27.865701Z","iopub.execute_input":"2025-08-05T08:59:27.865892Z","iopub.status.idle":"2025-08-05T08:59:27.879502Z","shell.execute_reply.started":"2025-08-05T08:59:27.865877Z","shell.execute_reply":"2025-08-05T08:59:27.878920Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# with open(fp_csv) as f:\n#     reader=csv.reader(f)\n#     next(reader) # fejlécet átugorjuk\n#     for i, row in enumerate(reader):\n#         recording_id=row[0]\n#         species_id=row[1]\n#         time_min=float(row[3])\n#         time_max=float(row[5])\n#         file_path=os.path.join(train_path, recording_id + '.flac')\n#         audio, _=librosa.load(file_path, sr=sr)\n\n#         spectrogram_gen(\n#             file_path=file_path,\n#             save=save,\n#             recording_id=recording_id,\n#             species_id=species_id,\n#             time_min=time_min,\n#             time_max=time_max,\n#             sr=sr,\n#             length=length,\n#             image_height=image_height,\n#             image_width=image_width\n#         )\n\n#         if i%100==0:\n#             print(f'{i} file feldolgozva.')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-05T08:59:27.880363Z","iopub.execute_input":"2025-08-05T08:59:27.880629Z","iopub.status.idle":"2025-08-05T08:59:27.893083Z","shell.execute_reply.started":"2025-08-05T08:59:27.880581Z","shell.execute_reply":"2025-08-05T08:59:27.892413Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# species=len([f for f in os.listdir(save) if os.path.isdir(os.path.join(save, f))])\n# print(f\"Fajok száma: {species}\")\n\n# print(\"Fájlok száma az egyes species mappákban:\")\n# for f in os.listdir(save):\n#     path=os.path.join(save, f)\n#     if os.path.isdir(path):\n#         files=len([name for name in os.listdir(path) if os.path.isfile(os.path.join(path, name))])\n#         print(f\"{f}:\\t{files}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-05T08:59:27.893747Z","iopub.execute_input":"2025-08-05T08:59:27.893982Z","iopub.status.idle":"2025-08-05T08:59:27.910321Z","shell.execute_reply.started":"2025-08-05T08:59:27.893959Z","shell.execute_reply":"2025-08-05T08:59:27.909637Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## One-hot ","metadata":{}},{"cell_type":"code","source":"class AudioDataset(torch.utils.data.Dataset):\n    def __init__(self, files):\n        self.files=files\n\n    def __len__(self):\n        return len(self.files)\n\n    def __getitem__(self, i):\n        f=self.files[i]\n        image=Image.open(f)\n        image=image.convert('L') # grayscale\n        image=np.array(image, dtype=np.float32)/255 # conv2d-hez\n        image=torch.tensor(image)\n        image=image.unsqueeze(0) # channel\n        #image=image.unsqueeze(-1) # batch size\n            \n        label=int(os.path.basename(os.path.dirname(f)))\n        s=torch.zeros(species)\n        s[label]=1.0\n\n        return image, s","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-05T08:59:27.911120Z","iopub.execute_input":"2025-08-05T08:59:27.911352Z","iopub.status.idle":"2025-08-05T08:59:27.924119Z","shell.execute_reply.started":"2025-08-05T08:59:27.911327Z","shell.execute_reply":"2025-08-05T08:59:27.923590Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Modell","metadata":{}},{"cell_type":"code","source":"class CNN(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.model=nn.Sequential(\n            nn.Conv2d(1, 16, (3,3)),\n            nn.ReLU(),\n            #nn.MaxPool2d(2),\n            nn.Conv2d(16, 32, (3,3)),\n            nn.ReLU(),\n            # nn.Conv2d(32, 64, (4,4)),\n            # nn.ReLU(),\n            #nn.MaxPool2d(2),\n            nn.Flatten(),\n            nn.Linear(64*(image_height-4)*(image_width-4), 128),\n            nn.ReLU(),\n            nn.Linear(128, species),\n            nn.Sigmoid()\n        )\n       \n\n    def forward(self, x):\n        return self.model(x)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-05T09:35:29.704161Z","iopub.execute_input":"2025-08-05T09:35:29.704689Z","iopub.status.idle":"2025-08-05T09:35:29.710050Z","shell.execute_reply.started":"2025-08-05T09:35:29.704659Z","shell.execute_reply":"2025-08-05T09:35:29.709274Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def train_model(\n    model,\n    training_loader,\n    val_loader,\n    device,\n    epochs=30,\n    lr=1e-3,\n    patience=5,\n    min_delta=1e-4,\n    class_weights=None\n):\n    model.to(device)\n\n    if class_weights is not None:\n        loss_fn=nn.BCELoss(weight=class_weights)\n        class_weights=class_weights.to(device)\n    else:\n        loss_fn=nn.BCELoss()\n\n    optimizer=torch.optim.Adam(model.parameters())\n    scheduler=torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, factor=0.5, patience=patience)\n    patience_count=0\n    best_val_loss=float('inf')\n    \n    for epoch in range(epochs):\n        model.train()\n        train_loss=0.0\n\n        for inputs, labels in training_loader:\n            inputs=inputs.to(device)\n            labels=labels.to(device)\n            optimizer.zero_grad()\n            outputs=model(inputs)\n            loss=loss_fn(outputs, labels)\n            loss.backward()\n            optimizer.step()\n            train_loss+=loss.item()*inputs.size(0) # batch_size\n        train_loss/=len(training_loader.dataset)\n\n        model.eval()\n        val_loss=0.0\n        with torch.no_grad():\n            for inputs, labels in val_loader:\n                inputs=inputs.to(device)\n                labels=labels.to(device)\n                outputs=model(inputs)\n                metric.update(outputs, labels)\n                loss=loss_fn(outputs, labels)\n                val_loss+=loss.item()*inputs.size(0)\n\n            val_loss/=len(val_loader.dataset)\n\n        accuracy=metric.compute()\n        metric.reset()\n        scheduler.step(val_loss)\n        print(f\"Epoch: {epoch+1}/{epochs}\")\n        print(f\"Accuracy: {accuracy}\")\n        print(f\"Train loss: {train_loss}\")\n        print(f\"Validation loss: {val_loss}\")\n\n        if val_loss<best_val_loss-min_delta:\n            best_val_loss=val_loss\n            patience_count=0\n            best_model=model.state_dict()\n        else:\n            patience_count+=1\n            if patience_count>=patience:\n                print(f\"Early stopping. Epoch: {epoch+1}\")\n                break\n\n    model.load_state_dict(best_model)\n    return model","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-05T09:35:34.382998Z","iopub.execute_input":"2025-08-05T09:35:34.383736Z","iopub.status.idle":"2025-08-05T09:35:34.392213Z","shell.execute_reply.started":"2025-08-05T09:35:34.383703Z","shell.execute_reply":"2025-08-05T09:35:34.391652Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Training","metadata":{}},{"cell_type":"code","source":"all_files=glob(\"/kaggle/working/spectrograms/*/*.bmp\")\nprint(f\"Összes file: {len(all_files)}\")\ntrain_files, val_files=train_test_split(all_files, test_size=0.1)\n\ntrain_dataset=AudioDataset(train_files)\nval_dataset=AudioDataset(val_files)\n\ntraining_loader=DataLoader(train_dataset, batch_size=batch_size, shuffle=True)\nval_loader=DataLoader(val_dataset, batch_size=batch_size, shuffle=True)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-05T08:59:27.985799Z","iopub.execute_input":"2025-08-05T08:59:27.985994Z","iopub.status.idle":"2025-08-05T08:59:28.007487Z","shell.execute_reply.started":"2025-08-05T08:59:27.985979Z","shell.execute_reply":"2025-08-05T08:59:28.006831Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Tanítás","metadata":{}},{"cell_type":"code","source":"model=CNN()\ntrain_model(\n    model=model,\n    training_loader=training_loader,\n    val_loader=val_loader,\n    device=device,\n    epochs=epochs\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-05T09:35:40.193076Z","iopub.execute_input":"2025-08-05T09:35:40.193315Z","iopub.status.idle":"2025-08-05T09:38:04.694362Z","shell.execute_reply.started":"2025-08-05T09:35:40.193298Z","shell.execute_reply":"2025-08-05T09:38:04.693650Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Test gen","metadata":{}},{"cell_type":"code","source":"def gen_test(\n    file_path,\n    sr=48000,\n    length=10,\n    image_height=128,\n    image_width=400):\n\n    spectrograms=[]\n    audio, _=librosa.load(file_path, sr=sr)\n    slice_length=sr*length\n    n=len(audio)//slice_length\n\n    for i in range(n):\n        start=i*slice_length\n        end=start+slice_length\n        if end>len(audio):\n            end=len(audio)\n        sliced_audio=audio[start:end]\n\n        S = librosa.feature.melspectrogram(y=sliced_audio, sr=sr)\n        S_db = librosa.power_to_db(S, ref=np.max)\n        S_norm = (S_db - S_db.min()) / (S_db.max() - S_db.min())\n        S_norm = (S_norm * 255).astype(np.uint8)\n        image=Image.fromarray(S_norm).resize((image_width, image_height))\n        array=np.array(image)/255.0\n        spectrograms.append(array)\n\n    return spectrograms","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-05T08:59:27.938092Z","iopub.execute_input":"2025-08-05T08:59:27.938308Z","iopub.status.idle":"2025-08-05T08:59:27.955860Z","shell.execute_reply.started":"2025-08-05T08:59:27.938291Z","shell.execute_reply":"2025-08-05T08:59:27.955128Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def predict_test(\n    model,\n    spectrograms,\n    device,\n    threshold=0.5\n):\n    model.eval()\n    model.to(device)\n    inputs=[]\n\n    for s in spectrograms:\n        tensor=torch.tensor(s, dtype=torch.float32)\n        tensor=tensor.unsqueeze(0).unsqueeze(0) #batch, channels\n        inputs.append(tensor)\n    inputs=torch.cat(inputs).to(device)\n\n    with torch.no_grad():\n        outputs=model(inputs)\n\n    pred=outputs.max(dim=0).values\n    binary_pred=(pred>threshold).int()\n\n    return pred.cpu().numpy(), binary_pred.cpu().numpy()  ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-05T08:59:27.956698Z","iopub.execute_input":"2025-08-05T08:59:27.956940Z","iopub.status.idle":"2025-08-05T08:59:27.970165Z","shell.execute_reply.started":"2025-08-05T08:59:27.956917Z","shell.execute_reply":"2025-08-05T08:59:27.969516Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Predikció\n### Egy fájlon","metadata":{}},{"cell_type":"code","source":"# file_path='/kaggle/input/rfcx-species-audio-detection/train/34340b225.flac'\n# spectrograms=gen_test(file_path)\n# pred, binary_pred=predict_test(model, spectrograms, device)\n\n# print(\"Egyes fajok előfordulásának valószínűsége:\")\n# for i, probability in enumerate(pred):\n#     print(f\"{i}.\\t{probability}\")\n# print(\"Binary prediction:\")\n# print(binary_pred)\n\n# audio, sr=sf.read(file_path)\n# ipd.Audio(audio, rate=sr)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-05T09:00:31.448212Z","iopub.execute_input":"2025-08-05T09:00:31.448483Z","iopub.status.idle":"2025-08-05T09:00:31.451627Z","shell.execute_reply.started":"2025-08-05T09:00:31.448459Z","shell.execute_reply":"2025-08-05T09:00:31.450884Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Összes fájlon","metadata":{}},{"cell_type":"code","source":"def create_csv(model, test_path, device, csv_file=None):\n    rows=[]\n    \n    for i, file in enumerate(sorted(os.listdir(test_path))):\n        if file.endswith('.flac'):\n            file_path=os.path.join(test_path, file)\n            recording_id=file.replace('.flac', '')\n            spectrograms=gen_test(file_path)\n            pred, _=predict_test(model, spectrograms, device)\n            #pred_rounded=[round(p, 1) for p in pred]\n            pred_rounded=pred\n            \n            rows.append([recording_id]+list(pred_rounded))\n        if i%100==0:\n            print(f\"{i} file feldolgozva.\")\n    \n    df=pd.DataFrame(rows, columns=['recording_id']+[f\"s{i}\" for i in range(24)])\n    if csv_file:\n        df.to_csv(csv_file, index=False)\n    else:\n        print(df)\n    ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-05T09:42:57.469559Z","iopub.execute_input":"2025-08-05T09:42:57.470121Z","iopub.status.idle":"2025-08-05T09:42:57.475645Z","shell.execute_reply.started":"2025-08-05T09:42:57.470097Z","shell.execute_reply":"2025-08-05T09:42:57.474879Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission_dir='/kaggle/working/csv'\nos.makedirs(submission_dir, exist_ok=True)\ncsv_file=os.path.join(submission_dir, 'submission.csv')\ncreate_csv(model, test_path, device, csv_file=csv_file)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-05T09:43:00.964442Z","iopub.execute_input":"2025-08-05T09:43:00.965023Z","iopub.status.idle":"2025-08-05T09:51:52.292568Z","shell.execute_reply.started":"2025-08-05T09:43:00.965001Z","shell.execute_reply":"2025-08-05T09:51:52.292018Z"}},"outputs":[],"execution_count":null}]}