{"metadata":{"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":59093,"databundleVersionId":7469972,"sourceType":"competition"}],"dockerImageVersionId":30648,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true},"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"papermill":{"default_parameters":{},"duration":22321.864322,"end_time":"2024-01-28T12:56:49.320132","environment_variables":{},"exception":null,"input_path":"__notebook__.ipynb","output_path":"__notebook__.ipynb","parameters":{},"start_time":"2024-01-28T06:44:47.45581","version":"2.4.0"},"widgets":{"application/vnd.jupyter.widget-state+json":{"state":{"020b844a5f1c4a998793589345d58187":{"model_module":"@jupyter-widgets/base","model_module_version":"1.2.0","model_name":"LayoutModel","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"1.2.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"1.2.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"overflow_x":null,"overflow_y":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"387ef6c55cf34ee8b06cef960ab5709e":{"model_module":"@jupyter-widgets/controls","model_module_version":"1.5.0","model_name":"DescriptionStyleModel","state":{"_model_module":"@jupyter-widgets/controls","_model_module_version":"1.5.0","_model_name":"DescriptionStyleModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"1.2.0","_view_name":"StyleView","description_width":""}},"4551e56c177e48c7b32c50244181acce":{"model_module":"@jupyter-widgets/controls","model_module_version":"1.5.0","model_name":"HTMLModel","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"1.5.0","_model_name":"HTMLModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"1.5.0","_view_name":"HTMLView","description":"","description_tooltip":null,"layout":"IPY_MODEL_020b844a5f1c4a998793589345d58187","placeholder":"​","style":"IPY_MODEL_a76c83a1114641e9a0278861a509523d","value":" 21.4M/21.4M [00:00&lt;00:00, 39.7MB/s]"}},"54c978d8e366477fa1f2e4de7d812eaa":{"model_module":"@jupyter-widgets/base","model_module_version":"1.2.0","model_name":"LayoutModel","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"1.2.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"1.2.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"overflow_x":null,"overflow_y":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"585b9ad521bc42f88613a33772d14b09":{"model_module":"@jupyter-widgets/controls","model_module_version":"1.5.0","model_name":"HTMLModel","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"1.5.0","_model_name":"HTMLModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"1.5.0","_view_name":"HTMLView","description":"","description_tooltip":null,"layout":"IPY_MODEL_54c978d8e366477fa1f2e4de7d812eaa","placeholder":"​","style":"IPY_MODEL_387ef6c55cf34ee8b06cef960ab5709e","value":"model.safetensors: 100%"}},"5c5e6c736e884230a714ede1aac584e8":{"model_module":"@jupyter-widgets/base","model_module_version":"1.2.0","model_name":"LayoutModel","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"1.2.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"1.2.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"overflow_x":null,"overflow_y":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"5d247d0364d444f4bda51aea5d8e9103":{"model_module":"@jupyter-widgets/controls","model_module_version":"1.5.0","model_name":"HBoxModel","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"1.5.0","_model_name":"HBoxModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"1.5.0","_view_name":"HBoxView","box_style":"","children":["IPY_MODEL_585b9ad521bc42f88613a33772d14b09","IPY_MODEL_f84cec30df65438192b9c608c0d1d8b4","IPY_MODEL_4551e56c177e48c7b32c50244181acce"],"layout":"IPY_MODEL_5c5e6c736e884230a714ede1aac584e8"}},"a76c83a1114641e9a0278861a509523d":{"model_module":"@jupyter-widgets/controls","model_module_version":"1.5.0","model_name":"DescriptionStyleModel","state":{"_model_module":"@jupyter-widgets/controls","_model_module_version":"1.5.0","_model_name":"DescriptionStyleModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"1.2.0","_view_name":"StyleView","description_width":""}},"f34a838e5b6b4dcc82ea12ad3977b520":{"model_module":"@jupyter-widgets/controls","model_module_version":"1.5.0","model_name":"ProgressStyleModel","state":{"_model_module":"@jupyter-widgets/controls","_model_module_version":"1.5.0","_model_name":"ProgressStyleModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"1.2.0","_view_name":"StyleView","bar_color":null,"description_width":""}},"f84cec30df65438192b9c608c0d1d8b4":{"model_module":"@jupyter-widgets/controls","model_module_version":"1.5.0","model_name":"FloatProgressModel","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"1.5.0","_model_name":"FloatProgressModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"1.5.0","_view_name":"ProgressView","bar_style":"success","description":"","description_tooltip":null,"layout":"IPY_MODEL_fe2e5aa594d24e889081a556aebdec4f","max":21355344,"min":0,"orientation":"horizontal","style":"IPY_MODEL_f34a838e5b6b4dcc82ea12ad3977b520","value":21355344}},"fe2e5aa594d24e889081a556aebdec4f":{"model_module":"@jupyter-widgets/base","model_module_version":"1.2.0","model_name":"LayoutModel","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"1.2.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"1.2.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"overflow_x":null,"overflow_y":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}}},"version_major":2,"version_minor":0}}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"## 📙 Import libraries and modules","metadata":{"papermill":{"duration":0.003786,"end_time":"2024-01-28T06:44:50.964435","exception":false,"start_time":"2024-01-28T06:44:50.960649","status":"completed"},"tags":[]}},{"cell_type":"code","source":"# Importing essential libraries\nimport gc\nimport os\nimport random\nimport warnings\nimport numpy as np\nimport pandas as pd\nfrom IPython.display import display\n\n# PyTorch for deep learning\nimport timm\nimport torch\nimport torch.nn as nn  \nimport torch.optim as optim\nimport torch.nn.functional as F\nfrom torch.optim.lr_scheduler import CosineAnnealingLR\n\n# torchvision for image processing and augmentation\nimport torchvision.transforms as transforms\n\n# Suppressing minor warnings to keep the output clean\nwarnings.filterwarnings('ignore', category=Warning)\n\n# Reclaim memory no longer in use.\ngc.collect()","metadata":{"papermill":{"duration":5.810106,"end_time":"2024-01-28T06:44:56.777717","exception":false,"start_time":"2024-01-28T06:44:50.967611","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2024-02-29T11:35:25.802213Z","iopub.execute_input":"2024-02-29T11:35:25.802568Z","iopub.status.idle":"2024-02-29T11:35:33.686150Z","shell.execute_reply.started":"2024-02-29T11:35:25.802533Z","shell.execute_reply":"2024-02-29T11:35:33.685254Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## ⚙️ Configuration","metadata":{"papermill":{"duration":0.003167,"end_time":"2024-01-28T06:44:56.784246","exception":false,"start_time":"2024-01-28T06:44:56.781079","status":"completed"},"tags":[]}},{"cell_type":"code","source":"# Configuration class containing hyperparameters and settings\nclass Config:\n    seed = 42 \n    image_transform = transforms.Resize((512,512))  \n    batch_size = 16\n    num_epochs = 9\n    num_folds = 5\n\n# Set the seed for reproducibility across multiple libraries\ndef set_seed(seed):\n    torch.backends.cudnn.deterministic = True\n    torch.backends.cudnn.benchmark = True\n    torch.manual_seed(seed)\n    np.random.seed(seed)\n    random.seed(seed)\n    \nset_seed(Config.seed)\n\n# Define the 'Kullback Leibler Divergence' loss function\ndef KL_loss(p,q):\n    epsilon=10**(-15)\n    p=torch.clip(p,epsilon,1-epsilon)\n    q = nn.functional.log_softmax(q,dim=1)\n    return torch.mean(torch.sum(p*(torch.log(p)-q),dim=1))\n\n# Reclaim memory no longer in use.\ngc.collect()","metadata":{"papermill":{"duration":0.139048,"end_time":"2024-01-28T06:44:56.926359","exception":false,"start_time":"2024-01-28T06:44:56.787311","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2024-02-29T11:35:33.688170Z","iopub.execute_input":"2024-02-29T11:35:33.688552Z","iopub.status.idle":"2024-02-29T11:35:33.866114Z","shell.execute_reply.started":"2024-02-29T11:35:33.688521Z","shell.execute_reply":"2024-02-29T11:35:33.865391Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 📂 Data Loading","metadata":{"papermill":{"duration":0.003288,"end_time":"2024-01-28T06:44:56.933246","exception":false,"start_time":"2024-01-28T06:44:56.929958","status":"completed"},"tags":[]}},{"cell_type":"code","source":"# Load training data\ntrain_df = pd.read_csv(\"/kaggle/input/hms-harmful-brain-activity-classification/train.csv\")\n\n# Filter out cases where the total number of votes is less than 5\nindices_eliminados = train_df.index[train_df[['seizure_vote','lpd_vote','gpd_vote','lrda_vote','grda_vote','other_vote']].sum(axis=1) < 4]\ntrain_df = train_df.drop(indices_eliminados)\ntrain_df = train_df.reset_index()\n\n\n# Define labels for classification\nlabels = ['seizure', 'lpd', 'gpd', 'lrda', 'grda', 'other']\n\n# Initialize an empty DataFrame for storing features\ntrain_feats = pd.DataFrame()\n\n# Aggregate votes for each label and merge into train_feats DataFrame\nfor label in labels:\n    # Group by 'spectrogram_id' and sum the votes for the current label\n    group = train_df[f'{label}_vote'].groupby(train_df['spectrogram_id']).sum()\n\n    # Create a DataFrame from the grouped data\n    label_vote_sum = pd.DataFrame({'spectrogram_id': group.index, f'{label}_vote_sum': group.values})\n\n    # Initialize train_feats with the first label or merge subsequent labels\n    if label == 'seizure':\n        train_feats = label_vote_sum\n    else:\n        train_feats = train_feats.merge(label_vote_sum, on='spectrogram_id', how='left')\n\n# Add a column to sum all votes\ntrain_feats['total_vote'] = 0\nfor label in labels:\n    train_feats['total_vote'] += train_feats[f'{label}_vote_sum']\n\n# Calculate and store the normalized vote for each label\nfor label in labels:\n    train_feats[f'{label}_vote'] = train_feats[f'{label}_vote_sum'] / train_feats['total_vote']\n\n# Select relevant columns for the training features\nchoose_cols = ['spectrogram_id']\nfor label in labels:\n    choose_cols += [f'{label}_vote']\ntrain_feats = train_feats[choose_cols]\n\n# Add a column with the path to the spectrogram files\ntrain_feats['path'] = train_feats['spectrogram_id'].apply(lambda x: \"/kaggle/input/hms-harmful-brain-activity-classification/train_spectrograms/\" + str(x) + \".parquet\")\n\n# Reclaim memory no longer in use.\ngc.collect()","metadata":{"papermill":{"duration":0.468753,"end_time":"2024-01-28T06:44:57.40548","exception":false,"start_time":"2024-01-28T06:44:56.936727","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2024-02-29T11:35:33.867177Z","iopub.execute_input":"2024-02-29T11:35:33.867470Z","iopub.status.idle":"2024-02-29T11:35:34.351074Z","shell.execute_reply.started":"2024-02-29T11:35:33.867440Z","shell.execute_reply":"2024-02-29T11:35:34.350154Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 🎰 Data Preprocessing","metadata":{"papermill":{"duration":0.003848,"end_time":"2024-01-28T06:44:57.41335","exception":false,"start_time":"2024-01-28T06:44:57.409502","status":"completed"},"tags":[]}},{"cell_type":"code","source":"def get_batch(paths, batch_size=Config.batch_size):\n    # Set a small epsilon to avoid division by zero\n    eps = 1e-6\n\n    # Initialize a list to store batch data\n    batch_data = []\n\n    # Iterate over each path in the provided paths\n    for path in paths:\n        # Read data from parquet file\n        data = pd.read_parquet(path[0])\n\n        # Fill missing values, remove time column, and transpose\n        data = data.fillna(-1).values[:, 1:].T\n\n        # Clip values and apply logarithmic transformation\n        data = np.clip(data, np.exp(-6), np.exp(10))\n        data = np.log(data)\n\n        # Normalize the data\n        data_mean = data.mean(axis=(0, 1))\n        data_std = data.std(axis=(0, 1))\n        data = (data - data_mean) / (data_std + eps)\n\n        # Convert data to a PyTorch tensor and apply transformations\n        data_tensor = torch.unsqueeze(torch.Tensor(data), dim=0)\n        data = Config.image_transform(data_tensor)\n\n        # Append the processed data to the batch_data list\n        batch_data.append(data)\n\n    # Stack all the batch data into a single tensor\n    batch_data = torch.stack(batch_data)\n\n    # Return the batch data\n    return batch_data","metadata":{"papermill":{"duration":0.015617,"end_time":"2024-01-28T06:44:57.432829","exception":false,"start_time":"2024-01-28T06:44:57.417212","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2024-02-29T11:35:34.353166Z","iopub.execute_input":"2024-02-29T11:35:34.353458Z","iopub.status.idle":"2024-02-29T11:35:34.361108Z","shell.execute_reply.started":"2024-02-29T11:35:34.353434Z","shell.execute_reply":"2024-02-29T11:35:34.360258Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 🤖 Model Training","metadata":{"papermill":{"duration":0.003763,"end_time":"2024-01-28T06:44:57.440662","exception":false,"start_time":"2024-01-28T06:44:57.436899","status":"completed"},"tags":[]}},{"cell_type":"code","source":"# Determine device availability\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\nprint(f\"Using device: {device}\")\n\n# Assuming train_feats is defined and contains the training features and labels\ntotal_idx = np.arange(len(train_feats))\nnp.random.shuffle(total_idx)\n\ngc.collect()\n\n# Cross-validation loop\nfor fold in range(Config.num_folds):\n    # Split data into train and test sets for this fold\n    test_idx = total_idx[fold * len(total_idx) // Config.num_folds:(fold + 1) * len(total_idx) // Config.num_folds]\n    train_idx = np.array([idx for idx in total_idx if idx not in test_idx])\n\n    # Initialize EfficientNet-B1 model with pretrained weights\n    model = timm.create_model('efficientnet_b1', pretrained=True, num_classes=6, in_chans=1)\n    model.to(device)\n\n    optimizer = optim.AdamW(model.parameters(), lr=0.001, betas=(0.5, 0.999), weight_decay=0.01)\n    scheduler = CosineAnnealingLR(optimizer, T_max=Config.num_epochs)\n\n    best_test_loss = float('inf')\n    train_losses = []\n    test_losses = []\n\n    print(f\"Starting training for fold {fold + 1}\")\n\n    # Training loop\n    for epoch in range(Config.num_epochs):\n        model.train()\n        train_loss = []\n        random_num = np.arange(len(train_idx))\n        np.random.shuffle(random_num)\n        train_idx = train_idx[random_num]\n\n        # Iterate over batches in the training set\n        for idx in range(0, len(train_idx), Config.batch_size):\n            optimizer.zero_grad()\n            train_idx1 = train_idx[idx:idx + Config.batch_size]\n            train_X1_path = train_feats[['path']].iloc[train_idx1].values\n            train_X1 = get_batch(train_X1_path, batch_size=Config.batch_size)\n            train_y1 = train_feats[['seizure_vote', 'lpd_vote', 'gpd_vote', 'lrda_vote', 'grda_vote', 'other_vote']].iloc[train_idx1].values\n            train_y1 = torch.Tensor(train_y1)\n\n            train_pred = model(train_X1.to(device))\n            loss = KL_loss(train_y1.to(device), train_pred)\n            loss.backward()\n            optimizer.step()\n            train_loss.append(loss.item())\n\n        epoch_train_loss = np.mean(train_loss)\n        train_losses.append(epoch_train_loss)\n        print(f\"Epoch {epoch + 1}: Train Loss = {epoch_train_loss:.2f}\")\n\n        scheduler.step()\n\n        # Evaluation loop\n        model.eval()\n        test_loss = []\n        with torch.no_grad():\n            for idx in range(0, len(test_idx), Config.batch_size):\n                test_idx1 = test_idx[idx:idx + Config.batch_size]\n                test_X1_path = train_feats[['path']].iloc[test_idx1].values\n                test_X1 = get_batch(test_X1_path, batch_size=Config.batch_size)\n                test_y1 = train_feats[['seizure_vote', 'lpd_vote', 'gpd_vote', 'lrda_vote', 'grda_vote', 'other_vote']].iloc[test_idx1].values\n                test_y1 = torch.Tensor(test_y1)\n\n                test_pred = model(test_X1.to(device))\n                loss = KL_loss(test_y1.to(device), test_pred)\n                test_loss.append(loss.item())\n\n        epoch_test_loss = np.mean(test_loss)\n        test_losses.append(epoch_test_loss)\n        print(f\"Epoch {epoch + 1}: Test Loss = {epoch_test_loss:.2f}\")\n\n        # Save the model if it has the best test loss so far\n        if epoch_test_loss < best_test_loss:\n            best_test_loss = epoch_test_loss\n            torch.save(model.state_dict(), f\"efficientnet_b1_fold{fold}.pth\")\n\n        gc.collect()\n\n    print(f\"Fold {fold + 1} Best Test Loss: {best_test_loss:.2f}\")","metadata":{"papermill":{"duration":22310.196541,"end_time":"2024-01-28T12:56:47.64122","exception":false,"start_time":"2024-01-28T06:44:57.444679","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2024-02-29T11:35:34.362698Z","iopub.execute_input":"2024-02-29T11:35:34.363013Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}