{"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":"gpu","dataSources":[{"sourceId":38128,"databundleVersionId":4230952,"sourceType":"competition"}],"dockerImageVersionId":30732,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n        \n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-06-17T06:59:43.701472Z","iopub.execute_input":"2024-06-17T06:59:43.702186Z","iopub.status.idle":"2024-06-17T06:59:44.081951Z","shell.execute_reply.started":"2024-06-17T06:59:43.702157Z","shell.execute_reply":"2024-06-17T06:59:44.081068Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os, gc, pickle\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\nfrom colorama import Fore, Back, Style\nfrom matplotlib.ticker import MaxNLocator\nimport warnings\nwarnings.simplefilter('ignore')\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn.model_selection import KFold\nfrom sklearn.preprocessing import StandardScaler, scale\nfrom sklearn.decomposition import PCA\nfrom sklearn.dummy import DummyRegressor\nfrom sklearn.pipeline import make_pipeline, Pipeline\nfrom sklearn.linear_model import Ridge\nfrom sklearn.linear_model import Lasso\nfrom sklearn.multioutput import MultiOutputRegressor\nimport lightgbm as lgb\nfrom sklearn.compose import TransformedTargetRegressor\nfrom sklearn.metrics import mean_squared_error\n\nDATA_DIR = \"/kaggle/input/open-problems-multimodal/\"\nFP_CELL_METADATA = os.path.join(DATA_DIR,\"metadata.csv\")\n\nFP_CITE_TRAIN_INPUTS = os.path.join(DATA_DIR,\"train_cite_inputs.h5\")\nFP_CITE_TRAIN_TARGETS = os.path.join(DATA_DIR,\"train_cite_targets.h5\")\nFP_CITE_TEST_INPUTS = os.path.join(DATA_DIR,\"test_cite_inputs.h5\")\n\nFP_MULTIOME_TRAIN_INPUTS = os.path.join(DATA_DIR,\"train_multi_inputs.h5\")\nFP_MULTIOME_TRAIN_TARGETS = os.path.join(DATA_DIR,\"train_multi_targets.h5\")\nFP_MULTIOME_TEST_INPUTS = os.path.join(DATA_DIR,\"test_multi_inputs.h5\")\n\nFP_SUBMISSION = os.path.join(DATA_DIR,\"sample_submission.csv\")\nFP_EVALUATION_IDS = os.path.join(DATA_DIR,\"evaluation_ids.csv\")","metadata":{"execution":{"iopub.status.busy":"2024-06-17T06:59:44.142439Z","iopub.execute_input":"2024-06-17T06:59:44.143149Z","iopub.status.idle":"2024-06-17T06:59:48.067859Z","shell.execute_reply.started":"2024-06-17T06:59:44.143117Z","shell.execute_reply":"2024-06-17T06:59:48.066945Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install --quiet tables","metadata":{"execution":{"iopub.status.busy":"2024-06-17T06:59:48.069406Z","iopub.execute_input":"2024-06-17T06:59:48.069980Z","iopub.status.idle":"2024-06-17T07:00:01.007903Z","shell.execute_reply.started":"2024-06-17T06:59:48.069953Z","shell.execute_reply":"2024-06-17T07:00:01.006780Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_cell = pd.read_csv(FP_CELL_METADATA)\ndf_cell_cite = df_cell[df_cell.technology==\"citeseq\"]\ndf_cell_multi = df_cell[df_cell.technology==\"multiome\"]\ndf_cell_cite.shape, df_cell_multi.shape","metadata":{"execution":{"iopub.status.busy":"2024-06-17T07:00:01.009418Z","iopub.execute_input":"2024-06-17T07:00:01.009738Z","iopub.status.idle":"2024-06-17T07:00:01.576062Z","shell.execute_reply.started":"2024-06-17T07:00:01.009710Z","shell.execute_reply":"2024-06-17T07:00:01.575041Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n# Preprocessing\ncol_start = 10000\n\nclass PreprocessCiteseq(BaseEstimator, TransformerMixin):\n    columns_to_use = 13000\n    \n    @staticmethod\n    def take_column_subset(X):\n        return X[:,-(PreprocessCiteseq.columns_to_use+col_start):-col_start]\n    \n    def transform(self, X):\n        print(X.shape)\n        X = X[:,~self.all_zero_columns]\n        print(X.shape)\n        X = PreprocessCiteseq.take_column_subset(X) # use only a part of the columns\n        print(X.shape)\n        gc.collect()\n\n        X = self.pca.transform(X)\n        print(X.shape)\n        return X\n\n    def fit_transform(self, X):\n        gc.collect()\n        print(X.shape)\n        self.all_zero_columns = (X == 0).all(axis=0)\n        X = X[:,~self.all_zero_columns]\n        print(X.shape)\n        X = PreprocessCiteseq.take_column_subset(X) # use only a part of the columns\n        print(X.shape)\n        gc.collect()\n\n        self.pca = PCA(n_components=100, copy=False, random_state=1)\n        X = self.pca.fit_transform(X)\n#         plt.plot(self.pca.explained_variance_ratio_.cumsum())\n#         plt.title(\"Cumulative explained variance ratio\")\n#         plt.gca().xaxis.set_major_locator(MaxNLocator(integer=True))\n#         plt.xlabel('PCA component')\n#         plt.ylabel('Cumulative explained variance ratio')\n#         plt.show()\n        print(X.shape)\n        return X\n\npreprocessor = PreprocessCiteseq()\n\ncite_train_x = None\ncite_train_x = preprocessor.fit_transform(pd.read_hdf(FP_CITE_TRAIN_INPUTS).values)\n\ncite_train_y = pd.read_hdf(FP_CITE_TRAIN_TARGETS).values\nprint(cite_train_y.shape)\n\ncite_test_x = preprocessor.fit_transform(pd.read_hdf(FP_CITE_TEST_INPUTS).values)\nprint(cite_test_x.shape)","metadata":{"execution":{"iopub.status.busy":"2024-06-17T07:00:01.578276Z","iopub.execute_input":"2024-06-17T07:00:01.578558Z","iopub.status.idle":"2024-06-17T07:02:25.350015Z","shell.execute_reply.started":"2024-06-17T07:00:01.578534Z","shell.execute_reply":"2024-06-17T07:02:25.349094Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pip install lightgbm xgboost catboost scikit-learn ","metadata":{"execution":{"iopub.status.busy":"2024-06-17T07:02:25.351211Z","iopub.execute_input":"2024-06-17T07:02:25.351508Z","iopub.status.idle":"2024-06-17T07:02:37.699518Z","shell.execute_reply.started":"2024-06-17T07:02:25.351470Z","shell.execute_reply":"2024-06-17T07:02:37.698238Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import r2_score","metadata":{"execution":{"iopub.status.busy":"2024-06-17T07:02:37.701076Z","iopub.execute_input":"2024-06-17T07:02:37.701413Z","iopub.status.idle":"2024-06-17T07:02:37.707349Z","shell.execute_reply.started":"2024-06-17T07:02:37.701382Z","shell.execute_reply":"2024-06-17T07:02:37.706277Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from catboost import CatBoostRegressor\nfrom sklearn.multioutput import MultiOutputRegressor\nfrom sklearn.metrics import r2_score, mean_squared_error\nimport gc\n\n# Function to train and evaluate a model\ndef train_and_evaluate_model(model, train_x, train_y):\n    model.fit(train_x, train_y)\n    y_pred = model.predict(train_x)\n    r2_scores = r2_score(train_y, y_pred, multioutput='raw_values')\n    mse_scores = mean_squared_error(train_y, y_pred, multioutput='raw_values')\n    r2_total = r2_score(train_y, y_pred)\n    mse_total = mean_squared_error(train_y, y_pred)\n    return r2_scores, r2_total, mse_scores, mse_total, model\n\n# Define CatBoost parameters\nparams = {\n    'iterations': 1000,             # equivalent to n_estimators\n    'learning_rate': 0.1,\n    'random_seed': 42,\n    'l2_leaf_reg': 0.2,             # regularization parameter\n    'depth': 10,                    # equivalent to max_depth\n    'rsm': 0.8,                     # equivalent to colsample_bytree\n    'subsample': 0.5,\n    'min_data_in_leaf': 83,         # equivalent to min_child_samples\n    'bagging_temperature': 1,       # bagging parameter\n    'random_strength': 1,           # used to control the amount of randomness\n    'one_hot_max_size': 2,          # for categorical features\n    'leaf_estimation_method': 'Newton', # estimation method for leaf values\n}\n# Initialize CatBoost regressor\ncatboost_model = CatBoostRegressor(**params)\n\n# Wrap CatBoost model in MultiOutputRegressor for multi-output support\nmulti_output_catboost = MultiOutputRegressor(catboost_model)\n\nprint('Training CatBoost model with MultiOutputRegressor...')\nr2_scores, r2_total, mse_scores, mse_total, trained_model = train_and_evaluate_model(multi_output_catboost, cite_train_x, cite_train_y)\n\n# Print R2 scores and MSE for each target\nfor i, r2 in enumerate(r2_scores):\n    print(f'R^2 Score for Target {i}: {r2}')\n    print(f'MSE for Target {i}: {mse_scores[i]}')\n\nprint('R^2 score total:', r2_total)\nprint('MSE total :', mse_total)\n\n# Clean up to free memory\ngc.collect()\n","metadata":{"execution":{"iopub.status.busy":"2024-06-17T07:02:37.708487Z","iopub.execute_input":"2024-06-17T07:02:37.708779Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Hello World\")","metadata":{"execution":{"iopub.status.busy":"2024-06-17T06:59:35.262372Z","iopub.execute_input":"2024-06-17T06:59:35.263171Z","iopub.status.idle":"2024-06-17T06:59:35.275744Z","shell.execute_reply.started":"2024-06-17T06:59:35.263138Z","shell.execute_reply":"2024-06-17T06:59:35.274782Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}