{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# What is about ?\n\n### Briefly - downsample and make quick experiments\n\nHere we will downsample the data. I.e. select 10% of data as a kind of \"Playground\" - for quick experiments. \nAnd will train/tune different models on that playground first.\n\n\n### About CV scheme\n\nPublic and private test sets are quite different. (Private - contains new DAY (and donor), while public ONLY new donor).\nSo one should be careful with the validation schemes.\nSome proposals are described here: \n\nNotebook: https://www.kaggle.com/code/alexandervc/mmscel-crossvalidation-schemes\nTopic: https://www.kaggle.com/competitions/open-problems-multimodal/discussion/358860\n\nWe will be based on them. \n\n### Start with selection of \"Playground\" - 10% part of data - to quickly test models, ideas\n\nData is quite big, and so training models, tuning params might take long time. That is not always affordable.\nIn the present script we first choose some 10% part of data - to make quick experiments.\nThat part is chosen to have SAME proporitions of key characteristics: donors, days, cell types as the initial data\n\nSo we can create CV scheme for that \"playground\" part.\nBut we can also simplify even further - for start - use  not 6-fold scheme but just splite by days. And have only 1 train subset for quick experiments. \n\nTo simplify even further we can start play with just one target only. \n","metadata":{}},{"cell_type":"code","source":"tune_RF = False # True # Takes 4 minutes for 6 params ","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:11:29.154237Z","iopub.execute_input":"2022-11-07T10:11:29.154775Z","iopub.status.idle":"2022-11-07T10:11:29.159624Z","shell.execute_reply.started":"2022-11-07T10:11:29.154735Z","shell.execute_reply":"2022-11-07T10:11:29.158762Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Install/import modules, load technical data\n","metadata":{}},{"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# 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":"2022-11-07T10:11:29.165199Z","iopub.execute_input":"2022-11-07T10:11:29.166293Z","iopub.status.idle":"2022-11-07T10:11:29.186597Z","shell.execute_reply.started":"2022-11-07T10:11:29.166247Z","shell.execute_reply":"2022-11-07T10:11:29.185257Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import time\nt0start = time.time()\n\nimport pandas as pd\nimport numpy as np\nimport os\nimport sys\n\nimport matplotlib.pyplot as plt\n#plt.style.use('dark_background')\nimport seaborn as sns\n\n#If you see a urllib warning running this cell, go to \"Settings\" on the right hand side, \n#and turn on internet. Note, you need to be phone verified.\n!pip install --quiet tables\n\n\nimport h5py\n!pip install hdf5plugin~=2.0 # https://forum.hdfgroup.org/t/cant-open-directory-usr-local-hdf5-lib-plugin/9738/4\nimport hdf5plugin\n\n# !pip install scanpy\n# import scanpy as sc\n# import anndata\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\")\n\ndf_cell = pd.read_csv(FP_CELL_METADATA)\ndf_cell","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:11:29.188824Z","iopub.execute_input":"2022-11-07T10:11:29.190561Z","iopub.status.idle":"2022-11-07T10:11:52.363799Z","shell.execute_reply.started":"2022-11-07T10:11:29.190454Z","shell.execute_reply":"2022-11-07T10:11:52.362262Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import time\nt0start = time.time()\n\nimport pandas as pd\nimport numpy as np\nimport os\nimport sys\n\nimport matplotlib.pyplot as plt\n#plt.style.use('dark_background')\nimport seaborn as sns\n\n#If you see a urllib warning running this cell, go to \"Settings\" on the right hand side, \n#and turn on internet. Note, you need to be phone verified.\n!pip install --quiet tables\n\n\nimport h5py\n!pip install hdf5plugin~=2.0 # https://forum.hdfgroup.org/t/cant-open-directory-usr-local-hdf5-lib-plugin/9738/4\nimport hdf5plugin\n\n# !pip install scanpy\n# import scanpy as sc\n# import anndata\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\")\n\ndf_cell = pd.read_csv(FP_CELL_METADATA)\ndf_cell","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:11:52.366536Z","iopub.execute_input":"2022-11-07T10:11:52.367058Z","iopub.status.idle":"2022-11-07T10:12:15.065962Z","shell.execute_reply.started":"2022-11-07T10:11:52.366996Z","shell.execute_reply":"2022-11-07T10:12:15.064492Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Load prepared Features for CITE-seq part of task","metadata":{}},{"cell_type":"code","source":"%%time\n\nprint('Load prepared features for CITE-seq')\n# These files contain both train and test parts .\n# For CITEseq part - first 70988 elements - train, and later 48663 - test. Overall 119651 samples.\n# fn = '/kaggle/input/feature-shop-for-multimodal-singlecell-competition/citeseq_train_and_test_TruncatedSVD200_niter7_rs42.csv'\nfn = '/kaggle/input/feature-shop-for-multimodal-singlecell-competition/citeseq_train_and_test_PCA500.csv'\ndf_cite = pd.read_csv(fn,index_col = 0)\ndisplay(df_cite)\n","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:15.068617Z","iopub.execute_input":"2022-11-07T10:12:15.069028Z","iopub.status.idle":"2022-11-07T10:12:35.461124Z","shell.execute_reply.started":"2022-11-07T10:12:15.068989Z","shell.execute_reply":"2022-11-07T10:12:35.459769Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_cite.mean(axis = 0)","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:35.462701Z","iopub.execute_input":"2022-11-07T10:12:35.463109Z","iopub.status.idle":"2022-11-07T10:12:35.637330Z","shell.execute_reply.started":"2022-11-07T10:12:35.463074Z","shell.execute_reply":"2022-11-07T10:12:35.635932Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_cite.std(axis=0)","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:35.639371Z","iopub.execute_input":"2022-11-07T10:12:35.639732Z","iopub.status.idle":"2022-11-07T10:12:36.344704Z","shell.execute_reply.started":"2022-11-07T10:12:35.639699Z","shell.execute_reply":"2022-11-07T10:12:36.343474Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Load Targets for CITE-seq","metadata":{}},{"cell_type":"code","source":"%%time\n#if 1:\nprint('Load CITE-seq targets and ')\ndf_cite_train_y = pd.read_hdf(FP_CITE_TRAIN_TARGETS)\ndisplay(df_cite_train_y)","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:36.346843Z","iopub.execute_input":"2022-11-07T10:12:36.347357Z","iopub.status.idle":"2022-11-07T10:12:37.182235Z","shell.execute_reply.started":"2022-11-07T10:12:36.347304Z","shell.execute_reply":"2022-11-07T10:12:37.181205Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Load and start prepare some metadata (cut only CITE-seq train part)","metadata":{}},{"cell_type":"code","source":"%%time\nfn2 = '/kaggle/input/feature-shop-for-multimodal-singlecell-competition/_citeseq_meta_all_text_also.csv'\ndf_meta_full = pd.read_csv(fn2,index_col = 0)\ndisplay(df_meta_full)\n#if 1:\ndf_meta = pd.DataFrame(index = df_cite_train_y.index) \ndf_meta = df_meta.join(df_cell.set_index('cell_id') )\ndisplay(df_meta)","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:37.183681Z","iopub.execute_input":"2022-11-07T10:12:37.184626Z","iopub.status.idle":"2022-11-07T10:12:37.615743Z","shell.execute_reply.started":"2022-11-07T10:12:37.184580Z","shell.execute_reply":"2022-11-07T10:12:37.614384Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Create \"Playground\"  (i.e. downsample)\n\nSmall 10% of data of data where we can make prelimanary experiments. \n\nit will be labeled by special column \"Playground\" in df_meta (meta data for CITE-seq train only)","metadata":{}},{"cell_type":"code","source":"# Prepare for creation of additional holdout folds with 10% of samples \n# We will use stratified Kfold to achieve that days, cell_types and donors are equally distributed \nimport numpy as np\nfrom sklearn.model_selection import StratifiedKFold\nscol = 'donor&day&CT'\ndf_meta[scol] =df_meta['donor'].apply(lambda x:str(x)+'_') + df_meta['day'].apply(lambda x:str(x)+'_') + df_meta['cell_type']\n\n\nskf = StratifiedKFold(n_splits=10,  shuffle=True, random_state=40)\nskf.get_n_splits(df_meta, df_meta[scol] )\n\n\n\ny = df_meta[scol] \nfor train_index, test_index in skf.split(df_meta, df_meta[scol]):\n    print(\"TRAIN:\", len(train_index), \"TEST:\", len(test_index) ); \n    break\nprint(test_index)\nprint(df_meta[scol].value_counts().head(5)   )\nprint(df_meta.iloc[test_index,:][scol].value_counts().head(5)    )\n\n\nflagged_column_name = 'Playground'\ndf_meta[flagged_column_name] = 0 \ndf_meta.loc[df_meta.index[test_index],flagged_column_name]  = 1\ndf_meta","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:37.620771Z","iopub.execute_input":"2022-11-07T10:12:37.621181Z","iopub.status.idle":"2022-11-07T10:12:37.984842Z","shell.execute_reply.started":"2022-11-07T10:12:37.621143Z","shell.execute_reply":"2022-11-07T10:12:37.983593Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Modeling Preparations","metadata":{}},{"cell_type":"code","source":"from sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import r2_score","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:37.986594Z","iopub.execute_input":"2022-11-07T10:12:37.987852Z","iopub.status.idle":"2022-11-07T10:12:37.993596Z","shell.execute_reply.started":"2022-11-07T10:12:37.987802Z","shell.execute_reply":"2022-11-07T10:12:37.992305Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_models_stat = pd.DataFrame()# columns = [ 'r2_score','mse','Time',  'n_feat', 'Target' ])\n#IXmdl = 0\ndf_models_stat","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:37.995748Z","iopub.execute_input":"2022-11-07T10:12:37.996219Z","iopub.status.idle":"2022-11-07T10:12:38.012131Z","shell.execute_reply.started":"2022-11-07T10:12:37.996173Z","shell.execute_reply":"2022-11-07T10:12:38.010876Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dict_save_predictions = {}\ndef update_models_stat(model, model_ID, t0 ):\n    \n    IXmdl = model_ID # df_models_stat.shape[0] + 1\n    #df_models_stat.loc[IXmdl,'Model'] = model_ID\n    y_pred_loc = model.predict(X_test)\n    df_models_stat.loc[IXmdl,'r2_score'] = r2_score(y_test, y_pred_loc) \n    df_models_stat.loc[IXmdl,'mse'] =  mean_squared_error(y_test, y_pred_loc)\n    df_models_stat.loc[IXmdl,'Time'] = np.round( time.time() - t0,3)\n    df_models_stat.loc[IXmdl,'Target'] = selected_target\n    df_models_stat.loc[IXmdl,'n_feat'] = X_train.shape[1]\n    df_models_stat.loc[IXmdl,'n_samples_train'] = X_train.shape[0]\n\n    dict_save_predictions[model_ID] = (model.predict(X_train), model.predict(X_test), \n                                       model.predict(X_test_public_like), model.predict(X_oop)   )\n    \n","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:38.014018Z","iopub.execute_input":"2022-11-07T10:12:38.014483Z","iopub.status.idle":"2022-11-07T10:12:38.024347Z","shell.execute_reply.started":"2022-11-07T10:12:38.014447Z","shell.execute_reply":"2022-11-07T10:12:38.023100Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib\n\nimport matplotlib.pyplot as plt","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:38.026217Z","iopub.execute_input":"2022-11-07T10:12:38.026625Z","iopub.status.idle":"2022-11-07T10:12:38.041449Z","shell.execute_reply.started":"2022-11-07T10:12:38.026590Z","shell.execute_reply":"2022-11-07T10:12:38.039844Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# lasso_40 ","metadata":{}},{"cell_type":"code","source":"# Create X,y, X_train, y_train\nselected_target = 'CD31'\nn_features = 50\n\nX= df_cite.iloc[:70988,:n_features][df_meta['Playground']==1]\ny= df_cite_train_y[df_meta['Playground']==1][selected_target]\nprint('X.shape, y.shape', X.shape, y.shape )\n \nmask_train = (df_meta['Playground']==1)&(df_meta['day']!=4)&(df_meta['donor']!=31800) \nX_train = df_cite.iloc[:70988,:n_features][mask_train]\ny_train = df_cite_train_y[mask_train][ selected_target ]\n\n\nX.shape,y.shape,X_train.shape,y_train.shape","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:38.043264Z","iopub.execute_input":"2022-11-07T10:12:38.043796Z","iopub.status.idle":"2022-11-07T10:12:38.102599Z","shell.execute_reply.started":"2022-11-07T10:12:38.043756Z","shell.execute_reply":"2022-11-07T10:12:38.101453Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create X,y, X_train, y_train\nselected_target = 'CD31'\nn_features = 40\n\nX= df_cite.iloc[:70988,:n_features][df_meta['Playground']==1]\ny= df_cite_train_y[df_meta['Playground']==1][selected_target]\nprint('X.shape, y.shape', X.shape, y.shape )\n\n# Create simplfied validation scheme - like real test data - with two test-sets private-like, public-like:\n# Private like test - new DAY, and donor, \n# While public like - only new donor (days are the same as in train):\n# Step 1: \nmask_train = (df_meta['Playground']==1)&(df_meta['day']!=4)&(df_meta['donor']!=31800) \nX_train = df_cite.iloc[:70988,:n_features][mask_train]\ny_train = df_cite_train_y[mask_train][ selected_target ]\n# Step 2:\nmask_test_private_like = (df_meta['Playground']==1)&(df_meta['day']==4)\nX_test_private_like = df_cite.iloc[:70988,:n_features][ mask_test_private_like  ]\ny_test_private_like = df_cite_train_y[mask_test_private_like][ selected_target ]\nX_test = X_test_private_like\ny_test = y_test_private_like\n# Step 3: \nmask_test_public_like = (df_meta['Playground']==1)&(df_meta['day']!=4)  &(df_meta['donor']==31800) \nX_test_public_like = df_cite.iloc[:70988,:n_features][mask_test_public_like ]\ny_test_public_like = df_cite_train_y[mask_test_public_like][ selected_target ]\nX_test2 = X_test_public_like\ny_test2 = y_test_public_like\n\nmask_out_of_playground = (df_meta['Playground']==0)\nX_oop = df_cite.iloc[:70988,:n_features][mask_out_of_playground]\ny_oop = df_cite_train_y[mask_out_of_playground][ selected_target ]\n\n\n\nX.shape,y.shape, X_train.shape, X_test_private_like.shape, X_test_public_like.shape, y_train.shape, y_test_private_like.shape, y_test_public_like.shape\n\n","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:38.104356Z","iopub.execute_input":"2022-11-07T10:12:38.104729Z","iopub.status.idle":"2022-11-07T10:12:38.252174Z","shell.execute_reply.started":"2022-11-07T10:12:38.104695Z","shell.execute_reply":"2022-11-07T10:12:38.251073Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nfrom sklearn.linear_model import Lasso\nfrom sklearn.model_selection import GridSearchCV\nlasso = Lasso()\n\nparameters = {\"alpha\":[1e-15, 1e-10, 1e-8, 1e-4, 1e-3, 1e-2, 1, 5, 10, 20]}\nlasso_regression = GridSearchCV(lasso, parameters, scoring='neg_mean_squared_error', cv=5)\nlasso_regression.fit(X_train , y_train)\n\nprint(lasso_regression.best_params_)\nprint(lasso_regression.best_score_)\n","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:38.253830Z","iopub.execute_input":"2022-11-07T10:12:38.255060Z","iopub.status.idle":"2022-11-07T10:12:41.903793Z","shell.execute_reply.started":"2022-11-07T10:12:38.255009Z","shell.execute_reply":"2022-11-07T10:12:41.902216Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\nfrom sklearn.linear_model import Lasso\nt0 = time.time()\nmodel = Lasso(alpha=0.01)\nmodel.fit(X_train,y_train)\ny_train = model.predict(X_train)\ny_pred = model.predict(X_test)\nupdate_models_stat(model, 'Lasso_40', t0 ) # Updates df_models_stat\nr2_score(y_test, y_pred), mean_squared_error(y_test, y_pred)\n","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:41.906664Z","iopub.execute_input":"2022-11-07T10:12:41.908501Z","iopub.status.idle":"2022-11-07T10:12:42.055156Z","shell.execute_reply.started":"2022-11-07T10:12:41.908448Z","shell.execute_reply":"2022-11-07T10:12:42.053338Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"eps = 1e-6\nlasso_coef = model.coef_\nprint('Zero coefficients:', sum(np.abs(lasso_coef)< eps))\nprint('All coefficients:', lasso_coef.shape[0])","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:42.058252Z","iopub.execute_input":"2022-11-07T10:12:42.060076Z","iopub.status.idle":"2022-11-07T10:12:42.075898Z","shell.execute_reply.started":"2022-11-07T10:12:42.060024Z","shell.execute_reply":"2022-11-07T10:12:42.074050Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"coef = pd.Series(model.coef_, index = X_train.columns)","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:42.079107Z","iopub.execute_input":"2022-11-07T10:12:42.080138Z","iopub.status.idle":"2022-11-07T10:12:42.087120Z","shell.execute_reply.started":"2022-11-07T10:12:42.080085Z","shell.execute_reply":"2022-11-07T10:12:42.085287Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Lasso picked \" + str(sum(coef != 0)) + \" variables and eliminated the other \" +  str(sum(coef == 0)) + \" variables\")","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:42.089993Z","iopub.execute_input":"2022-11-07T10:12:42.091221Z","iopub.status.idle":"2022-11-07T10:12:42.102870Z","shell.execute_reply.started":"2022-11-07T10:12:42.091169Z","shell.execute_reply":"2022-11-07T10:12:42.100948Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"imp_coef = pd.concat([coef.sort_values().head(20),\n                     coef.sort_values().tail(20)])","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:42.104796Z","iopub.execute_input":"2022-11-07T10:12:42.105597Z","iopub.status.idle":"2022-11-07T10:12:42.122467Z","shell.execute_reply.started":"2022-11-07T10:12:42.105546Z","shell.execute_reply":"2022-11-07T10:12:42.120594Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('The most important coefficients are:')\nimp_coef","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:42.124844Z","iopub.execute_input":"2022-11-07T10:12:42.125753Z","iopub.status.idle":"2022-11-07T10:12:42.140595Z","shell.execute_reply.started":"2022-11-07T10:12:42.125702Z","shell.execute_reply":"2022-11-07T10:12:42.138973Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"matplotlib.rcParams['figure.figsize'] = (8.0, 10.0)\nimp_coef.plot(kind = \"barh\")\nplt.title(\"Coefficients in the Lasso Model\")","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:42.143080Z","iopub.execute_input":"2022-11-07T10:12:42.143979Z","iopub.status.idle":"2022-11-07T10:12:42.587180Z","shell.execute_reply.started":"2022-11-07T10:12:42.143930Z","shell.execute_reply":"2022-11-07T10:12:42.585835Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_models_stat","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:42.594829Z","iopub.execute_input":"2022-11-07T10:12:42.595308Z","iopub.status.idle":"2022-11-07T10:12:42.610506Z","shell.execute_reply.started":"2022-11-07T10:12:42.595271Z","shell.execute_reply":"2022-11-07T10:12:42.609224Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# lasso 50","metadata":{}},{"cell_type":"code","source":"# Create X,y, X_train, y_train\nselected_target = 'CD31'\nn_features = 50\n\nX= df_cite.iloc[:70988,:n_features][df_meta['Playground']==1]\ny= df_cite_train_y[df_meta['Playground']==1][selected_target]\nprint('X.shape, y.shape', X.shape, y.shape )\n\n# Create simplfied validation scheme - like real test data - with two test-sets private-like, public-like:\n# Private like test - new DAY, and donor, \n# While public like - only new donor (days are the same as in train):\n# Step 1: \nmask_train = (df_meta['Playground']==1)&(df_meta['day']!=4)&(df_meta['donor']!=31800) \nX_train = df_cite.iloc[:70988,:n_features][mask_train]\ny_train = df_cite_train_y[mask_train][ selected_target ]\n# Step 2:\nmask_test_private_like = (df_meta['Playground']==1)&(df_meta['day']==4)\nX_test_private_like = df_cite.iloc[:70988,:n_features][ mask_test_private_like  ]\ny_test_private_like = df_cite_train_y[mask_test_private_like][ selected_target ]\nX_test = X_test_private_like\ny_test = y_test_private_like\n# Step 3: \nmask_test_public_like = (df_meta['Playground']==1)&(df_meta['day']!=4)  &(df_meta['donor']==31800) \nX_test_public_like = df_cite.iloc[:70988,:n_features][mask_test_public_like ]\ny_test_public_like = df_cite_train_y[mask_test_public_like][ selected_target ]\nX_test2 = X_test_public_like\ny_test2 = y_test_public_like\n\nmask_out_of_playground = (df_meta['Playground']==0)\nX_oop = df_cite.iloc[:70988,:n_features][mask_out_of_playground]\ny_oop = df_cite_train_y[mask_out_of_playground][ selected_target ]\n\n\n\nX.shape,y.shape, X_train.shape, X_test_private_like.shape, X_test_public_like.shape, y_train.shape, y_test_private_like.shape, y_test_public_like.shape\n","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:42.613152Z","iopub.execute_input":"2022-11-07T10:12:42.613953Z","iopub.status.idle":"2022-11-07T10:12:42.764198Z","shell.execute_reply.started":"2022-11-07T10:12:42.613908Z","shell.execute_reply":"2022-11-07T10:12:42.762985Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nfrom sklearn.linear_model import Lasso\nfrom sklearn.model_selection import GridSearchCV\nlasso = Lasso()\n\nparameters = {\"alpha\":[1e-15, 1e-10, 1e-8, 1e-4, 1e-3, 1e-2, 1, 5, 10, 20]}\nlasso_regression = GridSearchCV(lasso, parameters, scoring='neg_mean_squared_error', cv=5)\nlasso_regression.fit(X_train , y_train)\n\nprint(lasso_regression.best_params_)\nprint(lasso_regression.best_score_)\n","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:42.765333Z","iopub.execute_input":"2022-11-07T10:12:42.765728Z","iopub.status.idle":"2022-11-07T10:12:46.521341Z","shell.execute_reply.started":"2022-11-07T10:12:42.765696Z","shell.execute_reply":"2022-11-07T10:12:46.519891Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\nfrom sklearn.linear_model import Lasso\nt0 = time.time()\nmodel = Lasso(alpha=0.01)\nmodel.fit(X_train,y_train)\ny_train = model.predict(X_train)\ny_pred = model.predict(X_test)\nupdate_models_stat(model, 'Lasso_50', t0 ) # Updates df_models_stat\nr2_score(y_test, y_pred), mean_squared_error(y_test, y_pred)","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:46.524385Z","iopub.execute_input":"2022-11-07T10:12:46.526215Z","iopub.status.idle":"2022-11-07T10:12:46.668333Z","shell.execute_reply.started":"2022-11-07T10:12:46.526164Z","shell.execute_reply":"2022-11-07T10:12:46.666455Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"eps = 1e-6\nlasso_coef = model.coef_\nprint('Zero coefficients:', sum(np.abs(lasso_coef)< eps))\nprint('All coefficients:', lasso_coef.shape[0])","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:46.671429Z","iopub.execute_input":"2022-11-07T10:12:46.673230Z","iopub.status.idle":"2022-11-07T10:12:46.689411Z","shell.execute_reply.started":"2022-11-07T10:12:46.673179Z","shell.execute_reply":"2022-11-07T10:12:46.687282Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"coef = pd.Series(model.coef_, index = X_train.columns)","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:46.693959Z","iopub.execute_input":"2022-11-07T10:12:46.695842Z","iopub.status.idle":"2022-11-07T10:12:46.703137Z","shell.execute_reply.started":"2022-11-07T10:12:46.695787Z","shell.execute_reply":"2022-11-07T10:12:46.701308Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Lasso picked \" + str(sum(coef != 0)) + \" variables and eliminated the other \" +  str(sum(coef == 0)) + \" variables\")","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:46.705899Z","iopub.execute_input":"2022-11-07T10:12:46.707019Z","iopub.status.idle":"2022-11-07T10:12:46.718647Z","shell.execute_reply.started":"2022-11-07T10:12:46.706967Z","shell.execute_reply":"2022-11-07T10:12:46.717026Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"imp_coef = pd.concat([coef.sort_values().head(25),\n                     coef.sort_values().tail(25)])","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:46.721296Z","iopub.execute_input":"2022-11-07T10:12:46.722358Z","iopub.status.idle":"2022-11-07T10:12:46.733294Z","shell.execute_reply.started":"2022-11-07T10:12:46.722306Z","shell.execute_reply":"2022-11-07T10:12:46.731089Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('The most important coefficients are:')\nimp_coef","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:46.736083Z","iopub.execute_input":"2022-11-07T10:12:46.737372Z","iopub.status.idle":"2022-11-07T10:12:46.753775Z","shell.execute_reply.started":"2022-11-07T10:12:46.737316Z","shell.execute_reply":"2022-11-07T10:12:46.752546Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"matplotlib.rcParams['figure.figsize'] = (8.0, 10.0)\nimp_coef.plot(kind = \"barh\")\nplt.title(\"Coefficients in the Lasso Model\")","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:46.755878Z","iopub.execute_input":"2022-11-07T10:12:46.756764Z","iopub.status.idle":"2022-11-07T10:12:47.488007Z","shell.execute_reply.started":"2022-11-07T10:12:46.756713Z","shell.execute_reply":"2022-11-07T10:12:47.486841Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_models_stat","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:47.490025Z","iopub.execute_input":"2022-11-07T10:12:47.490518Z","iopub.status.idle":"2022-11-07T10:12:47.506301Z","shell.execute_reply.started":"2022-11-07T10:12:47.490472Z","shell.execute_reply":"2022-11-07T10:12:47.504700Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# lasso 100","metadata":{}},{"cell_type":"code","source":"# Create X,y, X_train, y_train\nselected_target = 'CD31'\nn_features = 100\n\nX= df_cite.iloc[:70988,:n_features][df_meta['Playground']==1]\ny= df_cite_train_y[df_meta['Playground']==1][selected_target]\nprint('X.shape, y.shape', X.shape, y.shape )\n\n# Create simplfied validation scheme - like real test data - with two test-sets private-like, public-like:\n# Private like test - new DAY, and donor, \n# While public like - only new donor (days are the same as in train):\n# Step 1: \nmask_train = (df_meta['Playground']==1)&(df_meta['day']!=4)&(df_meta['donor']!=31800) \nX_train = df_cite.iloc[:70988,:n_features][mask_train]\ny_train = df_cite_train_y[mask_train][ selected_target ]\n# Step 2:\nmask_test_private_like = (df_meta['Playground']==1)&(df_meta['day']==4)\nX_test_private_like = df_cite.iloc[:70988,:n_features][ mask_test_private_like  ]\ny_test_private_like = df_cite_train_y[mask_test_private_like][ selected_target ]\nX_test = X_test_private_like\ny_test = y_test_private_like\n# Step 3: \nmask_test_public_like = (df_meta['Playground']==1)&(df_meta['day']!=4)  &(df_meta['donor']==31800) \nX_test_public_like = df_cite.iloc[:70988,:n_features][mask_test_public_like ]\ny_test_public_like = df_cite_train_y[mask_test_public_like][ selected_target ]\nX_test2 = X_test_public_like\ny_test2 = y_test_public_like\n\nmask_out_of_playground = (df_meta['Playground']==0)\nX_oop = df_cite.iloc[:70988,:n_features][mask_out_of_playground]\ny_oop = df_cite_train_y[mask_out_of_playground][ selected_target ]\n\n\n\nX.shape,y.shape, X_train.shape, X_test_private_like.shape, X_test_public_like.shape, y_train.shape, y_test_private_like.shape, y_test_public_like.shape\n","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:47.508036Z","iopub.execute_input":"2022-11-07T10:12:47.508486Z","iopub.status.idle":"2022-11-07T10:12:47.674761Z","shell.execute_reply.started":"2022-11-07T10:12:47.508442Z","shell.execute_reply":"2022-11-07T10:12:47.673859Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nfrom sklearn.linear_model import Lasso\nfrom sklearn.model_selection import GridSearchCV\nlasso = Lasso()\n\nparameters = {\"alpha\":[1e-15, 1e-10, 1e-8, 1e-4, 1e-3, 1e-2, 1, 5, 10, 20]}\nlasso_regression = GridSearchCV(lasso, parameters, scoring='neg_mean_squared_error', cv=5)\nlasso_regression.fit(X_train , y_train)\n\nprint(lasso_regression.best_params_)\nprint(lasso_regression.best_score_)\n","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:47.675793Z","iopub.execute_input":"2022-11-07T10:12:47.676168Z","iopub.status.idle":"2022-11-07T10:12:53.716709Z","shell.execute_reply.started":"2022-11-07T10:12:47.676133Z","shell.execute_reply":"2022-11-07T10:12:53.715118Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\nfrom sklearn.linear_model import Lasso\nt0 = time.time()\nmodel = Lasso(alpha=0.01)\nmodel.fit(X_train,y_train)\ny_train = model.predict(X_train)\ny_pred = model.predict(X_test)\nupdate_models_stat(model, 'Lasso_100', t0 ) # Updates df_models_stat\nr2_score(y_test, y_pred), mean_squared_error(y_test, y_pred)","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:53.719061Z","iopub.execute_input":"2022-11-07T10:12:53.719595Z","iopub.status.idle":"2022-11-07T10:12:53.914323Z","shell.execute_reply.started":"2022-11-07T10:12:53.719529Z","shell.execute_reply":"2022-11-07T10:12:53.912445Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"eps = 1e-6\nlasso_coef = model.coef_\nprint('Zero coefficients:', sum(np.abs(lasso_coef)< eps))\nprint('All coefficients:', lasso_coef.shape[0])","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:53.922653Z","iopub.execute_input":"2022-11-07T10:12:53.923735Z","iopub.status.idle":"2022-11-07T10:12:53.946260Z","shell.execute_reply.started":"2022-11-07T10:12:53.923655Z","shell.execute_reply":"2022-11-07T10:12:53.944517Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"coef = pd.Series(model.coef_, index = X_train.columns)","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:53.954308Z","iopub.execute_input":"2022-11-07T10:12:53.955757Z","iopub.status.idle":"2022-11-07T10:12:53.970877Z","shell.execute_reply.started":"2022-11-07T10:12:53.955676Z","shell.execute_reply":"2022-11-07T10:12:53.969095Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Lasso picked \" + str(sum(coef != 0)) + \" variables and eliminated the other \" +  str(sum(coef == 0)) + \" variables\")","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:53.974108Z","iopub.execute_input":"2022-11-07T10:12:53.975444Z","iopub.status.idle":"2022-11-07T10:12:53.997886Z","shell.execute_reply.started":"2022-11-07T10:12:53.975355Z","shell.execute_reply":"2022-11-07T10:12:53.996125Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"imp_coef = pd.concat([coef.sort_values().head(50),\n                     coef.sort_values().tail(50)])\n","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:54.001244Z","iopub.execute_input":"2022-11-07T10:12:54.002565Z","iopub.status.idle":"2022-11-07T10:12:54.020218Z","shell.execute_reply.started":"2022-11-07T10:12:54.002476Z","shell.execute_reply":"2022-11-07T10:12:54.018492Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pd.set_option(\"display.max_rows\", 100)","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:54.022265Z","iopub.execute_input":"2022-11-07T10:12:54.023058Z","iopub.status.idle":"2022-11-07T10:12:54.033059Z","shell.execute_reply.started":"2022-11-07T10:12:54.023015Z","shell.execute_reply":"2022-11-07T10:12:54.031961Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('The most important coefficients are:')\nimp_coef","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:54.034672Z","iopub.execute_input":"2022-11-07T10:12:54.035732Z","iopub.status.idle":"2022-11-07T10:12:54.052961Z","shell.execute_reply.started":"2022-11-07T10:12:54.035676Z","shell.execute_reply":"2022-11-07T10:12:54.051790Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"matplotlib.rcParams['figure.figsize'] = (8.0, 10.0)\nimp_coef.plot(kind = \"barh\")\nplt.title(\"Coefficients in the Lasso Model\")","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:54.054362Z","iopub.execute_input":"2022-11-07T10:12:54.055040Z","iopub.status.idle":"2022-11-07T10:12:55.306589Z","shell.execute_reply.started":"2022-11-07T10:12:54.054991Z","shell.execute_reply":"2022-11-07T10:12:55.305420Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_models_stat","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:55.308271Z","iopub.execute_input":"2022-11-07T10:12:55.308653Z","iopub.status.idle":"2022-11-07T10:12:55.323907Z","shell.execute_reply.started":"2022-11-07T10:12:55.308621Z","shell.execute_reply":"2022-11-07T10:12:55.322652Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# lasso 200","metadata":{}},{"cell_type":"code","source":"# Create X,y, X_train, y_train\nselected_target = 'CD31'\nn_features = 200\n\nX= df_cite.iloc[:70988,:n_features][df_meta['Playground']==1]\ny= df_cite_train_y[df_meta['Playground']==1][selected_target]\nprint('X.shape, y.shape', X.shape, y.shape )\n\n# Create simplfied validation scheme - like real test data - with two test-sets private-like, public-like:\n# Private like test - new DAY, and donor, \n# While public like - only new donor (days are the same as in train):\n# Step 1: \nmask_train = (df_meta['Playground']==1)&(df_meta['day']!=4)&(df_meta['donor']!=31800) \nX_train = df_cite.iloc[:70988,:n_features][mask_train]\ny_train = df_cite_train_y[mask_train][ selected_target ]\n# Step 2:\nmask_test_private_like = (df_meta['Playground']==1)&(df_meta['day']==4)\nX_test_private_like = df_cite.iloc[:70988,:n_features][ mask_test_private_like  ]\ny_test_private_like = df_cite_train_y[mask_test_private_like][ selected_target ]\nX_test = X_test_private_like\ny_test = y_test_private_like\n# Step 3: \nmask_test_public_like = (df_meta['Playground']==1)&(df_meta['day']!=4)  &(df_meta['donor']==31800) \nX_test_public_like = df_cite.iloc[:70988,:n_features][mask_test_public_like ]\ny_test_public_like = df_cite_train_y[mask_test_public_like][ selected_target ]\nX_test2 = X_test_public_like\ny_test2 = y_test_public_like\n\nmask_out_of_playground = (df_meta['Playground']==0)\nX_oop = df_cite.iloc[:70988,:n_features][mask_out_of_playground]\ny_oop = df_cite_train_y[mask_out_of_playground][ selected_target ]\n\n\n\nX.shape,y.shape, X_train.shape, X_test_private_like.shape, X_test_public_like.shape, y_train.shape, y_test_private_like.shape, y_test_public_like.shape\n","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:55.325598Z","iopub.execute_input":"2022-11-07T10:12:55.326106Z","iopub.status.idle":"2022-11-07T10:12:55.548004Z","shell.execute_reply.started":"2022-11-07T10:12:55.326059Z","shell.execute_reply":"2022-11-07T10:12:55.546643Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nfrom sklearn.linear_model import Lasso\nfrom sklearn.model_selection import GridSearchCV\nlasso = Lasso()\n\nparameters = {\"alpha\":[1e-15, 1e-10, 1e-8, 1e-4, 1e-3, 1e-2, 1, 5, 10, 20,30,40]}\nlasso_regression = GridSearchCV(lasso, parameters, scoring='neg_mean_squared_error', cv=5)\nlasso_regression.fit(X_train , y_train)\n\nprint(lasso_regression.best_params_)\nprint(lasso_regression.best_score_)\n","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:12:55.549358Z","iopub.execute_input":"2022-11-07T10:12:55.550403Z","iopub.status.idle":"2022-11-07T10:13:06.677925Z","shell.execute_reply.started":"2022-11-07T10:12:55.550351Z","shell.execute_reply":"2022-11-07T10:13:06.676319Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\nfrom sklearn.linear_model import Lasso\nt0 = time.time()\nmodel = Lasso(alpha=1)\nmodel.fit(X_train,y_train)\ny_train = model.predict(X_train)\ny_pred = model.predict(X_test)\nupdate_models_stat(model, 'Lasso_200', t0 ) # Updates df_models_stat\nr2_score(y_test, y_pred), mean_squared_error(y_test, y_pred)","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:13:06.679803Z","iopub.execute_input":"2022-11-07T10:13:06.684339Z","iopub.status.idle":"2022-11-07T10:13:06.887010Z","shell.execute_reply.started":"2022-11-07T10:13:06.684249Z","shell.execute_reply":"2022-11-07T10:13:06.885347Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"eps = 1e-6\nlasso_coef = model.coef_\nprint('Zero coefficients:', sum(np.abs(lasso_coef)< eps))\nprint('All coefficients:', lasso_coef.shape[0])","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:13:06.896033Z","iopub.execute_input":"2022-11-07T10:13:06.900366Z","iopub.status.idle":"2022-11-07T10:13:06.922656Z","shell.execute_reply.started":"2022-11-07T10:13:06.900280Z","shell.execute_reply":"2022-11-07T10:13:06.920501Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"coef = pd.Series(model.coef_, index = X_train.columns)","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:13:06.929311Z","iopub.execute_input":"2022-11-07T10:13:06.930634Z","iopub.status.idle":"2022-11-07T10:13:06.947470Z","shell.execute_reply.started":"2022-11-07T10:13:06.930560Z","shell.execute_reply":"2022-11-07T10:13:06.945553Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Lasso picked \" + str(sum(coef != 0)) + \" variables and eliminated the other \" +  str(sum(coef == 0)) + \" variables\")","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:13:06.950793Z","iopub.execute_input":"2022-11-07T10:13:06.952356Z","iopub.status.idle":"2022-11-07T10:13:06.974197Z","shell.execute_reply.started":"2022-11-07T10:13:06.952276Z","shell.execute_reply":"2022-11-07T10:13:06.971597Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"imp_coef = pd.concat([coef.sort_values().head(8),\n                     coef.sort_values().tail(12)])","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:13:06.978100Z","iopub.execute_input":"2022-11-07T10:13:06.984170Z","iopub.status.idle":"2022-11-07T10:13:06.994671Z","shell.execute_reply.started":"2022-11-07T10:13:06.984079Z","shell.execute_reply":"2022-11-07T10:13:06.993368Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('The most important coefficients are:')\nimp_coef","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:13:06.996233Z","iopub.execute_input":"2022-11-07T10:13:06.996648Z","iopub.status.idle":"2022-11-07T10:13:07.014056Z","shell.execute_reply.started":"2022-11-07T10:13:06.996613Z","shell.execute_reply":"2022-11-07T10:13:07.012910Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"matplotlib.rcParams['figure.figsize'] = (8.0, 10.0)\nimp_coef.plot(kind = \"barh\")\nplt.title(\"Coefficients in the Lasso Model\")","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:13:07.015752Z","iopub.execute_input":"2022-11-07T10:13:07.016909Z","iopub.status.idle":"2022-11-07T10:13:07.336990Z","shell.execute_reply.started":"2022-11-07T10:13:07.016871Z","shell.execute_reply":"2022-11-07T10:13:07.336124Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_models_stat","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:13:07.338950Z","iopub.execute_input":"2022-11-07T10:13:07.339846Z","iopub.status.idle":"2022-11-07T10:13:07.355593Z","shell.execute_reply.started":"2022-11-07T10:13:07.339794Z","shell.execute_reply":"2022-11-07T10:13:07.354224Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# lasso 500","metadata":{}},{"cell_type":"code","source":"# Create X,y, X_train, y_train\nselected_target = 'CD31'\nn_features = 500\n\nX= df_cite.iloc[:70988,:n_features][df_meta['Playground']==1]\ny= df_cite_train_y[df_meta['Playground']==1][selected_target]\nprint('X.shape, y.shape', X.shape, y.shape )\n\n# Create simplfied validation scheme - like real test data - with two test-sets private-like, public-like:\n# Private like test - new DAY, and donor, \n# While public like - only new donor (days are the same as in train):\n# Step 1: \nmask_train = (df_meta['Playground']==1)&(df_meta['day']!=4)&(df_meta['donor']!=31800) \nX_train = df_cite.iloc[:70988,:n_features][mask_train]\ny_train = df_cite_train_y[mask_train][ selected_target ]\n# Step 2:\nmask_test_private_like = (df_meta['Playground']==1)&(df_meta['day']==4)\nX_test_private_like = df_cite.iloc[:70988,:n_features][ mask_test_private_like  ]\ny_test_private_like = df_cite_train_y[mask_test_private_like][ selected_target ]\nX_test = X_test_private_like\ny_test = y_test_private_like\n# Step 3: \nmask_test_public_like = (df_meta['Playground']==1)&(df_meta['day']!=4)  &(df_meta['donor']==31800) \nX_test_public_like = df_cite.iloc[:70988,:n_features][mask_test_public_like ]\ny_test_public_like = df_cite_train_y[mask_test_public_like][ selected_target ]\nX_test2 = X_test_public_like\ny_test2 = y_test_public_like\n\nmask_out_of_playground = (df_meta['Playground']==0)\nX_oop = df_cite.iloc[:70988,:n_features][mask_out_of_playground]\ny_oop = df_cite_train_y[mask_out_of_playground][ selected_target ]\n\n\n\nX.shape,y.shape, X_train.shape, X_test_private_like.shape, X_test_public_like.shape, y_train.shape, y_test_private_like.shape, y_test_public_like.shape\n","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:13:07.357121Z","iopub.execute_input":"2022-11-07T10:13:07.357593Z","iopub.status.idle":"2022-11-07T10:13:07.869582Z","shell.execute_reply.started":"2022-11-07T10:13:07.357556Z","shell.execute_reply":"2022-11-07T10:13:07.868409Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.linear_model import Lasso\nfrom sklearn.model_selection import GridSearchCV\nlasso = Lasso()\n\nparameters = {\"alpha\":[1e-15, 1e-10, 1e-8, 1e-4, 1e-3, 1e-2, 1, 5, 10, 20]}\nlasso_regression = GridSearchCV(lasso, parameters, scoring='neg_mean_squared_error', cv=5)\nlasso_regression.fit(X_train , y_train)\n\nprint(lasso_regression.best_params_)\nprint(lasso_regression.best_score_)\n","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:13:07.873556Z","iopub.execute_input":"2022-11-07T10:13:07.873983Z","iopub.status.idle":"2022-11-07T10:13:32.176367Z","shell.execute_reply.started":"2022-11-07T10:13:07.873947Z","shell.execute_reply":"2022-11-07T10:13:32.174206Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\nfrom sklearn.linear_model import Lasso\nt0 = time.time()\nmodel = Lasso(alpha=1)\nmodel.fit(X_train,y_train)\ny_train = model.predict(X_train)\ny_pred = model.predict(X_test)\nupdate_models_stat(model, 'Lasso_500', t0 ) # Updates df_models_stat\nr2_score(y_test, y_pred), mean_squared_error(y_test, y_pred)","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:13:32.179235Z","iopub.execute_input":"2022-11-07T10:13:32.180148Z","iopub.status.idle":"2022-11-07T10:13:32.458770Z","shell.execute_reply.started":"2022-11-07T10:13:32.180076Z","shell.execute_reply":"2022-11-07T10:13:32.457049Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"eps = 1e-6\nlasso_coef = model.coef_\nprint('Zero coefficients:', sum(np.abs(lasso_coef)< eps))\nprint('All coefficients:', lasso_coef.shape[0])","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:13:32.467286Z","iopub.execute_input":"2022-11-07T10:13:32.471887Z","iopub.status.idle":"2022-11-07T10:13:32.495753Z","shell.execute_reply.started":"2022-11-07T10:13:32.471792Z","shell.execute_reply":"2022-11-07T10:13:32.493692Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"coef = pd.Series(model.coef_, index = X_train.columns)","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:13:32.502631Z","iopub.execute_input":"2022-11-07T10:13:32.508814Z","iopub.status.idle":"2022-11-07T10:13:32.521607Z","shell.execute_reply.started":"2022-11-07T10:13:32.508717Z","shell.execute_reply":"2022-11-07T10:13:32.519858Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Lasso picked \" + str(sum(coef != 0)) + \" variables and eliminated the other \" +  str(sum(coef == 0)) + \" variables\")","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:13:32.524573Z","iopub.execute_input":"2022-11-07T10:13:32.525825Z","iopub.status.idle":"2022-11-07T10:13:32.546813Z","shell.execute_reply.started":"2022-11-07T10:13:32.525759Z","shell.execute_reply":"2022-11-07T10:13:32.545092Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"imp_coef = pd.concat([coef.sort_values().head(8),\n                     coef.sort_values().tail(12)])","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:13:32.550001Z","iopub.execute_input":"2022-11-07T10:13:32.551258Z","iopub.status.idle":"2022-11-07T10:13:32.567159Z","shell.execute_reply.started":"2022-11-07T10:13:32.551177Z","shell.execute_reply":"2022-11-07T10:13:32.565783Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('The most important coefficients are:')\nimp_coef","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:13:32.568598Z","iopub.execute_input":"2022-11-07T10:13:32.568960Z","iopub.status.idle":"2022-11-07T10:13:32.585483Z","shell.execute_reply.started":"2022-11-07T10:13:32.568928Z","shell.execute_reply":"2022-11-07T10:13:32.584481Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"matplotlib.rcParams['figure.figsize'] = (8.0, 7.0)\nimp_coef.plot(kind = \"barh\")\nplt.title(\"Coefficients in the Lasso Model\")","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:13:32.586964Z","iopub.execute_input":"2022-11-07T10:13:32.587564Z","iopub.status.idle":"2022-11-07T10:13:32.910291Z","shell.execute_reply.started":"2022-11-07T10:13:32.587525Z","shell.execute_reply":"2022-11-07T10:13:32.909451Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_models_stat","metadata":{"execution":{"iopub.status.busy":"2022-11-07T10:13:32.911480Z","iopub.execute_input":"2022-11-07T10:13:32.912619Z","iopub.status.idle":"2022-11-07T10:13:32.928741Z","shell.execute_reply.started":"2022-11-07T10:13:32.912577Z","shell.execute_reply":"2022-11-07T10:13:32.927493Z"},"trusted":true},"execution_count":null,"outputs":[]}]}