{"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":"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)\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport gc\n\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-16T11:24:36.692863Z","iopub.execute_input":"2022-11-16T11:24:36.693396Z","iopub.status.idle":"2022-11-16T11:24:37.588215Z","shell.execute_reply.started":"2022-11-16T11:24:36.693296Z","shell.execute_reply":"2022-11-16T11:24:37.587196Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = pd.read_csv('/kaggle/input/digital-turbine-auction-bid-price-prediction/train_data.csv')\n\ntest = pd.read_csv('/kaggle/input/digital-turbine-auction-bid-price-prediction/test_data.csv')","metadata":{"execution":{"iopub.status.busy":"2022-11-16T11:24:40.886004Z","iopub.execute_input":"2022-11-16T11:24:40.886404Z","iopub.status.idle":"2022-11-16T11:25:10.025957Z","shell.execute_reply.started":"2022-11-16T11:24:40.886364Z","shell.execute_reply":"2022-11-16T11:25:10.024788Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.info(null_counts=True)","metadata":{"execution":{"iopub.status.busy":"2022-11-16T11:25:15.075127Z","iopub.execute_input":"2022-11-16T11:25:15.075547Z","iopub.status.idle":"2022-11-16T11:25:18.208481Z","shell.execute_reply.started":"2022-11-16T11:25:15.075507Z","shell.execute_reply":"2022-11-16T11:25:18.207291Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Remove the Null rows as the data is huge, I can just remove them\ntrain.dropna(axis=0, inplace=True)\ntrain.reset_index(inplace=True, drop=True)\nprint(train.info(null_counts=True))","metadata":{"execution":{"iopub.status.busy":"2022-11-16T11:25:20.303051Z","iopub.execute_input":"2022-11-16T11:25:20.303472Z","iopub.status.idle":"2022-11-16T11:25:30.751357Z","shell.execute_reply.started":"2022-11-16T11:25:20.303435Z","shell.execute_reply":"2022-11-16T11:25:30.750257Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Reduce the data types as its not required to have large chunks of memory for almost all of them.\ndef Reduce_Memory(df):\n    for col in df.columns:\n        if col != 'eventTimestamp':\n            if df[col].dtype == 'object':\n                df[col] = df[col].astype('category')\n            if df[col].dtype == 'int64':\n                df[col] = df[col].astype('int8')\n            if df[col].dtype == 'float64':\n                df[col] = df[col].astype('float16')\n    df.info(verbose=True)","metadata":{"execution":{"iopub.status.busy":"2022-11-16T11:25:39.608091Z","iopub.execute_input":"2022-11-16T11:25:39.608547Z","iopub.status.idle":"2022-11-16T11:25:39.615663Z","shell.execute_reply.started":"2022-11-16T11:25:39.608481Z","shell.execute_reply":"2022-11-16T11:25:39.614260Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Reduce_Memory(train)","metadata":{"execution":{"iopub.status.busy":"2022-11-16T11:25:42.225539Z","iopub.execute_input":"2022-11-16T11:25:42.226586Z","iopub.status.idle":"2022-11-16T11:26:01.054159Z","shell.execute_reply.started":"2022-11-16T11:25:42.226532Z","shell.execute_reply":"2022-11-16T11:26:01.053084Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Reduce_Memory(test)","metadata":{"execution":{"iopub.status.busy":"2022-11-16T11:26:03.128932Z","iopub.execute_input":"2022-11-16T11:26:03.129317Z","iopub.status.idle":"2022-11-16T11:26:03.278663Z","shell.execute_reply.started":"2022-11-16T11:26:03.129284Z","shell.execute_reply":"2022-11-16T11:26:03.277563Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"gc.collect()","metadata":{"execution":{"iopub.status.busy":"2022-11-16T11:26:07.497033Z","iopub.execute_input":"2022-11-16T11:26:07.497425Z","iopub.status.idle":"2022-11-16T11:26:07.613167Z","shell.execute_reply.started":"2022-11-16T11:26:07.497391Z","shell.execute_reply":"2022-11-16T11:26:07.612055Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def process_timestamp(df):\n    df['event_date'] = pd.to_datetime(df['eventTimestamp'], unit='ms')\n    df['event_month'] = df['event_date'].dt.strftime('%m').astype('int8')\n    df['event_day'] = df['event_date'].dt.dayofweek+1\n    df['event_day'] = df['event_day'].astype('int8')\n    df['event_hour'] = df['event_date'].dt.strftime('%H')\n    df['event_hour'] = df['event_hour'].astype('int8')\n    return df","metadata":{"execution":{"iopub.status.busy":"2022-11-16T11:26:10.500824Z","iopub.execute_input":"2022-11-16T11:26:10.501441Z","iopub.status.idle":"2022-11-16T11:26:10.513010Z","shell.execute_reply.started":"2022-11-16T11:26:10.501394Z","shell.execute_reply":"2022-11-16T11:26:10.511835Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = process_timestamp(train)\ntest = process_timestamp(test)\ntrain.info(verbose=True)","metadata":{"execution":{"iopub.status.busy":"2022-11-16T11:26:13.603893Z","iopub.execute_input":"2022-11-16T11:26:13.604277Z","iopub.status.idle":"2022-11-16T11:27:20.245890Z","shell.execute_reply.started":"2022-11-16T11:26:13.604245Z","shell.execute_reply":"2022-11-16T11:27:20.244702Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.drop(columns='eventTimestamp', inplace=True)\ntest.drop(columns='eventTimestamp', inplace=True)\ntrain.info(verbose=True)","metadata":{"execution":{"iopub.status.busy":"2022-11-16T11:27:34.819444Z","iopub.execute_input":"2022-11-16T11:27:34.820451Z","iopub.status.idle":"2022-11-16T11:27:35.000427Z","shell.execute_reply.started":"2022-11-16T11:27:34.820412Z","shell.execute_reply":"2022-11-16T11:27:34.999222Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"gc.collect()","metadata":{"execution":{"iopub.status.busy":"2022-11-16T11:27:37.857011Z","iopub.execute_input":"2022-11-16T11:27:37.857420Z","iopub.status.idle":"2022-11-16T11:27:37.972780Z","shell.execute_reply.started":"2022-11-16T11:27:37.857381Z","shell.execute_reply":"2022-11-16T11:27:37.971558Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import statistics\n# Calculate the occurence of deviceIds on train data and convert deviceId column to numerical occurance column\nocc_counts = train.groupby('deviceId')['deviceId'].count().tolist()\nocc_counts.sort()\nplt.hist(occ_counts, range=(0, 50))\nplt.show()\n\nprint('Mean : ', statistics.mean(occ_counts))\nprint('Median : ', statistics.median(occ_counts))\nprint('Single Mode : ', statistics.mode(occ_counts))\ndel occ_counts\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2022-11-16T11:27:41.436861Z","iopub.execute_input":"2022-11-16T11:27:41.437271Z","iopub.status.idle":"2022-11-16T11:27:41.990817Z","shell.execute_reply.started":"2022-11-16T11:27:41.437240Z","shell.execute_reply":"2022-11-16T11:27:41.989782Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Encode the deviceIds depending on their frequency. As the plot is not uniform, I will use the median value as a limit. If deviceId occurs more than Median 18, train['frequent'] = 1 \n# I will encode the test set also according to the training set.\nfreq_devices = []\nfrequency_count = train['deviceId'].value_counts()\nfor idx, deviceId in enumerate(frequency_count.index.tolist()):\n    if frequency_count[idx] > 18:\n        freq_devices.append(deviceId)\nlen(freq_devices)","metadata":{"execution":{"iopub.status.busy":"2022-11-16T11:27:43.886545Z","iopub.execute_input":"2022-11-16T11:27:43.887598Z","iopub.status.idle":"2022-11-16T11:27:44.057378Z","shell.execute_reply.started":"2022-11-16T11:27:43.887537Z","shell.execute_reply":"2022-11-16T11:27:44.056422Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train['frequent_user'] = train.groupby('deviceId')['deviceId'].transform('count')\ntrain['frequent_user'] = train['frequent_user'].apply(lambda x : 1 if x > 18 else 0)\ntrain['frequent_user'] = train['frequent_user'].astype('int8')\ntrain.head()","metadata":{"execution":{"iopub.status.busy":"2022-11-16T11:27:46.975116Z","iopub.execute_input":"2022-11-16T11:27:46.975571Z","iopub.status.idle":"2022-11-16T11:27:49.796445Z","shell.execute_reply.started":"2022-11-16T11:27:46.975534Z","shell.execute_reply":"2022-11-16T11:27:49.795217Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test['frequent_user'] = 0\ntest['frequent_user'] = test['deviceId'].apply(lambda x: 1 if x in freq_devices else 0)\ntest['frequent_user'] = test['frequent_user'].astype('int8')\ntest.head()\n\ndel freq_devices\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2022-11-16T11:27:54.819957Z","iopub.execute_input":"2022-11-16T11:27:54.820352Z","iopub.status.idle":"2022-11-16T11:28:12.307459Z","shell.execute_reply.started":"2022-11-16T11:27:54.820320Z","shell.execute_reply":"2022-11-16T11:28:12.306460Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train['frequent_user'].corr(train['winBid'])","metadata":{"execution":{"iopub.status.busy":"2022-11-16T11:19:08.525727Z","iopub.execute_input":"2022-11-16T11:19:08.526766Z","iopub.status.idle":"2022-11-16T11:19:08.692760Z","shell.execute_reply.started":"2022-11-16T11:19:08.526723Z","shell.execute_reply":"2022-11-16T11:19:08.691437Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cat_var = ['unitDisplayType', 'brandName', 'bundleId', 'appVersion', 'correctModelName', 'countryCode', 'osAndVersion', 'connectionType', 'c1', 'c3', 'size', 'mediationProviderVersion']\nnum_var = ['eventTimeStamp', 'c2', 'c4', 'bidFloorPrice', 'sentPrice', 'has_won', 'winBid', 'event_month', 'event_day', 'event_hour', 'frequent_user']","metadata":{"execution":{"iopub.status.busy":"2022-11-16T11:28:18.896402Z","iopub.execute_input":"2022-11-16T11:28:18.897475Z","iopub.status.idle":"2022-11-16T11:28:18.903799Z","shell.execute_reply.started":"2022-11-16T11:28:18.897433Z","shell.execute_reply":"2022-11-16T11:28:18.902293Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sns.heatmap(train.corr()[['winBid']].sort_values(by='winBid', ascending=False), vmin=-1, vmax=1, annot=True, cmap='BrBG')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-11-16T11:19:16.207193Z","iopub.execute_input":"2022-11-16T11:19:16.208354Z","iopub.status.idle":"2022-11-16T11:19:18.694342Z","shell.execute_reply.started":"2022-11-16T11:19:16.208306Z","shell.execute_reply":"2022-11-16T11:19:18.693046Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from scipy.stats import f_oneway\n# I apply ANOVE test on catergorical data to check if they are correlated to the target.\n# H0 - categories have same/similar mean values, which means they are not correlated with the target.\n# Ha - one or all categories have different means\n# If the P-value resulting from ANOVA test is less than 0.05, I will reject H0 and keep the categorical features as it is correlated to the target.\nfor cat in cat_var:\n    anova = f_oneway(*(train.groupby(cat)['winBid'].apply(list)))\n    print(f\"{cat}'s p-value : \", anova[1])\n    \ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2022-11-16T08:00:05.427974Z","iopub.execute_input":"2022-11-16T08:00:05.428330Z","iopub.status.idle":"2022-11-16T08:00:22.135312Z","shell.execute_reply.started":"2022-11-16T08:00:05.428298Z","shell.execute_reply":"2022-11-16T08:00:22.134465Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"As all categorical variables are correlated to target variable, I will keep them.","metadata":{}},{"cell_type":"markdown","source":"As the data is quite large and kaggle allowed RAM is not enough, I will need to reduce the categorical features. Due to the large number of categories in some of the features, it will be difficult to make \nthem One Hot Encoded and utilize all.\nFor this limitation, I will One Hot Encode N top categories.","metadata":{}},{"cell_type":"code","source":"top_10s = {}\nfor cat in cat_var:\n    top_10s[cat] = [x for x in train[cat].value_counts().sort_values(ascending=False).head(10).index]\nprint(top_10s)\nfor key, val in top_10s.items():\n    print(f\"{key} = {len(val)}\")","metadata":{"execution":{"iopub.status.busy":"2022-11-16T11:28:26.118205Z","iopub.execute_input":"2022-11-16T11:28:26.118628Z","iopub.status.idle":"2022-11-16T11:28:26.638948Z","shell.execute_reply.started":"2022-11-16T11:28:26.118594Z","shell.execute_reply":"2022-11-16T11:28:26.636790Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def one_hot_top_x(df, variable, top_x_labels):\n    # Function to create dummy variables for desired number of most frequent categories\n    \n    for label in top_x_labels:\n        df[variable+'_'+label] = np.where(df[variable]==label, 1, 0)\n        df[variable+'_'+label] = df[variable+'_'+label].astype('int8')","metadata":{"execution":{"iopub.status.busy":"2022-11-16T11:28:29.301959Z","iopub.execute_input":"2022-11-16T11:28:29.302355Z","iopub.status.idle":"2022-11-16T11:28:29.308764Z","shell.execute_reply.started":"2022-11-16T11:28:29.302323Z","shell.execute_reply":"2022-11-16T11:28:29.307431Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for cat in cat_var:\n    one_hot_top_x(train, cat, top_10s[cat])\n    train.drop(columns=[cat], inplace=True)\nprint(train.info(verbose=True))","metadata":{"execution":{"iopub.status.busy":"2022-11-16T11:28:34.052983Z","iopub.execute_input":"2022-11-16T11:28:34.053732Z","iopub.status.idle":"2022-11-16T11:28:48.648360Z","shell.execute_reply.started":"2022-11-16T11:28:34.053691Z","shell.execute_reply":"2022-11-16T11:28:48.647201Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for cat in cat_var:\n    one_hot_top_x(test, cat, top_10s[cat])\n    test.drop(columns=[cat], inplace=True)\nprint(test.info(verbose=True))","metadata":{"execution":{"iopub.status.busy":"2022-11-16T11:30:01.145702Z","iopub.execute_input":"2022-11-16T11:30:01.146785Z","iopub.status.idle":"2022-11-16T11:30:01.302012Z","shell.execute_reply.started":"2022-11-16T11:30:01.146742Z","shell.execute_reply":"2022-11-16T11:30:01.300879Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig, ax = plt.subplots(figsize=(40, 40))\nsns.heatmap(train.corr()[['winBid']].sort_values(by='winBid', ascending=False), vmin=-1, vmax=1, annot=True, cmap='BrBG', ax=ax)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-11-16T08:01:46.429048Z","iopub.execute_input":"2022-11-16T08:01:46.429407Z","iopub.status.idle":"2022-11-16T08:05:10.176472Z","shell.execute_reply.started":"2022-11-16T08:01:46.429376Z","shell.execute_reply":"2022-11-16T08:05:10.175580Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"gc.collect()","metadata":{"execution":{"iopub.status.busy":"2022-11-16T11:30:07.627472Z","iopub.execute_input":"2022-11-16T11:30:07.628826Z","iopub.status.idle":"2022-11-16T11:30:07.748094Z","shell.execute_reply.started":"2022-11-16T11:30:07.628779Z","shell.execute_reply":"2022-11-16T11:30:07.746918Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"features = train.columns.values.tolist()\nfeatures.remove('deviceId')\nfeatures.remove('has_won')\nfeatures.remove('winBid')\nfeatures.remove('event_date')\nfeatures","metadata":{"execution":{"iopub.status.busy":"2022-11-16T11:30:10.453934Z","iopub.execute_input":"2022-11-16T11:30:10.454327Z","iopub.status.idle":"2022-11-16T11:30:10.463579Z","shell.execute_reply.started":"2022-11-16T11:30:10.454293Z","shell.execute_reply":"2022-11-16T11:30:10.462512Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.info(verbose=True)","metadata":{"execution":{"iopub.status.busy":"2022-11-16T08:05:27.114553Z","iopub.execute_input":"2022-11-16T08:05:27.115148Z","iopub.status.idle":"2022-11-16T08:05:27.129337Z","shell.execute_reply.started":"2022-11-16T08:05:27.115112Z","shell.execute_reply":"2022-11-16T08:05:27.128023Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nfrom sklearn import linear_model, metrics\nfrom sklearn.linear_model import LinearRegression\nfrom xgboost import XGBRegressor\n\nfrom numpy import mean\nfrom numpy import absolute\nfrom numpy import sqrt\n\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2022-11-16T11:30:20.451153Z","iopub.execute_input":"2022-11-16T11:30:20.451580Z","iopub.status.idle":"2022-11-16T11:30:20.857632Z","shell.execute_reply.started":"2022-11-16T11:30:20.451546Z","shell.execute_reply":"2022-11-16T11:30:20.856451Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_train = train[['winBid']]","metadata":{"execution":{"iopub.status.busy":"2022-11-16T11:30:24.961035Z","iopub.execute_input":"2022-11-16T11:30:24.961439Z","iopub.status.idle":"2022-11-16T11:30:24.977469Z","shell.execute_reply.started":"2022-11-16T11:30:24.961405Z","shell.execute_reply":"2022-11-16T11:30:24.976427Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.preprocessing import StandardScaler\n\nX_train, X_test, Y_train, Y_test = train_test_split(train[features], y_train, test_size=0.4, random_state=1)\n\nx_scaler = StandardScaler().fit(X_train)\ny_scaler = StandardScaler().fit(Y_train)\n\nX_train_scaled = x_scaler.transform(X_train)\nY_train_scaled = y_scaler.transform(Y_train)\n\nX_test_scaled = x_scaler.transform(X_test)\nY_test_scaled = y_scaler.transform(Y_test)\n\n\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2022-11-16T11:30:28.832135Z","iopub.execute_input":"2022-11-16T11:30:28.832555Z","iopub.status.idle":"2022-11-16T11:31:12.975544Z","shell.execute_reply.started":"2022-11-16T11:30:28.832516Z","shell.execute_reply":"2022-11-16T11:31:12.974444Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"For base model, I use Linear Regression for multiple variables to see if a simple model can be used for this data.","metadata":{}},{"cell_type":"code","source":"# create linear regression object\nreg = LinearRegression()\n  \n# train the model using the training sets\nreg.fit(X_train_scaled, Y_train_scaled)\n  \n# regression coefficients\n#print('Coefficients: ', reg.coef_)\n  \n# variance score: 1 means perfect prediction\nprint('Variance score: {}'.format(reg.score(X_test_scaled, Y_test_scaled)))\n  \n# plot for residual error\n \nplt.figure(figsize=(40, 40))\n## setting plot style\nplt.style.use('fivethirtyeight')\n  \n## plotting residual errors in training data\nplt.scatter(reg.predict(X_train_scaled), reg.predict(X_train_scaled) - Y_train_scaled,\n            color = \"blue\", s = 10, label = 'Train data')\n  \n## plotting residual errors in test data\nplt.scatter(reg.predict(X_test_scaled), reg.predict(X_test_scaled) - Y_test_scaled,\n            color = \"red\", s = 10, label = 'Test data')\n  \n## plotting line for zero residual error\nplt.hlines(y = 0, xmin = 0, xmax = 50, linewidth = 2)\n  \n## plotting legend\nplt.legend(loc = 'upper right')\n  \n## plot title\nplt.title(\"Residual errors\")\n  \n## method call for showing the plot\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-11-16T08:08:11.260190Z","iopub.execute_input":"2022-11-16T08:08:11.260577Z","iopub.status.idle":"2022-11-16T08:09:10.798340Z","shell.execute_reply.started":"2022-11-16T08:08:11.260544Z","shell.execute_reply":"2022-11-16T08:09:10.797411Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import GridSearchCV\nimport warnings\nwarnings.filterwarnings('ignore')\n\nregressor = XGBRegressor(eval_metric='mae', tree_method='gpu_hist', seed=42)\n\nparam_grid = {'max_depth' : [6, 7],\n             'n_estimators' : [600, 700],\n             'learning_rate': [0.005, 0.007]\n             }\n\nsearch = GridSearchCV(regressor, param_grid, cv=5).fit(X_train, Y_train)\n\nprint('The best parameters : ', search.best_params_)","metadata":{"execution":{"iopub.status.busy":"2022-11-16T09:42:12.031969Z","iopub.execute_input":"2022-11-16T09:42:12.032349Z","iopub.status.idle":"2022-11-16T10:21:34.199812Z","shell.execute_reply.started":"2022-11-16T09:42:12.032318Z","shell.execute_reply":"2022-11-16T10:21:34.198724Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"regressor = XGBRegressor(eval_metric='mae', tree_method='gpu_hist',learning_rate=search.best_params_['learning_rate'],\n                        n_estimators = search.best_params_['n_estimators'],\n                        max_depth = search.best_params_['max_depth'])\n\nregressor.fit(X_train, Y_train)","metadata":{"execution":{"iopub.status.busy":"2022-11-16T10:21:51.076591Z","iopub.execute_input":"2022-11-16T10:21:51.077461Z","iopub.status.idle":"2022-11-16T10:22:37.992606Z","shell.execute_reply.started":"2022-11-16T10:21:51.077425Z","shell.execute_reply":"2022-11-16T10:22:37.991656Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions = regressor.predict(X_test)","metadata":{"execution":{"iopub.status.busy":"2022-11-16T10:22:46.942481Z","iopub.execute_input":"2022-11-16T10:22:46.943191Z","iopub.status.idle":"2022-11-16T10:23:26.704102Z","shell.execute_reply.started":"2022-11-16T10:22:46.943156Z","shell.execute_reply":"2022-11-16T10:23:26.702970Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import explained_variance_score\n# variance score: 1 means perfect prediction\npred = predictions.reshape(Y_test.shape)\nprint('Variance score: {}'.format(explained_variance_score(Y_test, pred)))\n  \n# plot for residual error\n \nplt.figure(figsize=(25, 25))\n## setting plot style\nplt.style.use('fivethirtyeight')\n  \n## plotting residual errors in test data\nplt.scatter(pred, pred - Y_test,\n            color = \"blue\", s = 10, label = 'Test data')\n  \n## plotting line for zero residual error\nplt.hlines(y = 0, xmin = 0, xmax = 50, linewidth = 2)\n  \n## plotting legend\nplt.legend(loc = 'upper right')\n  \n## plot title\nplt.title(\"Residual errors\")\n  \n## method call for showing the plot\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2022-11-16T10:23:35.550717Z","iopub.execute_input":"2022-11-16T10:23:35.551709Z","iopub.status.idle":"2022-11-16T10:23:38.783222Z","shell.execute_reply.started":"2022-11-16T10:23:35.551655Z","shell.execute_reply":"2022-11-16T10:23:38.780759Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.metrics import r2_score\nMSE = np.sqrt(mean_squared_error(Y_test, predictions))\nprint(\"MSE Score is %.5f\" % MSE)\n\nMAE = mean_absolute_error(Y_test, predictions)\nprint(\"MAE Score is %.5f\" % MAE)\n\nR2 = r2_score(Y_test, predictions)\nprint(\"R2 Score is %.5f\" % R2)","metadata":{"execution":{"iopub.status.busy":"2022-11-16T10:23:46.947780Z","iopub.execute_input":"2022-11-16T10:23:46.948978Z","iopub.status.idle":"2022-11-16T10:23:47.145072Z","shell.execute_reply.started":"2022-11-16T10:23:46.948933Z","shell.execute_reply":"2022-11-16T10:23:47.143336Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#regressor.get_booster().feature_names = features\n\nfrom xgboost import plot_importance\n#plt.style.use('fivethirtyeight')\n#plt.rcParams.update({'font.size' : 16})\n\n\nfig, ax = plt.subplots(figsize=(48,50))\nplot_importance(regressor, ax=ax)\nplt.show()\n\n","metadata":{"execution":{"iopub.status.busy":"2022-11-16T10:48:40.218195Z","iopub.execute_input":"2022-11-16T10:48:40.218592Z","iopub.status.idle":"2022-11-16T10:48:42.492289Z","shell.execute_reply.started":"2022-11-16T10:48:40.218558Z","shell.execute_reply":"2022-11-16T10:48:42.491462Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_train.plot.box(title='winBid')","metadata":{"execution":{"iopub.status.busy":"2022-11-16T11:32:48.692625Z","iopub.execute_input":"2022-11-16T11:32:48.693119Z","iopub.status.idle":"2022-11-16T11:32:51.631377Z","shell.execute_reply.started":"2022-11-16T11:32:48.693073Z","shell.execute_reply":"2022-11-16T11:32:51.630320Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Finally,\nIt can be said that the Residual Error distribution error indicates that the data needs to be reworked on that as the model result is rather alright on the mean. However, the 'winBid' has significant outliers. As it is the target variable, removing the outlier samples don't really make sense.\nThus, more feature can be calculated from existing once to cooperate with the 'winBid' outlier values.","metadata":{}}]}