{"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":30732,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Leash Tutorial - ECFPs and KNN Classifier\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 KNN Model. 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-06-25T02:05:52.582146Z","iopub.execute_input":"2024-06-25T02:05:52.582590Z","iopub.status.idle":"2024-06-25T02:06:11.795830Z","shell.execute_reply.started":"2024-06-25T02:05:52.582554Z","shell.execute_reply":"2024-06-25T02:06:11.794354Z"},"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-06-25T02:06:11.798302Z","iopub.execute_input":"2024-06-25T02:06:11.798697Z","iopub.status.idle":"2024-06-25T02:06:27.793579Z","shell.execute_reply.started":"2024-06-25T02:06:11.798658Z","shell.execute_reply":"2024-06-25T02:06:27.792023Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#constants\n\nTRAIN_LIMIT_BINDS = 1000\nTRAIN_LIMIT_NOT_BINDS = 1000","metadata":{"execution":{"iopub.status.busy":"2024-06-25T02:06:43.438796Z","iopub.execute_input":"2024-06-25T02:06:43.439187Z","iopub.status.idle":"2024-06-25T02:06:43.445207Z","shell.execute_reply.started":"2024-06-25T02:06:43.439155Z","shell.execute_reply":"2024-06-25T02:06:43.443861Z"},"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-BELKA/train.parquet'\ntest_path = '/kaggle/input/leash-BELKA/test.csv'\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 {TRAIN_LIMIT_NOT_BINDS})\n                        UNION ALL\n                        (SELECT *\n                        FROM parquet_scan('{train_path}')\n                        WHERE binds = 1\n                        ORDER BY random()\n                        LIMIT {TRAIN_LIMIT_BINDS})\"\"\").df()\n\ncon.close()","metadata":{"execution":{"iopub.status.busy":"2024-06-25T02:07:23.001569Z","iopub.execute_input":"2024-06-25T02:07:23.002415Z","iopub.status.idle":"2024-06-25T02:08:17.452876Z","shell.execute_reply.started":"2024-06-25T02:07:23.002377Z","shell.execute_reply":"2024-06-25T02:08:17.451781Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len(df)","metadata":{"execution":{"iopub.status.busy":"2024-06-25T02:09:16.366630Z","iopub.execute_input":"2024-06-25T02:09:16.367044Z","iopub.status.idle":"2024-06-25T02:09:16.374560Z","shell.execute_reply.started":"2024-06-25T02:09:16.367012Z","shell.execute_reply":"2024-06-25T02:09:16.373289Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.head()","metadata":{"execution":{"iopub.status.busy":"2024-06-25T02:09:18.521114Z","iopub.execute_input":"2024-06-25T02:09:18.521591Z","iopub.status.idle":"2024-06-25T02:09:18.547250Z","shell.execute_reply.started":"2024-06-25T02:09:18.521557Z","shell.execute_reply":"2024-06-25T02:09:18.546133Z"},"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-06-25T02:09:20.708506Z","iopub.execute_input":"2024-06-25T02:09:20.708915Z","iopub.status.idle":"2024-06-25T02:09:25.026811Z","shell.execute_reply.started":"2024-06-25T02:09:20.708882Z","shell.execute_reply":"2024-06-25T02:09:25.025564Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.head()","metadata":{"execution":{"iopub.status.busy":"2024-06-25T02:09:25.028707Z","iopub.execute_input":"2024-06-25T02:09:25.029072Z","iopub.status.idle":"2024-06-25T02:09:25.056045Z","shell.execute_reply.started":"2024-06-25T02:09:25.029042Z","shell.execute_reply":"2024-06-25T02:09:25.054843Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Train Model","metadata":{}},{"cell_type":"markdown","source":"### Prepare data","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)","metadata":{"execution":{"iopub.status.busy":"2024-06-25T02:09:36.891340Z","iopub.execute_input":"2024-06-25T02:09:36.891776Z","iopub.status.idle":"2024-06-25T02:09:36.956318Z","shell.execute_reply.started":"2024-06-25T02:09:36.891742Z","shell.execute_reply":"2024-06-25T02:09:36.954918Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Load KNN model","metadata":{}},{"cell_type":"code","source":"from sklearn.neighbors import KNeighborsClassifier\n\n# Create and train the random forest model\nknn_model = KNeighborsClassifier(n_neighbors=5)\nknn_model.fit(X_train, y_train)\n\n# Make predictions on the test set\ny_pred_proba = knn_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-06-25T02:10:52.782389Z","iopub.execute_input":"2024-06-25T02:10:52.782804Z","iopub.status.idle":"2024-06-25T02:10:53.130204Z","shell.execute_reply.started":"2024-06-25T02:10:52.782772Z","shell.execute_reply":"2024-06-25T02:10:53.128999Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Trying different k values","metadata":{}},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n# Function to calculate mAP for different values of k\ndef calculate_map_scores(k_values):\n    map_scores = []\n    for k in k_values:\n        knn_model = KNeighborsClassifier(n_neighbors=k)\n        knn_model.fit(X_train, y_train)\n        y_pred_proba = knn_model.predict_proba(X_test)[:, 1]  # Probability of the positive class\n        map_score = average_precision_score(y_test, y_pred_proba)\n        map_scores.append(map_score)\n    return map_scores\n\n# Define a range of k values\nk_values = range(1, 40)\n\n# Calculate mAP scores for the range of k values\nmap_scores = calculate_map_scores(k_values)\n\n# Plot the mAP scores\nplt.figure(figsize=(10, 6))\nplt.plot(k_values, map_scores, marker='o')\nplt.title('Mean Average Precision (mAP) Score vs. Number of Neighbors (k)')\nplt.xlabel('Number of Neighbors (k)')\nplt.ylabel('Mean Average Precision (mAP) Score')\nplt.xticks(k_values)\nplt.grid(True)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-06-25T02:15:09.957990Z","iopub.execute_input":"2024-06-25T02:15:09.958558Z","iopub.status.idle":"2024-06-25T02:15:23.788534Z","shell.execute_reply.started":"2024-06-25T02:15:09.958512Z","shell.execute_reply":"2024-06-25T02:15:23.787337Z"},"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-BELKA/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 = knn_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":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}