{"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":72284,"databundleVersionId":7919275,"sourceType":"competition"}],"dockerImageVersionId":30673,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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# 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-04-04T20:09:32.282913Z","iopub.execute_input":"2024-04-04T20:09:32.284131Z","iopub.status.idle":"2024-04-04T20:09:32.294499Z","shell.execute_reply.started":"2024-04-04T20:09:32.284082Z","shell.execute_reply":"2024-04-04T20:09:32.293139Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport json\nimport pandas as pd\nimport datetime\nimport warnings\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split, ShuffleSplit, cross_val_score\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import roc_auc_score, accuracy_score\n\n%matplotlib inline","metadata":{"execution":{"iopub.status.busy":"2024-04-04T20:09:35.264804Z","iopub.execute_input":"2024-04-04T20:09:35.265710Z","iopub.status.idle":"2024-04-04T20:09:35.507625Z","shell.execute_reply.started":"2024-04-04T20:09:35.265663Z","shell.execute_reply":"2024-04-04T20:09:35.506423Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport warnings\nimport random\nimport math\nimport pandas as pd\nimport xgboost\nimport lightgbm\nimport catboost\n\nfrom matplotlib.colors import ListedColormap\nfrom scipy.stats import pearsonr\nfrom itertools import combinations\nfrom sklearn.base import BaseEstimator\nfrom sklearn import datasets\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import (RandomForestClassifier,\n                              ExtraTreesClassifier,\n                              VotingClassifier)\nfrom sklearn.tree import (DecisionTreeRegressor,\n                          DecisionTreeClassifier)\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.metrics import r2_score, f1_score, accuracy_score, roc_auc_score\n\n\nfrom scipy.special import comb\n\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import OneHotEncoder, StandardScaler\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.model_selection import GridSearchCV","metadata":{"execution":{"iopub.status.busy":"2024-04-04T20:09:37.592475Z","iopub.execute_input":"2024-04-04T20:09:37.593149Z","iopub.status.idle":"2024-04-04T20:09:39.698546Z","shell.execute_reply.started":"2024-04-04T20:09:37.593115Z","shell.execute_reply":"2024-04-04T20:09:39.697404Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data = pd.read_csv('/kaggle/input/copy-of-23-24-ml/train_data.csv', index_col=\"match_id_hash\")\ntarget = pd.read_csv('/kaggle/input/copy-of-23-24-ml/train_targets.csv', index_col=\"match_id_hash\")","metadata":{"execution":{"iopub.status.busy":"2024-04-04T20:09:43.578036Z","iopub.execute_input":"2024-04-04T20:09:43.578706Z","iopub.status.idle":"2024-04-04T20:09:45.107063Z","shell.execute_reply.started":"2024-04-04T20:09:43.578668Z","shell.execute_reply":"2024-04-04T20:09:45.105401Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"target.head()","metadata":{"execution":{"iopub.status.busy":"2024-04-04T20:09:45.141729Z","iopub.execute_input":"2024-04-04T20:09:45.142472Z","iopub.status.idle":"2024-04-04T20:09:45.163466Z","shell.execute_reply.started":"2024-04-04T20:09:45.142424Z","shell.execute_reply":"2024-04-04T20:09:45.162034Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data.head()","metadata":{"execution":{"iopub.status.busy":"2024-04-04T19:53:34.907549Z","iopub.execute_input":"2024-04-04T19:53:34.908406Z","iopub.status.idle":"2024-04-04T19:53:34.931268Z","shell.execute_reply.started":"2024-04-04T19:53:34.908367Z","shell.execute_reply":"2024-04-04T19:53:34.930215Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X = data.values\ny = target[\"radiant_win\"].values.astype(\"int8\")\nSEED = 42","metadata":{"execution":{"iopub.status.busy":"2024-04-04T20:09:50.535858Z","iopub.execute_input":"2024-04-04T20:09:50.536275Z","iopub.status.idle":"2024-04-04T20:09:50.567106Z","shell.execute_reply.started":"2024-04-04T20:09:50.536244Z","shell.execute_reply":"2024-04-04T20:09:50.565587Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train, X_valid, y_train, y_valid = train_test_split(X, y,\n                                                      test_size=0.2,\n                                                      random_state=SEED)\n\nprint(X_train.shape)\nprint(X_valid.shape)","metadata":{"execution":{"iopub.status.busy":"2024-04-04T20:09:52.128208Z","iopub.execute_input":"2024-04-04T20:09:52.128606Z","iopub.status.idle":"2024-04-04T20:09:52.228088Z","shell.execute_reply.started":"2024-04-04T20:09:52.128574Z","shell.execute_reply":"2024-04-04T20:09:52.226769Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from catboost import CatBoostClassifier","metadata":{"execution":{"iopub.status.busy":"2024-04-04T20:09:54.469805Z","iopub.execute_input":"2024-04-04T20:09:54.470545Z","iopub.status.idle":"2024-04-04T20:09:54.476189Z","shell.execute_reply.started":"2024-04-04T20:09:54.470507Z","shell.execute_reply":"2024-04-04T20:09:54.474812Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Определение пайплайна\n\n'''\npreprocessor = ColumnTransformer(transformers=[\n    (\"scaler\", StandardScaler(), numcols),\n    (\"ohe\", OneHotEncoder(drop=\"first\"), catcols)\n])\n'''\n'''\npipeline_catboost = Pipeline([\n    #('preprocessor', preprocessor),\n    (\"scaler\", StandardScaler()),\n    ('classifier', CatBoostClassifier(random_state=SEED, verbose=0))\n])\n\n# Определение сетки параметров\nparam_grid_catboost = {\n    'classifier__iterations': [100, 200, 300],\n    'classifier__depth': [4, 6, 8, 10],\n    'classifier__learning_rate': [0.1, 0.2, 0.3]\n}\n\n# Создание объекта GridSearchCV\ngrid_search_catboost_pipeline = GridSearchCV(pipeline_catboost, param_grid_catboost, scoring=\"roc_auc\", cv=5)\n\n# Подгонка (Fit) объекта GridSearchCV\ngrid_search_catboost_pipeline.fit(X_train, y_train)\n\n# Получение лучших параметров и оценки\nbest_params_catboost_pipeline = grid_search_catboost_pipeline.best_params_\n#best_f1_catboost_pipeline = grid_search_catboost_pipeline.best_score_\nbest_rocauc_catboost_pipeline = grid_search_catboost_pipeline.best_score_\n\nprint(\"Best Parameters for CatBoostClassifier (Pipeline):\", best_params_catboost_pipeline)\nprint(\"Best ROC AUC for CatBoostClassifier (Pipeline):\", best_f1_catboost_pipeline)\n'''\nprint('долгие вычисления')","metadata":{"execution":{"iopub.status.busy":"2024-04-04T19:53:35.084105Z","iopub.execute_input":"2024-04-04T19:53:35.084506Z","iopub.status.idle":"2024-04-04T19:53:35.096720Z","shell.execute_reply.started":"2024-04-04T19:53:35.084467Z","shell.execute_reply":"2024-04-04T19:53:35.095200Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"1. Best Parameters for CatBoostClassifier (Pipeline): {'classifier__depth': 4, 'classifier__iterations': 200, 'classifier__learning_rate': 0.1} Best F1 Score for CatBoostClassifier (Pipeline): 0.7419939455458848\n\n2. Best Parameters for CatBoostClassifier (Pipeline): {'classifier__depth': 6, 'classifier__iterations': 300, 'classifier__learning_rate': 0.1} Best ROC AUC for CatBoostClassifier (Pipeline): 0.7957575454079168","metadata":{}},{"cell_type":"code","source":"# Параметры для CatBoostClassifier\n#tr = {'classifier__depth':'depth','classifier__iterations': 'iterations','classifier__learning_rate':'learning_rate' }\n\n#best_params_catboost = {tr[k]: v for k, v in best_params_catboost_pipeline.items()}\n\n\nparams_catboost = {\n    'iterations': 300,\n    'learning_rate': 0.1,\n    'depth': 6,\n    'random_seed': SEED\n}\n\n# Создание конвейерной модели для CatBoostClassifier\ncatboost_pipeline = Pipeline(steps=[\n    (\"scaler\", StandardScaler()),\n    \n    (\"catboost\", CatBoostClassifier(**params_catboost, verbose=0))\n])\n\n# Обучение модели\ncatboost_pipeline.fit(X_train, y_train)\n\n# Получение предсказаний\ny_pred_catboost = catboost_pipeline.predict(X_valid)\nroc_auc_score(y_valid,y_pred_catboost )","metadata":{"execution":{"iopub.status.busy":"2024-04-04T20:10:00.936472Z","iopub.execute_input":"2024-04-04T20:10:00.936887Z","iopub.status.idle":"2024-04-04T20:10:17.498225Z","shell.execute_reply.started":"2024-04-04T20:10:00.936856Z","shell.execute_reply":"2024-04-04T20:10:17.497370Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"PATH_TO_DATA = '/kaggle/input/copy-of-23-24-ml/'\ndf_test_features = pd.read_csv(os.path.join(PATH_TO_DATA, \"test_data.csv\"),\n                                   index_col=\"match_id_hash\")\n\nX_test = df_test_features.values","metadata":{"execution":{"iopub.status.busy":"2024-04-04T20:11:25.251394Z","iopub.execute_input":"2024-04-04T20:11:25.251763Z","iopub.status.idle":"2024-04-04T20:11:25.629384Z","shell.execute_reply.started":"2024-04-04T20:11:25.251733Z","shell.execute_reply":"2024-04-04T20:11:25.628134Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_test_pred = catboost_pipeline.predict_proba(X_test)[:, 1]\n\ndf_submission = pd.DataFrame({\"radiant_win_prob\": y_test_pred},\n                                 index=df_test_features.index)\n\nsubmission_filename = \"submission_{}.csv\".format(\n    datetime.datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\"))\ndf_submission.to_csv(submission_filename)\nprint(\"Файл посылки сохранен, как: {}\".format(submission_filename))","metadata":{"execution":{"iopub.status.busy":"2024-04-04T19:53:49.065700Z","iopub.execute_input":"2024-04-04T19:53:49.066111Z","iopub.status.idle":"2024-04-04T19:53:49.400952Z","shell.execute_reply.started":"2024-04-04T19:53:49.066072Z","shell.execute_reply":"2024-04-04T19:53:49.399833Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"ПОПРОБУЮ сделать голосование","metadata":{}},{"cell_type":"code","source":"from xgboost import XGBRFClassifier\n# Параметры для XGBRFClassifier\nparams_xgbrf = {\n    'n_estimators': 300,\n    'max_depth': 7,\n    'learning_rate': 0.1,\n    \n    'random_state': SEED\n}\n\n# Создание конвейерной модели для XGBRFClassifier\nxgbrf_pipeline = Pipeline(steps=[\n    (\"scaler\", StandardScaler()),\n    (\"xgbrf\", XGBRFClassifier(**params_xgbrf))\n])\n\n# Обучение модели\nxgbrf_pipeline.fit(X_train, y_train)\n\n# Получение предсказаний\ny_pred_xgbrf = xgbrf_pipeline.predict(X_valid)\n\nrocauc_xgbrf = roc_auc_score(y_valid, y_pred_xgbrf)\nrocauc_xgbrf","metadata":{"execution":{"iopub.status.busy":"2024-04-04T19:53:49.402557Z","iopub.execute_input":"2024-04-04T19:53:49.403010Z","iopub.status.idle":"2024-04-04T19:54:06.589759Z","shell.execute_reply.started":"2024-04-04T19:53:49.402972Z","shell.execute_reply":"2024-04-04T19:54:06.587562Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"xgbrf = XGBRFClassifier(random_state=SEED)\nxgbrf.fit(X_train, y_train)\ny_pred_xgbrf = xgbrf.predict(X_valid)\n\nrocauc_xgbrf = roc_auc_score(y_valid, y_pred_xgbrf)\nrocauc_xgbrf\n#0.6687565161512906","metadata":{"execution":{"iopub.status.busy":"2024-04-04T19:54:17.296303Z","iopub.execute_input":"2024-04-04T19:54:17.296738Z","iopub.status.idle":"2024-04-04T19:54:21.401896Z","shell.execute_reply.started":"2024-04-04T19:54:17.296708Z","shell.execute_reply":"2024-04-04T19:54:21.400920Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_test_pred = xgbrf.predict_proba(X_test)[:, 1]\n\ndf_submission = pd.DataFrame({\"radiant_win_prob\": y_test_pred},\n                                 index=df_test_features.index)\nsubmission_filename = \"submission_{}.csv\".format(\n    datetime.datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\"))\ndf_submission.to_csv(submission_filename)\nprint(\"Файл посылки сохранен, как: {}\".format(submission_filename))","metadata":{"execution":{"iopub.status.busy":"2024-04-04T19:54:23.389059Z","iopub.execute_input":"2024-04-04T19:54:23.389752Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"А что , если лайтгбм. Но СПЕРВА EDA","metadata":{}},{"cell_type":"code","source":"'''\nknn_pipeline_boost = Pipeline(steps=[\n    (\"preprocessor\", preprocessor),\n    (\"knn\", lightgbm.LGBMClassifier(**params_gbdt))\n])\n\nknn_pipeline_rf.fit(X_train, y_train)\nknn_pipeline_boost.fit(X_train, y_train)\n\ny_pred_rf = knn_pipeline_rf.predict(X_test)\ny_pred_boost = knn_pipeline_boost.predict(X_test)\n'''\n\n\ndata.info()","metadata":{"execution":{"iopub.status.busy":"2024-04-04T19:54:06.593258Z","iopub.status.idle":"2024-04-04T19:54:06.593596Z","shell.execute_reply.started":"2024-04-04T19:54:06.593434Z","shell.execute_reply":"2024-04-04T19:54:06.593448Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']\nnumerical_vars = list(data.select_dtypes(include=numerics).columns)\nnumdata = data[numerical_vars]\nnumdata.shape","metadata":{"execution":{"iopub.status.busy":"2024-04-04T20:10:29.959376Z","iopub.execute_input":"2024-04-04T20:10:29.960227Z","iopub.status.idle":"2024-04-04T20:10:30.017203Z","shell.execute_reply.started":"2024-04-04T20:10:29.960189Z","shell.execute_reply":"2024-04-04T20:10:30.015593Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### слишком много колонок, попробую сделать фича селекшн. но при этом они все численные))\n\n##### 1. убрать фичи с низким вариансом","metadata":{}},{"cell_type":"code","source":"# using sklearn variancethreshold to find constant features\n\nfrom sklearn.feature_selection import VarianceThreshold\nsel = VarianceThreshold(threshold=0.1)  # 0.1 indicates 99% of observations approximately\nsel.fit(data)  # fit finds the features with low variance","metadata":{"execution":{"iopub.status.busy":"2024-04-04T20:10:33.359354Z","iopub.execute_input":"2024-04-04T20:10:33.360006Z","iopub.status.idle":"2024-04-04T20:10:33.535327Z","shell.execute_reply.started":"2024-04-04T20:10:33.359972Z","shell.execute_reply":"2024-04-04T20:10:33.533995Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# get_support is a boolean vector that indicates which features are retained\n# if we sum over get_support, we get the number of features that are not constant\nsum(sel.get_support())","metadata":{"execution":{"iopub.status.busy":"2024-04-04T20:10:36.182504Z","iopub.execute_input":"2024-04-04T20:10:36.182915Z","iopub.status.idle":"2024-04-04T20:10:36.191330Z","shell.execute_reply.started":"2024-04-04T20:10:36.182880Z","shell.execute_reply":"2024-04-04T20:10:36.189970Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# print the constant features\nprint(\n    len([\n        x for x in data.columns\n        if x not in data.columns[sel.get_support()]\n    ]))\n\n[x for x in data.columns if x not in data.columns[sel.get_support()]]","metadata":{"execution":{"iopub.status.busy":"2024-04-04T20:10:38.599023Z","iopub.execute_input":"2024-04-04T20:10:38.600517Z","iopub.status.idle":"2024-04-04T20:10:38.650177Z","shell.execute_reply.started":"2024-04-04T20:10:38.600473Z","shell.execute_reply":"2024-04-04T20:10:38.649240Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_test","metadata":{"execution":{"iopub.status.busy":"2024-04-04T20:11:39.465423Z","iopub.execute_input":"2024-04-04T20:11:39.465834Z","iopub.status.idle":"2024-04-04T20:11:39.475296Z","shell.execute_reply.started":"2024-04-04T20:11:39.465802Z","shell.execute_reply":"2024-04-04T20:11:39.473949Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#then remove the features from training and test set\ndata_new = sel.transform(data)\ndf_test_features_new = sel.transform(df_test_features)\n","metadata":{"execution":{"iopub.status.busy":"2024-04-04T20:11:42.374809Z","iopub.execute_input":"2024-04-04T20:11:42.375220Z","iopub.status.idle":"2024-04-04T20:11:42.460430Z","shell.execute_reply.started":"2024-04-04T20:11:42.375184Z","shell.execute_reply":"2024-04-04T20:11:42.459226Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_new.shape, df_test_features_new.shape","metadata":{"execution":{"iopub.status.busy":"2024-04-04T20:11:45.159206Z","iopub.execute_input":"2024-04-04T20:11:45.159584Z","iopub.status.idle":"2024-04-04T20:11:45.167751Z","shell.execute_reply.started":"2024-04-04T20:11:45.159554Z","shell.execute_reply":"2024-04-04T20:11:45.166246Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"##### 2. Выбор фич на основе перцентиля высшего скора (anova or IG)\n\n[Ссылка на использованный гайд](https://www.kaggle.com/code/prashant111/comprehensive-guide-on-feature-selection#0.1)","metadata":{}},{"cell_type":"code","source":"from sklearn.feature_selection import SelectPercentile, f_classif, mutual_info_classif\n\ndata_new2 = SelectPercentile(f_classif, percentile=10).fit_transform(data_new, y)\ndata_new2.shape","metadata":{"execution":{"iopub.status.busy":"2024-04-04T20:12:56.162189Z","iopub.execute_input":"2024-04-04T20:12:56.162571Z","iopub.status.idle":"2024-04-04T20:12:56.289089Z","shell.execute_reply.started":"2024-04-04T20:12:56.162541Z","shell.execute_reply":"2024-04-04T20:12:56.288242Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"попробовать сделать это на mutual_info_classif - (information gain) - непараметрический способ (для примера, но использовать я скорее буду параметрический способ, раз все мои переменные нумерные)","metadata":{}},{"cell_type":"code","source":"data_new3 = SelectPercentile(mutual_info_classif, percentile=10).fit_transform(data_new, y)\ndata_new3.shape","metadata":{"execution":{"iopub.status.busy":"2024-04-04T20:12:14.848802Z","iopub.execute_input":"2024-04-04T20:12:14.849525Z","iopub.status.idle":"2024-04-04T20:12:49.006290Z","shell.execute_reply.started":"2024-04-04T20:12:14.849490Z","shell.execute_reply":"2024-04-04T20:12:49.005113Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### Делаю попытку снова, на основе того, чему я научилась","metadata":{}},{"cell_type":"code","source":"X_train, X_valid, y_train, y_valid = train_test_split(data, y,\n                                                      test_size=0.2,\n                                                      random_state=SEED)\n\nprint(X_train.shape)\nprint(X_valid.shape)","metadata":{"execution":{"iopub.status.busy":"2024-04-04T20:12:58.600082Z","iopub.execute_input":"2024-04-04T20:12:58.600533Z","iopub.status.idle":"2024-04-04T20:12:58.663200Z","shell.execute_reply.started":"2024-04-04T20:12:58.600499Z","shell.execute_reply":"2024-04-04T20:12:58.661912Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# найти и удалить скоррелированные фичи\ndef correlation(dataset, threshold):\n    col_corr = set()  # Set of all the names of correlated columns\n    corr_matrix = dataset.corr()\n    for i in range(len(corr_matrix.columns)):\n        for j in range(i):\n            if abs(corr_matrix.iloc[i, j]) > threshold: # we are interested in absolute coeff value\n                colname = corr_matrix.columns[i]  # getting the name of column\n                col_corr.add(colname)\n    return col_corr\n\ncorr_features = correlation(X_train, 0.8)\nprint('correlated features: ', len(set(corr_features)) )","metadata":{"execution":{"iopub.status.busy":"2024-04-04T20:13:06.752712Z","iopub.execute_input":"2024-04-04T20:13:06.753692Z","iopub.status.idle":"2024-04-04T20:13:12.014995Z","shell.execute_reply.started":"2024-04-04T20:13:06.753647Z","shell.execute_reply":"2024-04-04T20:13:12.013704Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# удаление\nX_train.drop(labels=corr_features, axis=1, inplace=True)\nX_valid.drop(labels=corr_features, axis=1, inplace=True)\ndf_test_features.drop(labels=corr_features, axis=1, inplace=True)\n\nX_train.shape, X_valid.shape","metadata":{"execution":{"iopub.status.busy":"2024-04-04T20:13:45.176735Z","iopub.execute_input":"2024-04-04T20:13:45.177173Z","iopub.status.idle":"2024-04-04T20:13:45.202204Z","shell.execute_reply.started":"2024-04-04T20:13:45.177129Z","shell.execute_reply":"2024-04-04T20:13:45.201024Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data.drop(labels=corr_features, axis=1, inplace=True)","metadata":{"execution":{"iopub.status.busy":"2024-04-04T20:42:32.473734Z","iopub.execute_input":"2024-04-04T20:42:32.475029Z","iopub.status.idle":"2024-04-04T20:42:32.562065Z","shell.execute_reply.started":"2024-04-04T20:42:32.474959Z","shell.execute_reply":"2024-04-04T20:42:32.560777Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sel = VarianceThreshold(threshold=0.1)  # 0.1 indicates 99% of observations approximately\nsel.fit(X_train)  # fit finds the features with low variance\n#data_new = sel.transform(data)\n#df_test_features_new = sel.transform(df_test_features)","metadata":{"execution":{"iopub.status.busy":"2024-04-04T20:13:49.758421Z","iopub.execute_input":"2024-04-04T20:13:49.758827Z","iopub.status.idle":"2024-04-04T20:13:49.830796Z","shell.execute_reply.started":"2024-04-04T20:13:49.758794Z","shell.execute_reply":"2024-04-04T20:13:49.829520Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sum(sel.get_support())","metadata":{"execution":{"iopub.status.busy":"2024-04-04T20:13:51.814882Z","iopub.execute_input":"2024-04-04T20:13:51.815278Z","iopub.status.idle":"2024-04-04T20:13:51.824484Z","shell.execute_reply.started":"2024-04-04T20:13:51.815249Z","shell.execute_reply":"2024-04-04T20:13:51.823394Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train = sel.transform(X_train)\nX_valid = sel.transform(X_valid)\ndf_test_features_new = sel.transform(df_test_features)","metadata":{"execution":{"iopub.status.busy":"2024-04-04T20:13:54.248065Z","iopub.execute_input":"2024-04-04T20:13:54.248524Z","iopub.status.idle":"2024-04-04T20:13:54.300292Z","shell.execute_reply.started":"2024-04-04T20:13:54.248490Z","shell.execute_reply":"2024-04-04T20:13:54.298337Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_sel = sel.transform(data)","metadata":{"execution":{"iopub.status.busy":"2024-04-04T20:42:59.221381Z","iopub.execute_input":"2024-04-04T20:42:59.221854Z","iopub.status.idle":"2024-04-04T20:42:59.379570Z","shell.execute_reply.started":"2024-04-04T20:42:59.221748Z","shell.execute_reply":"2024-04-04T20:42:59.378465Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Создание конвейерной модели для CatBoostClassifier\nparams_catboost = {\n    'iterations': 300,\n    'learning_rate': 0.1,\n    'depth': 6,\n    'random_seed': SEED\n}\n\ncatboost_pipeline = Pipeline(steps=[\n    (\"scaler\", StandardScaler()),\n    \n    (\"catboost\", CatBoostClassifier(**params_catboost, verbose=0))\n])\n\n# Обучение модели\ncatboost_pipeline.fit(X_train, y_train)\n\n# Получение предсказаний\ny_pred_catboost = catboost_pipeline.predict(X_valid)\nroc_auc_score(y_valid,y_pred_catboost )","metadata":{"execution":{"iopub.status.busy":"2024-04-04T20:15:13.175190Z","iopub.execute_input":"2024-04-04T20:15:13.175582Z","iopub.status.idle":"2024-04-04T20:15:20.580507Z","shell.execute_reply.started":"2024-04-04T20:15:13.175553Z","shell.execute_reply":"2024-04-04T20:15:20.579331Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"грустно, но ладно. зато смогли убрать ненужные фичи, несильно потеряв в качестве. зато такие хорошие фичи можно будет дать логистической регрессии","metadata":{}},{"cell_type":"code","source":"# Создание пайплайна для логистической регрессии\nlogistic_pipeline = Pipeline(steps=[\n    (\"scaler\", StandardScaler()),\n    (\"logistic_regression\", LogisticRegression())\n])\n\n# Определение сетки параметров для логистической регрессии\nparam_grid = {\n    'logistic_regression__penalty': ['l1', 'l2'],\n    'logistic_regression__C': [0.001, 0.01, 0.1, 1, 10, 100],\n}\n\n# Создание объекта GridSearchCV\ngrid_search = GridSearchCV(estimator=logistic_pipeline, param_grid=param_grid, cv=5, scoring=\"roc_auc\")\n\n# Запуск поиска по сетке\ngrid_search.fit(X_train, y_train)\n\n# Вывод наилучших параметров и оценки\nprint(\"Best parameters found for Logistic Regression:\")\nprint(grid_search.best_params_)\nprint(\"Best score found for Logistic Regression:\")\nprint(grid_search.best_score_)","metadata":{"execution":{"iopub.status.busy":"2024-04-04T20:15:26.700555Z","iopub.execute_input":"2024-04-04T20:15:26.700970Z","iopub.status.idle":"2024-04-04T20:15:41.139913Z","shell.execute_reply.started":"2024-04-04T20:15:26.700937Z","shell.execute_reply":"2024-04-04T20:15:41.138280Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Best parameters found for Logistic Regression:\n{'logistic_regression__C': 0.01, 'logistic_regression__penalty': 'l2'}\n\nBest score found for Logistic Regression:\n0.7921502909826882\n\nКажется, есть смысл пилить на этом ансамбль))","metadata":{}},{"cell_type":"code","source":"params = {\n    'penalty':  'l2',\n    'C' : 0.01\n}\nlogistic_pipeline = Pipeline(steps=[\n    (\"scaler\", StandardScaler()),\n    (\"logistic_regression\", LogisticRegression(**params))\n])\n\nlogistic_pipeline.fit(X_train, y_train)\n\nvoting_clf = VotingClassifier(\n    estimators=[('logreg', logistic_pipeline), ('catboost', catboost_pipeline)],\n    voting='soft' # \n)\n\n\nvoting_clf.fit(X_train, y_train)\n\ny_pred = voting_clf.predict(X_valid)\n\nprint('roc_auc for logreg + catboost:', roc_auc_score(y_valid, y_pred))","metadata":{"execution":{"iopub.status.busy":"2024-04-04T20:16:57.134764Z","iopub.execute_input":"2024-04-04T20:16:57.135185Z","iopub.status.idle":"2024-04-04T20:17:05.646915Z","shell.execute_reply.started":"2024-04-04T20:16:57.135136Z","shell.execute_reply":"2024-04-04T20:17:05.644694Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"отправлю на субмишн логрег","metadata":{}},{"cell_type":"code","source":"X_test = df_test_features_new\ny_test_pred = logistic_pipeline.predict_proba(df_test_features_new)[:, 1]\n\ndf_submission = pd.DataFrame({\"radiant_win_prob\": y_test_pred},\n                                 index=df_test_features.index)\n\nsubmission_filename = \"submission_{}.csv\".format(\n    datetime.datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\"))\ndf_submission.to_csv(submission_filename)\nprint(\"Файл посылки сохранен, как: {}\".format(submission_filename))","metadata":{"execution":{"iopub.status.busy":"2024-04-04T19:54:06.628801Z","iopub.status.idle":"2024-04-04T19:54:06.629124Z","shell.execute_reply.started":"2024-04-04T19:54:06.628966Z","shell.execute_reply":"2024-04-04T19:54:06.628979Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_test = df_test_features_new\ny_test_pred = voting_clf.predict_proba(df_test_features_new)[:, 1]\n\ndf_submission = pd.DataFrame({\"radiant_win_prob\": y_test_pred},\n                                 index=df_test_features.index)\n\nsubmission_filename = \"submission_{}.csv\".format(\n    datetime.datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\"))\ndf_submission.to_csv(submission_filename)\nprint(\"Файл посылки сохранен, как: {}\".format(submission_filename))","metadata":{"execution":{"iopub.status.busy":"2024-04-04T20:17:12.093682Z","iopub.execute_input":"2024-04-04T20:17:12.094096Z","iopub.status.idle":"2024-04-04T20:17:12.235133Z","shell.execute_reply.started":"2024-04-04T20:17:12.094064Z","shell.execute_reply":"2024-04-04T20:17:12.233983Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Открою json ","metadata":{}},{"cell_type":"code","source":"with open(os.path.join(PATH_TO_DATA, \"train_raw_data.jsonl\")) as fin:\n    # прочтем 419 строку\n    for i in range(419):\n        line = fin.readline()\n\n    # переведем JSON в питоновский словарь\n    match = json.loads(line)","metadata":{"execution":{"iopub.status.busy":"2024-04-04T20:23:54.462099Z","iopub.execute_input":"2024-04-04T20:23:54.462541Z","iopub.status.idle":"2024-04-04T20:23:54.865080Z","shell.execute_reply.started":"2024-04-04T20:23:54.462510Z","shell.execute_reply":"2024-04-04T20:23:54.863543Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"player = match[\"players\"][9]\nplayer[\"kills\"], player[\"deaths\"], player[\"assists\"]","metadata":{"execution":{"iopub.status.busy":"2024-04-04T20:23:56.222906Z","iopub.execute_input":"2024-04-04T20:23:56.223350Z","iopub.status.idle":"2024-04-04T20:23:56.231111Z","shell.execute_reply.started":"2024-04-04T20:23:56.223316Z","shell.execute_reply":"2024-04-04T20:23:56.229998Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"player[\"ability_uses\"]","metadata":{"execution":{"iopub.status.busy":"2024-04-04T20:24:16.238601Z","iopub.execute_input":"2024-04-04T20:24:16.239599Z","iopub.status.idle":"2024-04-04T20:24:16.247196Z","shell.execute_reply.started":"2024-04-04T20:24:16.239561Z","shell.execute_reply":"2024-04-04T20:24:16.246056Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for i, player in enumerate(match[\"players\"]):\n    plt.plot(player[\"times\"], player[\"xp_t\"], label=str(i+1))\n\nplt.legend()\nplt.xlabel(\"Time, s\")\nplt.ylabel(\"XP\")\nplt.title(\"XP change for all players\");","metadata":{"execution":{"iopub.status.busy":"2024-04-04T20:24:33.741876Z","iopub.execute_input":"2024-04-04T20:24:33.743139Z","iopub.status.idle":"2024-04-04T20:24:34.275416Z","shell.execute_reply.started":"2024-04-04T20:24:33.743102Z","shell.execute_reply":"2024-04-04T20:24:34.274249Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"try:\n    import ujson as json\nexcept ModuleNotFoundError:\n    import json\n    print (\"Подумайте об установке ujson, чтобы работать с JSON объектами быстрее\")\n\ntry:\n    from tqdm.notebook import tqdm\nexcept ModuleNotFoundError:\n    tqdm_notebook = lambda x: x\n    print (\"Подумайте об установке tqdm, чтобы следить за прогрессом\")\n\n\ndef read_matches(matches_file, total_matches=31698, n_matches_to_read=None):\n    \"\"\"\n    Аргуент\n    -------\n    matches_file: JSON файл с сырыми данными\n\n    Результат\n    ---------\n    Возвращает записи о каждом матче\n    \"\"\"\n\n    if n_matches_to_read is None:\n        n_matches_to_read = total_matches\n\n    c = 0\n    with open(matches_file) as fin:\n        for line in tqdm(fin, total=total_matches):\n            if c >= n_matches_to_read:\n                break\n            else:\n                c += 1\n                yield json.loads(line)","metadata":{"execution":{"iopub.status.busy":"2024-04-04T20:25:13.824419Z","iopub.execute_input":"2024-04-04T20:25:13.824821Z","iopub.status.idle":"2024-04-04T20:25:13.851798Z","shell.execute_reply.started":"2024-04-04T20:25:13.824788Z","shell.execute_reply":"2024-04-04T20:25:13.850293Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def add_new_features(df_features, matches_file):\n    \"\"\"\n    Аргуенты\n    -------\n    df_features: таблица с данными\n    matches_file: JSON файл с сырыми данными\n\n    Результат\n    ---------\n    Добавляет новые признаки в таблицу\n    \"\"\"\n\n    for match in read_matches(matches_file, total_matches = df_features.shape[0]):\n        match_id_hash = match['match_id_hash']\n\n        # Посчитаем количество разрушенных вышек обеими командами\n        radiant_tower_kills = 0\n        dire_tower_kills = 0\n        for objective in match[\"objectives\"]:\n            if objective[\"type\"] == \"CHAT_MESSAGE_TOWER_KILL\":\n                if objective[\"team\"] == 2:\n                    radiant_tower_kills += 1\n                if objective[\"team\"] == 3:\n                    dire_tower_kills += 1\n\n        df_features.loc[match_id_hash, \"radiant_tower_kills\"] = radiant_tower_kills\n        df_features.loc[match_id_hash, \"dire_tower_kills\"] = dire_tower_kills\n        df_features.loc[match_id_hash, \"diff_tower_kills\"] = radiant_tower_kills - dire_tower_kills","metadata":{"execution":{"iopub.status.busy":"2024-04-04T20:58:18.455140Z","iopub.execute_input":"2024-04-04T20:58:18.456495Z","iopub.status.idle":"2024-04-04T20:58:18.474072Z","shell.execute_reply.started":"2024-04-04T20:58:18.456435Z","shell.execute_reply":"2024-04-04T20:58:18.471727Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Скопируем таблицу с признаками\ndf_train_features_extended = data.copy()\n\n# Добавим новые\nadd_new_features(df_train_features_extended,\n                 os.path.join(PATH_TO_DATA,\n                              \"train_raw_data.jsonl\"))","metadata":{"execution":{"iopub.status.busy":"2024-04-04T20:27:14.487669Z","iopub.execute_input":"2024-04-04T20:27:14.488283Z","iopub.status.idle":"2024-04-04T20:28:55.517712Z","shell.execute_reply.started":"2024-04-04T20:27:14.488251Z","shell.execute_reply":"2024-04-04T20:28:55.516403Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test_features = pd.read_csv(os.path.join(PATH_TO_DATA, \"test_data.csv\"),\n                                   index_col=\"match_id_hash\")\ndf_test_features_extended = df_test_features.copy()\nadd_new_features(df_test_features_extended,\n                 os.path.join(PATH_TO_DATA,\n                              \"test_raw_data.jsonl\"))","metadata":{"execution":{"iopub.status.busy":"2024-04-04T21:02:31.891468Z","iopub.execute_input":"2024-04-04T21:02:31.891988Z","iopub.status.idle":"2024-04-04T21:02:55.618718Z","shell.execute_reply.started":"2024-04-04T21:02:31.891951Z","shell.execute_reply":"2024-04-04T21:02:55.617463Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cv = ShuffleSplit(n_splits=5, test_size=0.3, random_state=SEED)","metadata":{"execution":{"iopub.status.busy":"2024-04-04T20:33:13.487262Z","iopub.execute_input":"2024-04-04T20:33:13.487705Z","iopub.status.idle":"2024-04-04T20:33:13.493685Z","shell.execute_reply.started":"2024-04-04T20:33:13.487674Z","shell.execute_reply":"2024-04-04T20:33:13.492255Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\ncv_scores_base = cross_val_score(catboost_pipeline, data, y, cv=cv, scoring=\"roc_auc\", n_jobs=-1)\ncv_scores_extended = cross_val_score(catboost_pipeline, df_train_features_extended.values, y,\n                                     cv=cv, scoring=\"roc_auc\", n_jobs=-1)","metadata":{"execution":{"iopub.status.busy":"2024-04-04T20:47:00.267800Z","iopub.execute_input":"2024-04-04T20:47:00.268294Z","iopub.status.idle":"2024-04-04T20:49:02.137187Z","shell.execute_reply.started":"2024-04-04T20:47:00.268260Z","shell.execute_reply":"2024-04-04T20:49:02.135255Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(f\"ROC-AUC на кросс-валидации для базовых признаков: {cv_scores_base.mean()}\")\nprint(f\"ROC-AUC на кросс-валидации для новых признаков: {cv_scores_extended.mean()}\")","metadata":{"execution":{"iopub.status.busy":"2024-04-04T20:49:05.232649Z","iopub.execute_input":"2024-04-04T20:49:05.233144Z","iopub.status.idle":"2024-04-04T20:49:05.241384Z","shell.execute_reply.started":"2024-04-04T20:49:05.233105Z","shell.execute_reply":"2024-04-04T20:49:05.239418Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train, X_valid, y_train, y_valid = train_test_split(df_train_features_extended, y,\n                                                      test_size=0.2,\n                                                      random_state=SEED)\n\n\ncatboost_pipeline.fit(X_train, y_train)\n","metadata":{"execution":{"iopub.status.busy":"2024-04-04T20:59:21.783045Z","iopub.execute_input":"2024-04-04T20:59:21.783613Z","iopub.status.idle":"2024-04-04T20:59:33.695569Z","shell.execute_reply.started":"2024-04-04T20:59:21.783571Z","shell.execute_reply":"2024-04-04T20:59:33.694250Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train_features_extended.shape","metadata":{"execution":{"iopub.status.busy":"2024-04-04T21:00:22.101289Z","iopub.execute_input":"2024-04-04T21:00:22.101707Z","iopub.status.idle":"2024-04-04T21:00:22.110438Z","shell.execute_reply.started":"2024-04-04T21:00:22.101678Z","shell.execute_reply":"2024-04-04T21:00:22.108937Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test_features_extended.shape","metadata":{"execution":{"iopub.status.busy":"2024-04-04T21:03:06.390374Z","iopub.execute_input":"2024-04-04T21:03:06.390806Z","iopub.status.idle":"2024-04-04T21:03:06.397598Z","shell.execute_reply.started":"2024-04-04T21:03:06.390773Z","shell.execute_reply":"2024-04-04T21:03:06.396470Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_test = df_test_features_extended.values\ny_test_pred = catboost_pipeline.predict_proba(X_test)[:, 1]\n\ndf_submission = pd.DataFrame({\"radiant_win_prob\": y_test_pred},\n                                 index=df_test_features.index)\n\nsubmission_filename = \"submission_{}.csv\".format(\n    datetime.datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\"))\ndf_submission.to_csv(submission_filename)\nprint(\"Файл посылки сохранен, как: {}\".format(submission_filename))","metadata":{"execution":{"iopub.status.busy":"2024-04-04T21:03:10.102267Z","iopub.execute_input":"2024-04-04T21:03:10.103685Z","iopub.status.idle":"2024-04-04T21:03:10.188933Z","shell.execute_reply.started":"2024-04-04T21:03:10.103633Z","shell.execute_reply":"2024-04-04T21:03:10.187539Z"},"trusted":true},"execution_count":null,"outputs":[]}]}