{"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":"nvidiaTeslaT4","dataSources":[{"sourceId":72284,"databundleVersionId":7919275,"sourceType":"competition"}],"dockerImageVersionId":30674,"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# 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-04T22:39:05.085149Z","iopub.execute_input":"2024-04-04T22:39:05.085466Z","iopub.status.idle":"2024-04-04T22:39:06.367151Z","shell.execute_reply.started":"2024-04-04T22:39:05.085437Z","shell.execute_reply":"2024-04-04T22:39:06.366205Z"},"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-04T22:39:06.369078Z","iopub.execute_input":"2024-04-04T22:39:06.369608Z","iopub.status.idle":"2024-04-04T22:39:08.488941Z","shell.execute_reply.started":"2024-04-04T22:39:06.369573Z","shell.execute_reply":"2024-04-04T22:39:08.488089Z"},"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-04T22:39:08.490104Z","iopub.execute_input":"2024-04-04T22:39:08.490542Z","iopub.status.idle":"2024-04-04T22:39:13.086275Z","shell.execute_reply.started":"2024-04-04T22:39:08.490504Z","shell.execute_reply":"2024-04-04T22:39:13.085435Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from catboost import CatBoostClassifier","metadata":{"execution":{"iopub.status.busy":"2024-04-04T22:39:13.088455Z","iopub.execute_input":"2024-04-04T22:39:13.088854Z","iopub.status.idle":"2024-04-04T22:39:13.093112Z","shell.execute_reply.started":"2024-04-04T22:39:13.088822Z","shell.execute_reply":"2024-04-04T22:39:13.092160Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"PATH_TO_DATA = '/kaggle/input/copy-of-23-24-ml/'\ntrain = pd.read_csv(os.path.join(PATH_TO_DATA,'train_data.csv'), index_col='match_id_hash')\ntarget = pd.read_csv(os.path.join(PATH_TO_DATA,'train_targets.csv'), index_col='match_id_hash')\ntest = pd.read_csv(os.path.join(PATH_TO_DATA,'test_data.csv'), index_col='match_id_hash')","metadata":{"execution":{"iopub.status.busy":"2024-04-04T22:39:13.094205Z","iopub.execute_input":"2024-04-04T22:39:13.094485Z","iopub.status.idle":"2024-04-04T22:39:14.680916Z","shell.execute_reply.started":"2024-04-04T22:39:13.094455Z","shell.execute_reply":"2024-04-04T22:39:14.679882Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"target['radiant_win'].value_counts()","metadata":{"execution":{"iopub.status.busy":"2024-04-04T22:39:14.681996Z","iopub.execute_input":"2024-04-04T22:39:14.682293Z","iopub.status.idle":"2024-04-04T22:39:14.699356Z","shell.execute_reply.started":"2024-04-04T22:39:14.682268Z","shell.execute_reply":"2024-04-04T22:39:14.698379Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y = target[\"radiant_win\"].values.astype(\"int8\")","metadata":{"execution":{"iopub.status.busy":"2024-04-04T22:39:14.700647Z","iopub.execute_input":"2024-04-04T22:39:14.700988Z","iopub.status.idle":"2024-04-04T22:39:14.709023Z","shell.execute_reply.started":"2024-04-04T22:39:14.700952Z","shell.execute_reply":"2024-04-04T22:39:14.708054Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.shape","metadata":{"execution":{"iopub.status.busy":"2024-04-04T22:39:14.710209Z","iopub.execute_input":"2024-04-04T22:39:14.710475Z","iopub.status.idle":"2024-04-04T22:39:14.721691Z","shell.execute_reply.started":"2024-04-04T22:39:14.710452Z","shell.execute_reply":"2024-04-04T22:39:14.720798Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def read_matches(matches_file):\n    \n    MATCHES_COUNT = {\n        'test_raw_data.jsonl': 7977,\n        'train_raw_data.jsonl': 31698,\n    }\n    _, filename = os.path.split(matches_file)\n    total_matches = MATCHES_COUNT.get(filename)\n    \n    with open(matches_file) as fin:\n        for line in tqdm(fin, total=total_matches):\n            yield json.loads(line)","metadata":{"execution":{"iopub.status.busy":"2024-04-04T22:39:14.722776Z","iopub.execute_input":"2024-04-04T22:39:14.723052Z","iopub.status.idle":"2024-04-04T22:39:14.732639Z","shell.execute_reply.started":"2024-04-04T22:39:14.723027Z","shell.execute_reply":"2024-04-04T22:39:14.731714Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import collections\n\nMATCH_FEATURES = [\n    ('game_time', lambda m: m['game_time']),\n    ('game_mode', lambda m: m['game_mode']),\n    ('lobby_type', lambda m: m['lobby_type']),\n    ('objectives_len', lambda m: len(m['objectives'])),\n    ('chat_len', lambda m: len(m['chat'])),\n]\n\nPLAYER_FIELDS = [\n    'hero_id',\n    \n    'kills',\n    'deaths',\n    'assists',\n    'denies',\n    \n    'gold',\n    'lh',\n    'xp',\n    'health',\n    'max_health',\n    'max_mana',\n    'level',\n\n    'x',\n    'y',\n    \n    'stuns',\n    'creeps_stacked',\n    'camps_stacked',\n    'rune_pickups',\n    'firstblood_claimed',\n    'teamfight_participation',\n    'towers_killed',\n    'roshans_killed',\n    'obs_placed',\n    'sen_placed',\n]\n\ndef extract_features_csv(match):\n    row = [\n        ('match_id_hash', match['match_id_hash']),\n    ]\n    \n    for field, f in MATCH_FEATURES:\n        row.append((field, f(match)))\n        \n    for slot, player in enumerate(match['players']):\n        if slot < 5:\n            player_name = 'r%d' % (slot + 1)\n        else:\n            player_name = 'd%d' % (slot - 4)\n\n        for field in PLAYER_FIELDS:\n            column_name = '%s_%s' % (player_name, field)\n            row.append((column_name, player[field]))\n        row.append((f'{player_name}_ability_level', len(player['ability_upgrades'])))\n        row.append((f'{player_name}_max_hero_hit', player['max_hero_hit']['value']))\n        row.append((f'{player_name}_purchase_count', len(player['purchase_log'])))\n        row.append((f'{player_name}_count_ability_use', sum(player['ability_uses'].values())))\n        row.append((f'{player_name}_damage_dealt', sum(player['damage'].values())))\n        row.append((f'{player_name}_damage_received', sum(player['damage_taken'].values())))\n            \n    return collections.OrderedDict(row)\n    \ndef extract_targets_csv(match, targets):\n    return collections.OrderedDict([('match_id_hash', match['match_id_hash'])] + [\n        (field, targets[field])\n        for field in ['game_time', 'radiant_win', 'duration', 'time_remaining', 'next_roshan_team']\n    ])","metadata":{"execution":{"iopub.status.busy":"2024-04-04T22:39:14.736403Z","iopub.execute_input":"2024-04-04T22:39:14.736751Z","iopub.status.idle":"2024-04-04T22:39:14.848387Z","shell.execute_reply.started":"2024-04-04T22:39:14.736728Z","shell.execute_reply":"2024-04-04T22:39:14.847411Z"},"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","metadata":{"execution":{"iopub.status.busy":"2024-04-04T22:39:14.849432Z","iopub.execute_input":"2024-04-04T22:39:14.849727Z","iopub.status.idle":"2024-04-04T22:39:14.867895Z","shell.execute_reply.started":"2024-04-04T22:39:14.849703Z","shell.execute_reply":"2024-04-04T22:39:14.867075Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\ndf_new_features = []\ndf_new_targets = []\n\nfor match in read_matches(os.path.join(PATH_TO_DATA, 'train_raw_data.jsonl')):\n    match_id_hash = match['match_id_hash']\n    features = extract_features_csv(match)\n    targets = extract_targets_csv(match, match['targets'])\n    \n    df_new_features.append(features)\n    df_new_targets.append(targets)","metadata":{"execution":{"iopub.status.busy":"2024-04-04T22:39:14.869030Z","iopub.execute_input":"2024-04-04T22:39:14.869592Z","iopub.status.idle":"2024-04-04T22:40:29.191788Z","shell.execute_reply.started":"2024-04-04T22:39:14.869561Z","shell.execute_reply":"2024-04-04T22:40:29.190865Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_new_features = pd.DataFrame.from_records(df_new_features).set_index('match_id_hash')\ndf_new_targets = pd.DataFrame.from_records(df_new_targets).set_index('match_id_hash')","metadata":{"execution":{"iopub.status.busy":"2024-04-04T22:40:29.192962Z","iopub.execute_input":"2024-04-04T22:40:29.193263Z","iopub.status.idle":"2024-04-04T22:40:38.274332Z","shell.execute_reply.started":"2024-04-04T22:40:29.193237Z","shell.execute_reply":"2024-04-04T22:40:38.273575Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_new_features = []\nfor match in read_matches(os.path.join(PATH_TO_DATA, 'test_raw_data.jsonl')):\n    match_id_hash = match['match_id_hash']\n    features = extract_features_csv(match)\n    \n    test_new_features.append(features)\ntest_new_features = pd.DataFrame.from_records(test_new_features).set_index('match_id_hash')","metadata":{"execution":{"iopub.status.busy":"2024-04-04T22:40:38.275354Z","iopub.execute_input":"2024-04-04T22:40:38.275613Z","iopub.status.idle":"2024-04-04T22:41:00.894171Z","shell.execute_reply.started":"2024-04-04T22:40:38.275590Z","shell.execute_reply":"2024-04-04T22:41:00.893361Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Удалю бесполезные колонки","metadata":{}},{"cell_type":"code","source":"from sklearn.feature_selection import VarianceThreshold\nsel = VarianceThreshold(threshold=0.1)  # 0.1 indicates 99% of observations approximately\nsel.fit(df_new_features)  # fit finds the features with low variance","metadata":{"execution":{"iopub.status.busy":"2024-04-04T22:41:00.895388Z","iopub.execute_input":"2024-04-04T22:41:00.895706Z","iopub.status.idle":"2024-04-04T22:41:01.048904Z","shell.execute_reply.started":"2024-04-04T22:41:00.895679Z","shell.execute_reply":"2024-04-04T22:41:01.047925Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sum(sel.get_support())","metadata":{"execution":{"iopub.status.busy":"2024-04-04T22:41:01.050039Z","iopub.execute_input":"2024-04-04T22:41:01.050329Z","iopub.status.idle":"2024-04-04T22:41:01.056732Z","shell.execute_reply.started":"2024-04-04T22:41:01.050303Z","shell.execute_reply":"2024-04-04T22:41:01.055843Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#then remove the features from training and test set\ndata_new = sel.transform(df_new_features)\ndf_test_new = sel.transform(test_new_features)","metadata":{"execution":{"iopub.status.busy":"2024-04-04T22:41:01.058169Z","iopub.execute_input":"2024-04-04T22:41:01.058504Z","iopub.status.idle":"2024-04-04T22:41:01.138735Z","shell.execute_reply.started":"2024-04-04T22:41:01.058473Z","shell.execute_reply":"2024-04-04T22:41:01.137712Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Из прошлой тетради видно, что лучшее решение  -  это совмещение catboost + logreg","metadata":{}},{"cell_type":"code","source":"from sklearn.feature_selection import SelectPercentile, f_classif\n\ndata_new2 = SelectPercentile(f_classif, percentile=10).fit_transform(data_new, y)\ndata_new2.shape","metadata":{"execution":{"iopub.status.busy":"2024-04-04T22:41:01.140176Z","iopub.execute_input":"2024-04-04T22:41:01.140461Z","iopub.status.idle":"2024-04-04T22:41:01.273164Z","shell.execute_reply.started":"2024-04-04T22:41:01.140437Z","shell.execute_reply":"2024-04-04T22:41:01.272156Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"SEED = 42\nX_train, X_valid, y_train, y_valid = train_test_split(data_new, 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-04T22:41:01.274269Z","iopub.execute_input":"2024-04-04T22:41:01.274567Z","iopub.status.idle":"2024-04-04T22:41:01.368389Z","shell.execute_reply.started":"2024-04-04T22:41:01.274532Z","shell.execute_reply":"2024-04-04T22:41:01.367479Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"params_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-04T22:41:01.369506Z","iopub.execute_input":"2024-04-04T22:41:01.369814Z","iopub.status.idle":"2024-04-04T22:41:17.694180Z","shell.execute_reply.started":"2024-04-04T22:41:01.369788Z","shell.execute_reply":"2024-04-04T22:41:17.693201Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-04T22:41:17.695790Z","iopub.execute_input":"2024-04-04T22:41:17.696624Z","iopub.status.idle":"2024-04-04T22:41:35.419933Z","shell.execute_reply.started":"2024-04-04T22:41:17.696565Z","shell.execute_reply":"2024-04-04T22:41:35.418930Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\ny_test_pred = catboost_pipeline.predict_proba(df_test_new)[:, 1]\n\ndf_submission = pd.DataFrame({\"radiant_win_prob\": y_test_pred},\n                                 index=test.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-04T22:41:35.421263Z","iopub.execute_input":"2024-04-04T22:41:35.422361Z","iopub.status.idle":"2024-04-04T22:41:35.497446Z","shell.execute_reply.started":"2024-04-04T22:41:35.422319Z","shell.execute_reply":"2024-04-04T22:41:35.496565Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import lightgbm\nfrom bayes_opt import BayesianOptimization","metadata":{"execution":{"iopub.status.busy":"2024-04-04T22:41:35.498597Z","iopub.execute_input":"2024-04-04T22:41:35.498878Z","iopub.status.idle":"2024-04-04T22:41:35.524475Z","shell.execute_reply.started":"2024-04-04T22:41:35.498853Z","shell.execute_reply":"2024-04-04T22:41:35.523567Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"We can find the way to choose parameters in docs:\n\nhttps://lightgbm.readthedocs.io/en/latest/Parameters-Tuning.html\n\nThanks to this kernel: https://www.kaggle.com/qwe1398775315/eda-lgbm-bayesianoptimization","metadata":{}},{"cell_type":"code","source":"def lgb_eval(num_leaves,max_depth,lambda_l2,lambda_l1,min_child_samples, min_data_in_leaf):\n    params = {\n    \"objective\" : \"binary\",\n    \"metric\" : \"auc\", \n    'is_unbalance': True,\n    \"num_leaves\" : int(num_leaves),\n    \"max_depth\" : int(max_depth),\n    \"lambda_l2\" : lambda_l2,\n    \"lambda_l1\" : lambda_l1,\n    \"num_threads\" : 20,\n    \"min_child_samples\" : int(min_child_samples),\n    'min_data_in_leaf': int(min_data_in_leaf),\n    \"learning_rate\" : 0.03,\n    \"subsample_freq\" : 5,\n    \"bagging_seed\" : 42,\n    \"verbosity\" : -1\n    }\n    \n    lgtrain = lightgbm.Dataset(X_train, y_train)\n    cv_result = lightgbm.cv(params,\n                       lgtrain,\n                       10000,\n                       early_stopping_rounds=300,\n                       stratified=True,\n                       nfold=5)\n    return cv_result['auc-mean'][-1]\n\ndef lgb_train(num_leaves,max_depth,lambda_l2,lambda_l1,min_child_samples, min_data_in_leaf):\n    params = {\n    \"objective\" : \"binary\",\n    \"metric\" : \"auc\", \n    'is_unbalance': True,\n    \"num_leaves\" : int(num_leaves),\n    \"max_depth\" : int(max_depth),\n    \"lambda_l2\" : lambda_l2,\n    \"lambda_l1\" : lambda_l1,\n    \"num_threads\" : 20,\n    \"min_child_samples\" : int(min_child_samples),\n    'min_data_in_leaf': int(min_data_in_leaf),\n    \"learning_rate\" : 0.03,\n    \"subsample_freq\" : 5,\n    \"bagging_seed\" : 42,\n    \"verbosity\" : -1\n    }\n    t_x,v_x,t_y,v_y = train_test_split(X_train, y_train,test_size=0.2)\n    lgtrain = lightgbm.Dataset(t_x, t_y)\n    lgvalid = lightgbm.Dataset(v_x, v_y)\n    model = lightgbm.train(params, lgtrain, 4000, valid_sets=[lgvalid])\n    pred_test_y = model.predict(X_test, num_iteration=model.best_iteration)\n    return pred_test_y, model\n    \ndef param_tuning(init_points,num_iter,**args):\n    lgbBO = BayesianOptimization(lgb_eval, {'num_leaves': (15, 200),\n                                                'max_depth': (5, 63),\n                                                'lambda_l2': (0.0, 5),\n                                                'lambda_l1': (0.0, 5),\n                                                'min_child_samples': (50, 5000),\n                                                'min_data_in_leaf': (50, 300)\n                                                })\n\n    lgbBO.maximize(init_points=init_points, n_iter=num_iter,**args)\n    return lgbBO","metadata":{"execution":{"iopub.status.busy":"2024-04-04T22:41:35.525708Z","iopub.execute_input":"2024-04-04T22:41:35.525962Z","iopub.status.idle":"2024-04-04T22:41:35.538675Z","shell.execute_reply.started":"2024-04-04T22:41:35.525939Z","shell.execute_reply":"2024-04-04T22:41:35.537586Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"params = {'lambda_l1': 3.3483782188386053,\n 'lambda_l2': 0.4710921246688088,\n 'max_depth': 61.1702877191018,\n 'min_child_samples': 85.41278882818256,\n 'min_data_in_leaf': 297.8755555483252,\n 'num_leaves': 25.672866108605408}","metadata":{"execution":{"iopub.status.busy":"2024-04-04T22:41:35.541017Z","iopub.execute_input":"2024-04-04T22:41:35.541788Z","iopub.status.idle":"2024-04-04T22:41:35.552443Z","shell.execute_reply.started":"2024-04-04T22:41:35.541733Z","shell.execute_reply":"2024-04-04T22:41:35.551573Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_test = df_test_new","metadata":{"execution":{"iopub.status.busy":"2024-04-04T22:41:35.553507Z","iopub.execute_input":"2024-04-04T22:41:35.553878Z","iopub.status.idle":"2024-04-04T22:41:35.563155Z","shell.execute_reply.started":"2024-04-04T22:41:35.553854Z","shell.execute_reply":"2024-04-04T22:41:35.562407Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred_test_y1, _ = lgb_train(**params)\npred_test_y2, _ = lgb_train(**params)\npred_test_y3, model = lgb_train(**params)\ny_pred = (pred_test_y1 + pred_test_y2 + pred_test_y3)/3","metadata":{"execution":{"iopub.status.busy":"2024-04-04T23:06:01.917412Z","iopub.execute_input":"2024-04-04T23:06:01.918249Z","iopub.status.idle":"2024-04-04T23:14:49.251025Z","shell.execute_reply.started":"2024-04-04T23:06:01.918199Z","shell.execute_reply":"2024-04-04T23:14:49.250105Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_submission_extended = pd.DataFrame(\n    {'radiant_win_prob': y_pred}, \n    index=test.index)\ndf_submission_extended.to_csv('submission.csv')","metadata":{"execution":{"iopub.status.busy":"2024-04-04T22:46:15.245388Z","iopub.status.idle":"2024-04-04T22:46:15.245705Z","shell.execute_reply.started":"2024-04-04T22:46:15.245552Z","shell.execute_reply":"2024-04-04T22:46:15.245565Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"param = {\n        'bagging_freq': 5,  #handling overfitting\n        'bagging_fraction': 0.5,  #handling overfitting - adding some noise\n        'boost_from_average':'false',\n        'boost': 'gbdt',\n        'feature_fraction': 0.05, #handling overfitting\n        'learning_rate': 0.01,  #the changes between one auc and a better one gets really small thus a small learning rate performs better\n        'max_depth': -1,  \n        'metric':'auc',\n        'min_data_in_leaf': 50,\n        'min_sum_hessian_in_leaf': 10.0,\n        'num_leaves': 10,\n        'num_threads': 5,\n        'tree_learner': 'serial',\n        'objective': 'binary', \n        'verbosity': 1\n    }","metadata":{"execution":{"iopub.status.busy":"2024-04-04T22:46:21.187070Z","iopub.execute_input":"2024-04-04T22:46:21.187454Z","iopub.status.idle":"2024-04-04T22:46:21.193538Z","shell.execute_reply.started":"2024-04-04T22:46:21.187424Z","shell.execute_reply":"2024-04-04T22:46:21.192592Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from lightgbm import LGBMClassifier\nparams = {#'num_leaves': 31, # number of leaves in full tree (31 by default) \n         'learning_rate': 0.01, #this determines the impact of each tree on the final outcome. \n        'n_jobs' : -1,\n         'min_data_in_leaf': 50,\n         'min_sum_hessian_in_leaf': 12.0,\n         'objective': 'binary', \n         'max_depth': -1,\n         'boosting': 'gbdt', #'dart' \n         'bagging_freq': 5,\n         'bagging_fraction': 0.81,\n         'boost_from_average':'false',\n         'bagging_seed': 17,\n         'metric': 'auc',\n         'verbosity': -1,\n         }","metadata":{"execution":{"iopub.status.busy":"2024-04-04T22:46:15.248658Z","iopub.status.idle":"2024-04-04T22:46:15.249110Z","shell.execute_reply.started":"2024-04-04T22:46:15.248878Z","shell.execute_reply":"2024-04-04T22:46:15.248896Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"best_params={'bagging_temperature': 0.41010395885331385,\n 'border_count': 186,\n 'depth': 8,\n 'iterations': 323,\n 'l2_leaf_reg': 21,\n 'learning_rate': 0.0673344419215237,\n 'random_strength': 3.230824361824754e-06,\n 'scale_pos_weight': 0.7421091918485163}\nbest_params['iterations']=1000","metadata":{"execution":{"iopub.status.busy":"2024-04-04T22:46:26.686548Z","iopub.execute_input":"2024-04-04T22:46:26.687177Z","iopub.status.idle":"2024-04-04T22:46:26.692324Z","shell.execute_reply.started":"2024-04-04T22:46:26.687143Z","shell.execute_reply":"2024-04-04T22:46:26.691217Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tuned_model = CatBoostClassifier(**best_params,task_type = \"GPU\",od_type='Iter',one_hot_max_size=10, verbose = 0)\ntuned_model.fit(train,y)","metadata":{"execution":{"iopub.status.busy":"2024-04-04T22:50:30.074209Z","iopub.execute_input":"2024-04-04T22:50:30.074592Z","iopub.status.idle":"2024-04-04T22:52:26.852241Z","shell.execute_reply.started":"2024-04-04T22:50:30.074557Z","shell.execute_reply":"2024-04-04T22:52:26.851364Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def submit_predictions(name,model):\n    df_test_features = pd.read_csv(os.path.join(PATH_TO_DATA, 'test_data.csv'), \n                                   index_col='match_id_hash')\n    X_test = df_test_features.values\n    y_test_pred = model.predict_proba(X_test)[:, 1]\n\n    df_submission = pd.DataFrame({'radiant_win_prob': y_test_pred}, \n                                 index=df_test_features.index)\n    submission_filename = 'submission_{}.csv'.format(name)\n    df_submission.to_csv(submission_filename)\n    print('Submission saved to {}'.format(submission_filename))","metadata":{"execution":{"iopub.status.busy":"2024-04-04T22:55:40.445427Z","iopub.execute_input":"2024-04-04T22:55:40.446326Z","iopub.status.idle":"2024-04-04T22:55:40.452295Z","shell.execute_reply.started":"2024-04-04T22:55:40.446292Z","shell.execute_reply":"2024-04-04T22:55:40.451211Z"},"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')\nX_test = df_test_features.values\ny_test_pred = tuned_model.predict_proba(X_test)[:, 1]\ny_pred_pred = (pred_test_y1 + pred_test_y2 + pred_test_y3 + y_test_pred )/4\ndf_submission = pd.DataFrame({'radiant_win_prob': y_pred_pred}, \n                                 index=df_test_features.index)\nsubmission_filename = 'submission_{}.csv'.format('ssss')\ndf_submission.to_csv(submission_filename)\nprint('Submission saved to {}'.format(submission_filename))","metadata":{"execution":{"iopub.status.busy":"2024-04-05T00:57:41.634010Z","iopub.execute_input":"2024-04-05T00:57:41.634358Z","iopub.status.idle":"2024-04-05T00:57:41.978246Z","shell.execute_reply.started":"2024-04-05T00:57:41.634312Z","shell.execute_reply":"2024-04-05T00:57:41.977005Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submit_predictions('tuned_cat_boost',model=tuned_model)","metadata":{"execution":{"iopub.status.busy":"2024-04-04T22:55:44.317300Z","iopub.execute_input":"2024-04-04T22:55:44.317767Z","iopub.status.idle":"2024-04-04T22:55:44.607685Z","shell.execute_reply.started":"2024-04-04T22:55:44.317738Z","shell.execute_reply":"2024-04-04T22:55:44.606674Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}