{"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":"gpu","dataSources":[{"sourceId":25954,"databundleVersionId":2091745,"sourceType":"competition"}],"dockerImageVersionId":31154,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"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","trusted":true,"execution":{"iopub.status.busy":"2025-10-29T17:57:43.434394Z","iopub.execute_input":"2025-10-29T17:57:43.434700Z","iopub.status.idle":"2025-10-29T17:58:34.421333Z","shell.execute_reply.started":"2025-10-29T17:57:43.434674Z","shell.execute_reply":"2025-10-29T17:58:34.420533Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import warnings\nwarnings.filterwarnings('ignore')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-30T13:27:20.262527Z","iopub.execute_input":"2025-10-30T13:27:20.262817Z","iopub.status.idle":"2025-10-30T13:27:20.266581Z","shell.execute_reply.started":"2025-10-30T13:27:20.262797Z","shell.execute_reply":"2025-10-30T13:27:20.265916Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nfrom pathlib import Path\nimport random\nimport math\nimport numpy as np\nimport pandas as pd\nfrom tqdm.auto import tqdm\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import Dataset, DataLoader\nimport torchvision.transforms as T\nimport timm \nimport librosa\nimport soundfile as sf","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-30T13:27:21.830115Z","iopub.execute_input":"2025-10-30T13:27:21.830831Z","iopub.status.idle":"2025-10-30T13:27:21.835167Z","shell.execute_reply.started":"2025-10-30T13:27:21.830806Z","shell.execute_reply":"2025-10-30T13:27:21.834233Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Конфиг с оптимизацией\nDATA_ROOT = Path(\"/kaggle/input/birdclef-2021\")\nTRAIN_AUDIO_DIR = DATA_ROOT / \"train_short_audio\"            \nTRAIN_META = DATA_ROOT / \"train_metadata.csv\"","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-30T13:27:24.645831Z","iopub.execute_input":"2025-10-30T13:27:24.646109Z","iopub.status.idle":"2025-10-30T13:27:24.650232Z","shell.execute_reply.started":"2025-10-30T13:27:24.646087Z","shell.execute_reply":"2025-10-30T13:27:24.649498Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"SR = 32000              # целевая дискретизация\nDURATION = 5            # длительность для большего контекста\nAUDIO_LEN = SR * DURATION\nN_MELS = 224            \nFMIN = 20\nFMAX = 16000            \nBATCH = 128 if torch.cuda.is_available() else 64  # батч\nNUM_WORKERS = 2  # воркеры\nDEVICE = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nSEED = 42","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-30T13:27:26.473169Z","iopub.execute_input":"2025-10-30T13:27:26.473841Z","iopub.status.idle":"2025-10-30T13:27:26.478357Z","shell.execute_reply.started":"2025-10-30T13:27:26.473815Z","shell.execute_reply":"2025-10-30T13:27:26.477579Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Воспроизводимость\ndef seed_everything(seed=SEED):\n    random.seed(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    if torch.cuda.is_available():\n        torch.cuda.manual_seed_all(seed)\n    torch.backends.cudnn.deterministic = True\n    torch.backends.cudnn.benchmark = True\n\nseed_everything()\nprint(\"Device:\", DEVICE)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-30T13:27:28.852794Z","iopub.execute_input":"2025-10-30T13:27:28.853058Z","iopub.status.idle":"2025-10-30T13:27:28.859653Z","shell.execute_reply.started":"2025-10-30T13:27:28.853039Z","shell.execute_reply":"2025-10-30T13:27:28.859032Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Упрощенные утилиты для аудио\ndef load_audio(path, sr=SR, duration=DURATION):\n    try:        \n        audio, orig_sr = librosa.load(path, sr=sr, duration=duration, mono=True)\n        return audio.astype(np.float32)\n    except Exception as e:\n        print(f\"Error loading {path}: {e}\")        \n        return np.zeros(AUDIO_LEN, dtype=np.float32)\n\ndef random_crop_or_pad(x, length=AUDIO_LEN):    \n    if len(x) >= length:\n        start = np.random.randint(0, len(x) - length + 1)\n        return x[start:start+length]\n    else:\n        # Простой паддинг в конец\n        return np.pad(x, (0, length - len(x)), mode='constant')\n\ndef compute_mel_spec(y, sr=32000, n_mels=N_MELS, fmin=FMIN, fmax=FMAX):\n    try:\n        mel = librosa.feature.melspectrogram(\n            y=y,\n            sr=sr,\n            n_mels=n_mels,\n            n_fft=2048,\n            hop_length=512,\n            fmin=fmin,\n            fmax=fmax,\n            power=2.0\n        )\n        \n        mel_db = librosa.power_to_db(mel, ref=1.0)\n        mel_db = (mel_db - mel_db.mean()) / (mel_db.std() + 1e-6)\n        return mel_db.astype(np.float32)\n    except Exception as e:        \n        return np.zeros((n_mels, 313), dtype=np.float32)  ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-30T13:27:31.313806Z","iopub.execute_input":"2025-10-30T13:27:31.314054Z","iopub.status.idle":"2025-10-30T13:27:31.321267Z","shell.execute_reply.started":"2025-10-30T13:27:31.314037Z","shell.execute_reply":"2025-10-30T13:27:31.320425Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Аугментации\ndef audio_augmentations(audio, apply_prob=0.5):\n    augmented = audio.copy()\n    \n    # Добавление шума\n    if np.random.rand() < apply_prob:\n        noise = np.random.normal(0, 0.005, audio.shape).astype(np.float32)\n        augmented += noise\n    \n    if np.random.rand() < apply_prob:\n        shift = int(len(audio) * 0.2 * np.random.uniform(-1, 1))\n        if abs(shift) > 0:\n            augmented = np.roll(augmented, shift)\n    \n    return augmented","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-30T13:27:38.673997Z","iopub.execute_input":"2025-10-30T13:27:38.674490Z","iopub.status.idle":"2025-10-30T13:27:38.679209Z","shell.execute_reply.started":"2025-10-30T13:27:38.674466Z","shell.execute_reply":"2025-10-30T13:27:38.678360Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def spec_augment_simple(mel):\n    mel = mel.copy()\n    T, F = mel.shape[1], mel.shape[0]\n    \n    # Маскировка времени\n    if T > 10:\n        t_mask_width = min(20, T // 4)\n        t0 = np.random.randint(0, T - t_mask_width)\n        mel[:, t0:t0+t_mask_width] = mel.min()\n    \n    # Частотная маскировка\n    if F > 5:\n        f_mask_width = min(5, F // 8)\n        f0 = np.random.randint(0, F - f_mask_width)\n        mel[f0:f0+f_mask_width, :] = mel.min()\n    \n    return mel","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-30T13:27:41.065415Z","iopub.execute_input":"2025-10-30T13:27:41.066101Z","iopub.status.idle":"2025-10-30T13:27:41.071007Z","shell.execute_reply.started":"2025-10-30T13:27:41.066079Z","shell.execute_reply":"2025-10-30T13:27:41.070186Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Подготовка данных\nmeta = pd.read_csv(TRAIN_META)\nlabels = sorted(meta['primary_label'].unique().tolist())\nLABEL2ID = {l:i for i,l in enumerate(labels)}\nID2LABEL = {i:l for l,i in LABEL2ID.items()}\nNUM_CLASSES = len(labels)\nprint(\"Found classes:\", NUM_CLASSES)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-30T13:27:44.122912Z","iopub.execute_input":"2025-10-30T13:27:44.123193Z","iopub.status.idle":"2025-10-30T13:27:44.427527Z","shell.execute_reply.started":"2025-10-30T13:27:44.123173Z","shell.execute_reply":"2025-10-30T13:27:44.426838Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Формирование DataFrame\nif TRAIN_AUDIO_DIR.exists():\n    audio_files = []\n    for bird_dir in TRAIN_AUDIO_DIR.iterdir():\n        if bird_dir.is_dir():\n            for audio_file in bird_dir.glob(\"*.ogg\"):\n                audio_files.append({\n                    \"filename\": audio_file.name,\n                    \"primary_label\": bird_dir.name,\n                    \"filepath\": str(audio_file)\n                })\n    df_short = pd.DataFrame(audio_files)\nelse:\n    raise FileNotFoundError(f\"Папка {TRAIN_AUDIO_DIR} не найдена!\")\n\nprint(\"Всего файлов:\", len(df_short))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-30T13:27:47.069590Z","iopub.execute_input":"2025-10-30T13:27:47.070259Z","iopub.status.idle":"2025-10-30T13:27:47.757103Z","shell.execute_reply.started":"2025-10-30T13:27:47.070232Z","shell.execute_reply":"2025-10-30T13:27:47.756238Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# # Фильтрация файлов\n# def filter_valid_files_simple(df, max_files_per_class=500):\n#     valid_files = []\n#     class_counts = {}\n    \n#     for _, row in tqdm(df.iterrows(), total=len(df), desc=\"Filtering files\"):\n#         label = row[\"primary_label\"]\n                \n#         if label not in class_counts:\n#             class_counts[label] = 0\n        \n#         if class_counts[label] < max_files_per_class:\n#             try:\n#                 # Быстрая проверка файла\n#                 audio = load_audio_fast(row[\"filepath\"], duration=1.0)\n#                 if len(audio) > 1000:  \n#                     valid_files.append(row)\n#                     class_counts[label] += 1\n#             except:\n#                 continue\n    \n#     filtered_df = pd.DataFrame(valid_files)\n#     print(f\"Filtered to {len(filtered_df)} files across {len(class_counts)} classes\")\n#     return filtered_df","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-30T13:16:54.878879Z","iopub.execute_input":"2025-10-30T13:16:54.879364Z","iopub.status.idle":"2025-10-30T13:16:54.884867Z","shell.execute_reply.started":"2025-10-30T13:16:54.879343Z","shell.execute_reply":"2025-10-30T13:16:54.884013Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class SimpleBirdDataset(Dataset):\n    def __init__(self, df, label2id, train=True):\n        self.df = df.reset_index(drop=True).copy()\n        self.label2id = label2id\n        self.train = train\n        # если в df есть метка primary_label\n        self.labels = [self.label2id[row] if row in self.label2id else 0\n                       for row in self.df['primary_label'].values]\n\n    def __len__(self):\n        return len(self.df)\n\n    def __getitem__(self, idx):\n        row = self.df.iloc[idx]\n        filepath = row[\"filepath\"]\n        label_idx = self.labels[idx]\n\n        # Загружаем аудио обычной функцией\n        audio = load_audio(filepath, sr=SR, duration=DURATION)  # гарантированно определена\n\n        # Crop / pad\n        audio = random_crop_or_pad(audio, length=AUDIO_LEN)\n\n        # Аугментации аудио (временные/шум)\n        if self.train and np.random.rand() < 0.7:\n            audio = audio_augmentations(audio, apply_prob=0.5)\n\n        # Мел-спектр\n        mel = compute_mel_spec(audio, sr=SR, n_mels=N_MELS, fmin=FMIN, fmax=FMAX)\n\n        # Спец-аугментация на спектрограмме\n        if self.train and np.random.rand() < 0.5:\n            mel = spec_augment_simple(mel)\n\n        # Нормализация\n        mel = (mel - mel.mean()) / (mel.std() + 1e-6)\n\n        # Преобразуем в тензор (1, n_mels, T)\n        mel_tensor = torch.tensor(mel, dtype=torch.float32).unsqueeze(0)\n\n        label = torch.tensor(label_idx, dtype=torch.long)\n        return mel_tensor, label","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-30T13:28:03.693978Z","iopub.execute_input":"2025-10-30T13:28:03.694256Z","iopub.status.idle":"2025-10-30T13:28:03.702150Z","shell.execute_reply.started":"2025-10-30T13:28:03.694237Z","shell.execute_reply":"2025-10-30T13:28:03.701299Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\nfrom pathlib import Path\nfrom tqdm.auto import tqdm\nimport librosa\nfrom sklearn.model_selection import train_test_split\n\ndef create_bird_dataframe_fast(audio_dir, max_files_per_class=150):\n    audio_dir = Path(audio_dir)\n    records = []\n    bird_dirs = sorted([d for d in audio_dir.iterdir() if d.is_dir()])\n\n    for bird_dir in tqdm(bird_dirs, desc=\"Scanning bird dirs\"):\n        files = list(bird_dir.glob(\"*.ogg\"))\n        if not files:\n            continue\n        random.shuffle(files)\n        files = files[:max_files_per_class]\n        for f in files:\n            records.append({\n                \"filename\": f.name,\n                \"primary_label\": bird_dir.name,\n                \"filepath\": str(f)\n            })\n    df = pd.DataFrame(records)\n    print(f\"Loaded {len(df)} files from {df['primary_label'].nunique()} classes\")\n    return df","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-30T13:28:08.990219Z","iopub.execute_input":"2025-10-30T13:28:08.990727Z","iopub.status.idle":"2025-10-30T13:28:08.996335Z","shell.execute_reply.started":"2025-10-30T13:28:08.990704Z","shell.execute_reply":"2025-10-30T13:28:08.995518Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"TRAIN_AUDIO_DIR = Path(\"/kaggle/input/birdclef-2021/train_short_audio\")\ndf_short_clean = create_bird_dataframe_fast(TRAIN_AUDIO_DIR, max_files_per_class=150)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-30T13:28:13.080393Z","iopub.execute_input":"2025-10-30T13:28:13.080649Z","iopub.status.idle":"2025-10-30T13:28:13.586158Z","shell.execute_reply.started":"2025-10-30T13:28:13.080631Z","shell.execute_reply":"2025-10-30T13:28:13.585571Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Проверяем результат\nif not df_short_clean.empty:\n    print(\"DataFrame created successfully!\")\n    print(f\"Shape: {df_short_clean.shape}\")\n    print(f\"Columns: {df_short_clean.columns.tolist()}\")\n    print(\"\\nFirst 3 rows:\")\n    print(df_short_clean.head(3))\n    \n    # Разделение данных - ВАЖНО: правильные отступы!\n    df_train, df_val = train_test_split(\n        df_short_clean, \n        test_size=0.15, \n        stratify=df_short_clean['primary_label'], \n        random_state=SEED\n    )\n    print(f\"Train size: {len(df_train)}, Val size: {len(df_val)}\")\n    \n    # Проверяем распределение\n    print(f\"Train classes: {df_train['primary_label'].nunique()}\")\n    print(f\"Val classes: {df_val['primary_label'].nunique()}\")\n    \nelse:\n    print(\"Failed to create DataFrame!\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-30T13:28:22.453884Z","iopub.execute_input":"2025-10-30T13:28:22.454569Z","iopub.status.idle":"2025-10-30T13:28:22.506354Z","shell.execute_reply.started":"2025-10-30T13:28:22.454545Z","shell.execute_reply":"2025-10-30T13:28:22.505601Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# маленькая проверка\ndf_test = df_short_clean.sample(n=min(10, len(df_short_clean)), random_state=SEED)\nds_test = SimpleBirdDataset(df_test, LABEL2ID, train=False)\n\n# Попытка получить пару (mel, label)\nx, y = ds_test[0]\nprint(\"x.shape:\", x.shape, \"y:\", y)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-30T13:28:25.355412Z","iopub.execute_input":"2025-10-30T13:28:25.356112Z","iopub.status.idle":"2025-10-30T13:28:38.434094Z","shell.execute_reply.started":"2025-10-30T13:28:25.356088Z","shell.execute_reply":"2025-10-30T13:28:38.433308Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Создаем датасеты и даталоадеры\nprint(\"Creating datasets and dataloaders...\")\ntrain_ds = SimpleBirdDataset(df_train, LABEL2ID, train=True)\nval_ds = SimpleBirdDataset(df_val, LABEL2ID, train=False)\n\ntrain_dl = DataLoader(\n    train_ds, \n    batch_size=BATCH, \n    shuffle=True, \n    num_workers=NUM_WORKERS,\n    pin_memory=True\n)\n\nval_dl = DataLoader(\n    val_ds, \n    batch_size=BATCH, \n    shuffle=False, \n    num_workers=NUM_WORKERS,\n    pin_memory=True\n)\n\nprint(f\"Train batches: {len(train_dl)}, Val batches: {len(val_dl)}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-30T13:29:25.646866Z","iopub.execute_input":"2025-10-30T13:29:25.647842Z","iopub.status.idle":"2025-10-30T13:29:25.671333Z","shell.execute_reply.started":"2025-10-30T13:29:25.647816Z","shell.execute_reply":"2025-10-30T13:29:25.670678Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Создаем модель\nclass BirdClassifier(nn.Module):\n    def __init__(self, num_classes):\n        super().__init__()\n        self.backbone = timm.create_model(\n            \"efficientnet_b0\",\n            pretrained=True,\n            in_chans=1,\n            num_classes=num_classes,\n            drop_rate=0.2\n        )\n    \n    def forward(self, x):\n        return self.backbone(x)\n\nmodel = BirdClassifier(NUM_CLASSES)\nmodel.to(DEVICE)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-30T13:29:28.587162Z","iopub.execute_input":"2025-10-30T13:29:28.587429Z","iopub.status.idle":"2025-10-30T13:29:28.871164Z","shell.execute_reply.started":"2025-10-30T13:29:28.587410Z","shell.execute_reply":"2025-10-30T13:29:28.870400Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Оптимизатор и функция потерь\noptimizer = torch.optim.AdamW(\n    model.parameters(),\n    lr=1e-3,\n    weight_decay=0.01\n)\n\ncriterion = nn.CrossEntropyLoss(label_smoothing=0.1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-30T13:29:39.403407Z","iopub.execute_input":"2025-10-30T13:29:39.403983Z","iopub.status.idle":"2025-10-30T13:29:39.408707Z","shell.execute_reply.started":"2025-10-30T13:29:39.403960Z","shell.execute_reply":"2025-10-30T13:29:39.407964Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Функции обучения\ndef train_one_epoch(model, loader, optimizer, criterion):\n    model.train()\n    total_loss, correct, total = 0, 0, 0\n    \n    for x, y in tqdm(loader, desc=\"Training\", leave=False):\n        x, y = x.to(DEVICE), y.to(DEVICE)\n        \n        optimizer.zero_grad()\n        preds = model(x)\n        loss = criterion(preds, y)\n        loss.backward()\n        \n        torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)\n        optimizer.step()\n        \n        total_loss += loss.item() * x.size(0)\n        correct += (preds.argmax(1) == y).sum().item()\n        total += x.size(0)\n    \n    return total_loss / total, correct / total\n\ndef validate(model, loader, criterion):\n    model.eval()\n    total_loss, correct, total = 0, 0, 0\n    \n    with torch.no_grad():\n        for x, y in tqdm(loader, desc=\"Validation\", leave=False):\n            x, y = x.to(DEVICE), y.to(DEVICE)\n            preds = model(x)\n            loss = criterion(preds, y)\n            \n            total_loss += loss.item() * x.size(0)\n            correct += (preds.argmax(1) == y).sum().item()\n            total += x.size(0)\n    \n    return total_loss / total, correct / total","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-30T13:29:47.134663Z","iopub.execute_input":"2025-10-30T13:29:47.135068Z","iopub.status.idle":"2025-10-30T13:29:47.142224Z","shell.execute_reply.started":"2025-10-30T13:29:47.135043Z","shell.execute_reply":"2025-10-30T13:29:47.141382Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from torch.cuda.amp import autocast, GradScaler\nimport time\n\nEPOCHS = 8\nscaler = GradScaler()\nbest_acc = 0.0\nbest_epoch = 0\n\nprint(\"\\n Начало обучения...\\n\")\nfor epoch in range(1, EPOCHS + 1):\n    t0 = time.time()\n    \n    # === Обучение ===\n    model.train()\n    total_loss, correct, total = 0, 0, 0\n    for x, y in tqdm(train_dl, desc=f\"Epoch {epoch}/{EPOCHS} [train]\", leave=False):\n        x, y = x.to(DEVICE), y.to(DEVICE)\n        optimizer.zero_grad()\n        \n        with autocast():  # ускорение и экономия памяти\n            preds = model(x)\n            loss = criterion(preds, y)\n        \n        scaler.scale(loss).backward()\n        scaler.unscale_(optimizer)\n        torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)\n        scaler.step(optimizer)\n        scaler.update()\n\n        total_loss += loss.item() * x.size(0)\n        correct += (preds.argmax(1) == y).sum().item()\n        total += x.size(0)\n\n    train_loss = total_loss / total\n    train_acc = correct / total\n\n    # === Валидация ===\n    model.eval()\n    val_loss, val_acc = 0, 0\n    total, correct = 0, 0\n    with torch.no_grad():\n        for x, y in tqdm(val_dl, desc=f\"Epoch {epoch}/{EPOCHS} [val]\", leave=False):\n            x, y = x.to(DEVICE), y.to(DEVICE)\n            preds = model(x)\n            loss = criterion(preds, y)\n            val_loss += loss.item() * x.size(0)\n            correct += (preds.argmax(1) == y).sum().item()\n            total += x.size(0)\n    val_loss /= total\n    val_acc = correct / total\n\n    # === Сохранение лучшей модели ===\n    if val_acc > best_acc:\n        best_acc = val_acc\n        best_epoch = epoch\n        torch.save(model.state_dict(), \"best_bird_model.pth\")\n\n    t1 = time.time()\n    print(f\"[{epoch:02d}/{EPOCHS}] \"\n          f\"train_loss={train_loss:.4f}, train_acc={train_acc:.3f} | \"\n          f\"val_loss={val_loss:.4f}, val_acc={val_acc:.3f} | \"\n          f\"time={t1 - t0:.1f}s\")\n\nprint(f\"\\n Обучение завершено! Лучшая эпоха: {best_epoch}, точность = {best_acc:.3f}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-30T13:31:29.692549Z","iopub.execute_input":"2025-10-30T13:31:29.693082Z","iopub.status.idle":"2025-10-30T15:13:52.683606Z","shell.execute_reply.started":"2025-10-30T13:31:29.693059Z","shell.execute_reply":"2025-10-30T15:13:52.682590Z"}},"outputs":[],"execution_count":null}]}