{"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":59093,"databundleVersionId":7469972,"sourceType":"competition"},{"sourceId":12161,"sourceType":"modelInstanceVersion","modelInstanceId":9865}],"dockerImageVersionId":30636,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"## 📙 Import libraries and modules","metadata":{}},{"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":{"execution":{"iopub.status.busy":"2024-02-27T23:06:32.634815Z","iopub.execute_input":"2024-02-27T23:06:32.635129Z","iopub.status.idle":"2024-02-27T23:06:37.590179Z","shell.execute_reply.started":"2024-02-27T23:06:32.635104Z","shell.execute_reply":"2024-02-27T23:06:37.589203Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## ⚙️ Configuration","metadata":{}},{"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":{"execution":{"iopub.status.busy":"2024-02-27T23:06:37.592092Z","iopub.execute_input":"2024-02-27T23:06:37.592780Z","iopub.status.idle":"2024-02-27T23:06:37.724451Z","shell.execute_reply.started":"2024-02-27T23:06:37.592745Z","shell.execute_reply":"2024-02-27T23:06:37.723540Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 📂 Data Loading","metadata":{}},{"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\ntrain_df","metadata":{"execution":{"iopub.status.busy":"2024-02-27T23:06:37.725611Z","iopub.execute_input":"2024-02-27T23:06:37.725951Z","iopub.status.idle":"2024-02-27T23:06:38.037806Z","shell.execute_reply.started":"2024-02-27T23:06:37.725919Z","shell.execute_reply":"2024-02-27T23:06:38.036852Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 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\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":{"execution":{"iopub.status.busy":"2024-02-27T23:06:38.039871Z","iopub.execute_input":"2024-02-27T23:06:38.040156Z","iopub.status.idle":"2024-02-27T23:06:38.216396Z","shell.execute_reply.started":"2024-02-27T23:06:38.040133Z","shell.execute_reply":"2024-02-27T23:06:38.215543Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Fix errors in labels\ntarget_mapping = {'seizure_vote': 'Seizure', 'lpd_vote': 'LPD', 'gpd_vote': 'GPD', 'lrda_vote': 'LRDA', 'grda_vote': 'GRDA', 'other_vote': 'Other'}\n\n# #Obtain the maximum label for each row\nvoto_maximo_columna = train_feats[['seizure_vote', 'lpd_vote', 'gpd_vote', 'lrda_vote', 'grda_vote', 'other_vote']].idxmax(axis=1)\n\n# Actualize column target\ntrain_feats['target'] = voto_maximo_columna.map(target_mapping)\n\ntrain_feats","metadata":{"execution":{"iopub.status.busy":"2024-02-27T23:06:38.217699Z","iopub.execute_input":"2024-02-27T23:06:38.217987Z","iopub.status.idle":"2024-02-27T23:06:38.244955Z","shell.execute_reply.started":"2024-02-27T23:06:38.217965Z","shell.execute_reply":"2024-02-27T23:06:38.244099Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from matplotlib import pyplot as plt\nplt.figure(figsize=(8, 6))\ntrain_feats['target'].value_counts().plot(kind='bar', color='skyblue')\nplt.title('Histograma de la columna \"target\"')\nplt.xlabel('Categoría')\nplt.ylabel('Frecuencia')\nplt.xticks(rotation=45)\nplt.show()\n\nprint(len(train_feats))\n\ntrain_feats = train_feats.drop('target', axis=1)","metadata":{"execution":{"iopub.status.busy":"2024-02-27T23:06:38.246067Z","iopub.execute_input":"2024-02-27T23:06:38.246353Z","iopub.status.idle":"2024-02-27T23:06:38.546305Z","shell.execute_reply.started":"2024-02-27T23:06:38.246331Z","shell.execute_reply":"2024-02-27T23:06:38.545471Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 🎰 Data Preprocessing","metadata":{}},{"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":{"execution":{"iopub.status.busy":"2024-02-27T23:06:38.547491Z","iopub.execute_input":"2024-02-27T23:06:38.547803Z","iopub.status.idle":"2024-02-27T23:06:38.555519Z","shell.execute_reply.started":"2024-02-27T23:06:38.547779Z","shell.execute_reply":"2024-02-27T23:06:38.554606Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 🤖 Model Training","metadata":{}},{"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 ResNet34d model with pretrained weights\n    # Define the model architecture\n    model = timm.create_model('resnet34d', pretrained=False, num_classes=6, in_chans=1)\n\n    # Load the pretrained weights from the specified path\n    model_path = \"/kaggle/input/pretrained-resnet/pytorch/pretrained/1/pretrained_resnet34d.pth\"\n    model.load_state_dict(torch.load(model_path, map_location=device))\n\n    # Move the model to the appropriate device\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\"resnet34d_fold{fold}.pth\")\n\n        gc.collect()\n\n    print(f\"Fold {fold + 1} Best Test Loss: {best_test_loss:.2f}\")","metadata":{"execution":{"iopub.status.busy":"2024-02-27T23:06:38.556782Z","iopub.execute_input":"2024-02-27T23:06:38.557062Z","iopub.status.idle":"2024-02-28T02:07:40.383579Z","shell.execute_reply.started":"2024-02-27T23:06:38.557039Z","shell.execute_reply":"2024-02-28T02:07:40.382453Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# device = 'cuda' if torch.cuda.is_available() else 'cpu'\n# model = timm.create_model('resnet34d', pretrained=True, num_classes=6, in_chans=1)\n# model.to(device)\n# torch.save(model.state_dict(), 'pretrained_resnet34d.pth')","metadata":{"execution":{"iopub.status.busy":"2024-02-28T02:07:40.384873Z","iopub.execute_input":"2024-02-28T02:07:40.385169Z","iopub.status.idle":"2024-02-28T02:07:40.389710Z","shell.execute_reply.started":"2024-02-28T02:07:40.385144Z","shell.execute_reply":"2024-02-28T02:07:40.388580Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}