{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","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"},"kaggle":{"accelerator":"tpu1vmV38","dataSources":[{"sourceId":67356,"databundleVersionId":8006601,"sourceType":"competition"}],"dockerImageVersionId":30673,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"!pip install rdkit","metadata":{"execution":{"iopub.status.busy":"2024-05-31T12:12:27.628056Z","iopub.execute_input":"2024-05-31T12:12:27.628478Z","iopub.status.idle":"2024-05-31T12:12:46.662712Z","shell.execute_reply.started":"2024-05-31T12:12:27.628441Z","shell.execute_reply":"2024-05-31T12:12:46.661419Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install duckdb","metadata":{"execution":{"iopub.status.busy":"2024-05-31T12:12:46.665278Z","iopub.execute_input":"2024-05-31T12:12:46.665629Z","iopub.status.idle":"2024-05-31T12:13:02.688115Z","shell.execute_reply.started":"2024-05-31T12:12:46.665599Z","shell.execute_reply":"2024-05-31T12:13:02.686895Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install catboost","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Data Preparation\n\nThe training and testing data paths are defined for the .parquet files. We use duckdb to scan search through the large training sets. Just to get started lets sample out an equal number of positive and negatives. \n\nThis query selects an equal number of samples where binds equals 0 (non-binding) and 1 (binding), limited to 30,000 each, to avoid model bias towards a particular class.","metadata":{}},{"cell_type":"code","source":"import duckdb\nimport pandas as pd\n\ntrain_path = '/kaggle/input/leash-predict-chemical-bindings/train.parquet'\ntest_path = '/kaggle/input/leash-predict-chemical-bindings/test.parquet'\n\ncon = duckdb.connect()\n\ndf = con.query(f\"\"\"(SELECT *\n                        FROM parquet_scan('{train_path}')\n                        WHERE binds = 0\n                        ORDER BY random()\n                        LIMIT 2000000)\n                        UNION ALL\n                        (SELECT *\n                        FROM parquet_scan('{train_path}')\n                        WHERE binds = 1\n                        ORDER BY random()\n                        LIMIT 2000000)\"\"\").df()\n\ncon.close()","metadata":{"execution":{"iopub.status.busy":"2024-05-31T12:13:05.516512Z","iopub.execute_input":"2024-05-31T12:13:05.516942Z","iopub.status.idle":"2024-05-31T12:14:03.969915Z","shell.execute_reply.started":"2024-05-31T12:13:05.516908Z","shell.execute_reply":"2024-05-31T12:14:03.968872Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.head()","metadata":{"execution":{"iopub.status.busy":"2024-05-31T12:14:12.088670Z","iopub.execute_input":"2024-05-31T12:14:12.089959Z","iopub.status.idle":"2024-05-31T12:14:12.110798Z","shell.execute_reply.started":"2024-05-31T12:14:12.089915Z","shell.execute_reply":"2024-05-31T12:14:12.109685Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Feature Preprocessing\n\nLets grab the smiles for the fully assembled molecule `molecule_smiles` and generate ecfps for it. We could choose different radiuses or bits, but 2 and 1024 is pretty standard.","metadata":{}},{"cell_type":"code","source":"from rdkit import Chem\nfrom rdkit.Chem import AllChem\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import average_precision_score\nfrom sklearn.preprocessing import OneHotEncoder\n\n# Convert SMILES to RDKit molecules\ndf['molecule'] = df['molecule_smiles'].apply(Chem.MolFromSmiles)\n\n# Generate ECFPs\ndef generate_ecfp(molecule, radius=2, bits=1024):\n    if molecule is None:\n        return None\n    return list(AllChem.GetMorganFingerprintAsBitVect(molecule, radius, nBits=bits))\n\ndf['ecfp'] = df['molecule'].apply(generate_ecfp)","metadata":{"execution":{"iopub.status.busy":"2024-05-31T12:14:15.071167Z","iopub.execute_input":"2024-05-31T12:14:15.071564Z","iopub.status.idle":"2024-05-31T12:14:16.958948Z","shell.execute_reply.started":"2024-05-31T12:14:15.071530Z","shell.execute_reply":"2024-05-31T12:14:16.957861Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Train Model","metadata":{}},{"cell_type":"code","source":"# One-hot encode the protein_name\nonehot_encoder = OneHotEncoder(sparse_output=False)\nprotein_onehot = onehot_encoder.fit_transform(df['protein_name'].values.reshape(-1, 1))\n\n# Combine ECFPs and one-hot encoded protein_name\nX = [ecfp + protein for ecfp, protein in zip(df['ecfp'].tolist(), protein_onehot.tolist())]\ny = df['binds'].tolist()\n\n# Split the data into train and test sets\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)","metadata":{"execution":{"iopub.status.busy":"2024-05-31T12:14:21.117188Z","iopub.execute_input":"2024-05-31T12:14:21.117623Z","iopub.status.idle":"2024-05-31T12:14:21.135412Z","shell.execute_reply.started":"2024-05-31T12:14:21.117587Z","shell.execute_reply":"2024-05-31T12:14:21.133887Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.head()","metadata":{"execution":{"iopub.status.busy":"2024-05-31T12:14:23.392570Z","iopub.execute_input":"2024-05-31T12:14:23.392964Z","iopub.status.idle":"2024-05-31T12:14:23.415102Z","shell.execute_reply.started":"2024-05-31T12:14:23.392935Z","shell.execute_reply":"2024-05-31T12:14:23.413668Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Best Score received with CatBoostClassifier","metadata":{}},{"cell_type":"code","source":"from catboost import CatBoostClassifier\ncatb_model = CatBoostClassifier().fit(X_train, y_train)\ny_pred_proba = catb_model.predict_proba(X_test)[:, 1]  # Probability of the positive class\n\n# Calculate the mean average precision\nmap_score = average_precision_score(y_test, y_pred_proba)\nprint(f\"Mean Average Precision (mAP): {map_score:.2f}\")","metadata":{"execution":{"iopub.status.busy":"2024-05-31T12:14:27.599254Z","iopub.execute_input":"2024-05-31T12:14:27.599660Z","iopub.status.idle":"2024-05-31T12:14:31.352156Z","shell.execute_reply.started":"2024-05-31T12:14:27.599631Z","shell.execute_reply":"2024-05-31T12:14:31.350954Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Look at that Average Precision score. We did amazing! \n\nActually no, we just overfit. This is likely recurring theme for this competition. It is easy to predict molecules that come from the same corner of chemical space, but generalizing to new molecules is extremely difficult.","metadata":{}},{"cell_type":"markdown","source":"## Test Prediction\n\n The trained Random Forest model is then used to predict the binding probabilities. These predictions are saved to a CSV file, which serves as the submission file for the Kaggle competition.","metadata":{}},{"cell_type":"code","source":"import os\n\n# Process the test.parquet file chunk by chunk\ntest_file = '/kaggle/input/leash-predict-chemical-bindings/test.csv'\noutput_file = 'submission.csv'  # Specify the path and filename for the output file\n\n# Read the test.parquet file into a pandas DataFrame\nfor df_test in pd.read_csv(test_file, chunksize=100000):\n\n    # Generate ECFPs for the molecule_smiles\n    df_test['molecule'] = df_test['molecule_smiles'].apply(Chem.MolFromSmiles)\n    df_test['ecfp'] = df_test['molecule'].apply(generate_ecfp)\n\n    # One-hot encode the protein_name\n    protein_onehot = onehot_encoder.transform(df_test['protein_name'].values.reshape(-1, 1))\n\n    # Combine ECFPs and one-hot encoded protein_name\n    X_test = [ecfp + protein for ecfp, protein in zip(df_test['ecfp'].tolist(), protein_onehot.tolist())]\n\n    # Predict the probabilities\n    probabilities = catb_model.predict_proba(X_test)[:, 1]\n\n    # Create a DataFrame with 'id' and 'probability' columns\n    output_df = pd.DataFrame({'id': df_test['id'], 'binds': probabilities})\n\n    # Save the output DataFrame to a CSV file\n    output_df.to_csv(output_file, index=False, mode='a', header=not os.path.exists(output_file))\n","metadata":{"execution":{"iopub.status.busy":"2024-05-31T12:14:38.441917Z","iopub.execute_input":"2024-05-31T12:14:38.442337Z"},"trusted":true},"execution_count":null,"outputs":[]}]}