{"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":116062,"databundleVersionId":14875579,"sourceType":"competition"},{"sourceId":14679913,"sourceType":"datasetVersion","datasetId":9335429},{"sourceId":292870115,"sourceType":"kernelVersion"}],"dockerImageVersionId":31154,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import torch\nimport torch.nn as nn\nimport numpy as np\nimport pandas as pd\nfrom tqdm.auto import tqdm\nfrom torch.utils.data import DataLoader\n\n# ==========================================\n# CONFIGURATION\n# ==========================================\nDEVICE = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nMODEL_PATH = \"/kaggle/input/train-npy/cafa6_resnet_focal.pth\"\nTARGET_TERMS_PATH = \"/kaggle/input/train-npy/target_terms.npy\" \nSUBMISSION_OUTPUT = \"submission.tsv\"\nBATCH_SIZE = 512\nMIN_SCORE = 0.001 \n\n# ==========================================\n# 1. DEFINE RESNET ARCHITECTURE (Must match training)\n# ==========================================\nclass ResidualBlock(nn.Module):\n    def __init__(self, dim, dropout=0.3):\n        super().__init__()\n        self.block = nn.Sequential(\n            nn.Linear(dim, dim),\n            nn.BatchNorm1d(dim),\n            nn.ReLU(),\n            nn.Dropout(dropout),\n            nn.Linear(dim, dim),\n            nn.BatchNorm1d(dim)\n        )\n        self.relu = nn.ReLU()\n        \n    def forward(self, x):\n        residual = x\n        out = self.block(x)\n        out += residual\n        return self.relu(out)\n\nclass ProteinResNet(nn.Module):\n    def __init__(self, input_dim, output_dim):\n        super().__init__()\n        self.entry = nn.Sequential(\n            nn.Linear(input_dim, 1024),\n            nn.BatchNorm1d(1024),\n            nn.ReLU()\n        )\n        self.res1 = ResidualBlock(1024)\n        self.res2 = ResidualBlock(1024)\n        self.res3 = ResidualBlock(1024)\n        self.head = nn.Sequential(\n            nn.Linear(1024, 512),\n            nn.ReLU(),\n            nn.Linear(512, output_dim)\n        )\n        \n    def forward(self, x):\n        x = self.entry(x)\n        x = self.res1(x)\n        x = self.res2(x)\n        x = self.res3(x)\n        return self.head(x)\n\n# ==========================================\n# 2. RUN INFERENCE\n# ==========================================\ndef generate_resnet_submission(test_ids, test_embeddings):\n    print(\"1. Loading Metadata...\")\n    target_terms = np.load(TARGET_TERMS_PATH, allow_pickle=True)\n    num_classes = len(target_terms)\n    \n    print(f\"2. Loading ResNet Model from {MODEL_PATH}...\")\n    model = ProteinResNet(input_dim=1280, output_dim=num_classes).to(DEVICE)\n    model.load_state_dict(torch.load(MODEL_PATH))\n    model.eval()\n    \n    # DataLoader (num_workers=0 to prevent the 'child process' error)\n    test_tensor = torch.tensor(test_embeddings, dtype=torch.float32)\n    test_loader = DataLoader(test_tensor, batch_size=BATCH_SIZE, shuffle=False, num_workers=0)\n    \n    print(f\"3. Predicting on {len(test_ids)} proteins...\")\n    \n    with open(SUBMISSION_OUTPUT, 'w') as f:\n        batch_start_idx = 0\n        with torch.no_grad():\n            for batch_x in tqdm(test_loader):\n                batch_x = batch_x.to(DEVICE)\n                \n                # Forward Pass\n                logits = model(batch_x)\n                probs = torch.sigmoid(logits)\n                probs = probs.cpu().numpy()\n                \n                # Write to file\n                for i, protein_probs in enumerate(probs):\n                    pid = test_ids[batch_start_idx + i]\n                    \n                    # Filter low scores\n                    valid_indices = np.where(protein_probs >= MIN_SCORE)[0]\n                    for idx in valid_indices:\n                        f.write(f\"{pid}\\t{target_terms[idx]}\\t{protein_probs[idx]:.3f}\\n\")\n                \n                batch_start_idx += len(batch_x)\n                \n    print(f\"Done! Raw ResNet predictions saved to {SUBMISSION_OUTPUT}\")\n\n# Run It\nif 'test_ids' in locals() and 'test_embeddings' in locals():\n    generate_resnet_submission(test_ids, test_embeddings)\nelse:\n    print(\"Error: test_ids and test_embeddings are missing from memory.\")\n    print(\"Please re-run the extraction step or load them if you saved them to disk.\")","metadata":{"trusted":true,"execution":{"execution_failed":"2026-01-30T18:25:23.224Z"}},"outputs":[],"execution_count":null}]}