{"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":"none","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":"import os\n\n# Set the path to the Kaggle input directory\nkaggle_input_dir = \"/kaggle/input\"\n\n# Function to list all files in the directory\ndef list_files(directory):\n    for root, dirs, files in os.walk(directory):\n        for file in files:\n            print(os.path.join(root, file))\n\n# List all files in the Kaggle input directory\nlist_files(kaggle_input_dir)\n","metadata":{"execution":{"iopub.status.busy":"2024-05-20T10:15:31.149733Z","iopub.execute_input":"2024-05-20T10:15:31.150113Z","iopub.status.idle":"2024-05-20T10:15:31.189690Z","shell.execute_reply.started":"2024-05-20T10:15:31.150081Z","shell.execute_reply":"2024-05-20T10:15:31.188539Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Leash Tutorial - ECFPs and Random Forest\n## Introduction\n\nThere are many ways to represent molecules for machine learning. \n\nIn this tutorial we will go through one of the simplest: ECFPs [[1]](https://pubs.acs.org/doi/10.1021/ci100050t) and Random Forest. This technique is surprisingly powerful, and on previous benchmarks often gets uncomfortably close to the state of the art.\n\nFirst molecule graphs are broken into bags of subgraphs of varying sizes.\n\n![ecfp featurizing process (chemaxon)](https://docs.chemaxon.com/display/docs/images/download/attachments/1806333/ecfp_generation.png)\n\nThen the bag of subgraphs is hashed into a bit vector\n\n![hashing process (chemaxon)](https://docs.chemaxon.com/display/docs/images/download/attachments/1806333/ecfp_folding.png)\n\nThis can be thought of as analogous to the [hashing trick](https://en.wikipedia.org/wiki/Feature_hashing) [[2]](https://alex.smola.org/papers/2009/Weinbergeretal09.pdf) on bag of words for NLP problems, from the days before transformers. \n\nRDKit, an open-source cheminformatics tool, is used for generating ECFP features. It facilitates the creation of hashed bit vectors, streamlining the process. We can install it as follows:","metadata":{}},{"cell_type":"code","source":"!pip install rdkit ","metadata":{"execution":{"iopub.status.busy":"2024-05-20T10:15:31.191214Z","iopub.execute_input":"2024-05-20T10:15:31.191526Z","iopub.status.idle":"2024-05-20T10:15:46.801685Z","shell.execute_reply.started":"2024-05-20T10:15:31.191501Z","shell.execute_reply":"2024-05-20T10:15:46.800299Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"The training set is pretty big, but we can treat the parquet files as databases using duckdb. We will use this to sample down to a smaller dataset for demonstration purposes. Lets install duckdb as well.","metadata":{}},{"cell_type":"code","source":"!pip install duckdb","metadata":{"execution":{"iopub.status.busy":"2024-05-20T10:15:46.803689Z","iopub.execute_input":"2024-05-20T10:15:46.804134Z","iopub.status.idle":"2024-05-20T10:15:59.885844Z","shell.execute_reply.started":"2024-05-20T10:15:46.804096Z","shell.execute_reply":"2024-05-20T10:15:59.884699Z"},"trusted":true},"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 30000)\n                        UNION ALL\n                        (SELECT *\n                        FROM parquet_scan('{train_path}')\n                        WHERE binds = 1\n                        ORDER BY random()\n                        LIMIT 30000)\"\"\").df()\n\ncon.close()","metadata":{"execution":{"iopub.status.busy":"2024-05-20T10:15:59.889022Z","iopub.execute_input":"2024-05-20T10:15:59.889459Z","iopub.status.idle":"2024-05-20T10:16:50.878268Z","shell.execute_reply.started":"2024-05-20T10:15:59.889420Z","shell.execute_reply":"2024-05-20T10:16:50.877378Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.head()","metadata":{"execution":{"iopub.status.busy":"2024-05-20T10:16:50.879902Z","iopub.execute_input":"2024-05-20T10:16:50.881063Z","iopub.status.idle":"2024-05-20T10:16:50.898792Z","shell.execute_reply.started":"2024-05-20T10:16:50.881028Z","shell.execute_reply":"2024-05-20T10:16:50.897764Z"},"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.ensemble import RandomForestClassifier\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-20T10:16:50.900034Z","iopub.execute_input":"2024-05-20T10:16:50.900321Z","iopub.status.idle":"2024-05-20T10:18:15.014688Z","shell.execute_reply.started":"2024-05-20T10:16:50.900298Z","shell.execute_reply":"2024-05-20T10:18:15.013026Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.head(2)","metadata":{"execution":{"iopub.status.busy":"2024-05-20T10:18:15.016497Z","iopub.execute_input":"2024-05-20T10:18:15.017505Z","iopub.status.idle":"2024-05-20T10:18:15.039028Z","shell.execute_reply.started":"2024-05-20T10:18:15.017458Z","shell.execute_reply":"2024-05-20T10:18:15.037806Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"all_blocks = pd.concat([df.buildingblock1_smiles, df.buildingblock2_smiles, df.buildingblock3_smiles])\n\nall_blocks.value_counts().head(20)","metadata":{"execution":{"iopub.status.busy":"2024-05-20T10:18:49.095314Z","iopub.execute_input":"2024-05-20T10:18:49.095703Z","iopub.status.idle":"2024-05-20T10:18:49.129505Z","shell.execute_reply.started":"2024-05-20T10:18:49.095675Z","shell.execute_reply":"2024-05-20T10:18:49.127995Z"},"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.2, random_state=42)\n\n# Create and train the random forest model\nrf_model = RandomForestClassifier(n_estimators=100, random_state=42)\nrf_model.fit(X_train, y_train)\n\n# Make predictions on the test set\ny_pred_proba = rf_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-20T10:18:15.450888Z","iopub.status.idle":"2024-05-20T10:18:15.451704Z","shell.execute_reply.started":"2024-05-20T10:18:15.451418Z","shell.execute_reply":"2024-05-20T10:18:15.451442Z"},"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 = rf_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-20T10:18:15.453191Z","iopub.status.idle":"2024-05-20T10:18:15.453972Z","shell.execute_reply.started":"2024-05-20T10:18:15.453685Z","shell.execute_reply":"2024-05-20T10:18:15.453708Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}