{"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)\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":{"execution":{"iopub.status.busy":"2022-10-06T17:51:46.490482Z","iopub.execute_input":"2022-10-06T17:51:46.491066Z","iopub.status.idle":"2022-10-06T17:51:46.535940Z","shell.execute_reply.started":"2022-10-06T17:51:46.490947Z","shell.execute_reply":"2022-10-06T17:51:46.533879Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%matplotlib inline\nfrom random import randint\nimport numpy as np\nimport pandas as pd\nfrom scipy.stats import skew\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.linear_model import LinearRegression, Ridge, Lasso\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.model_selection import StratifiedKFold,GridSearchCV,RandomizedSearchCV, train_test_split, RepeatedStratifiedKFold#For splitting\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler\nfrom sklearn.model_selection import train_test_split\n\nimport gc\nfrom tqdm import tqdm\nfrom sklearn.metrics import fbeta_score, make_scorer\nfrom scipy import stats\nfrom random import randint\nfrom sklearn.metrics import accuracy_score, f1_score, roc_auc_score, plot_roc_curve, plot_confusion_matrix, r2_score, mean_absolute_error,mean_squared_error, recall_score, precision_score\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler\nfrom sklearn.preprocessing import OneHotEncoder, LabelEncoder, OrdinalEncoder\nfrom sklearn.model_selection import train_test_split\n\n\nfrom sklearn.metrics import fbeta_score, make_scorer\nfrom sklearn.svm import SVR, LinearSVR\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom sklearn.tree import DecisionTreeRegressor\nfrom lightgbm import LGBMRegressor\nfrom sklearn.ensemble import GradientBoostingRegressor\nfrom catboost import CatBoostRegressor, Pool \nfrom sklearn.ensemble import RandomForestRegressor\nfrom xgboost import XGBRegressor\nfrom sklearn.ensemble import AdaBoostRegressor\n\nfrom sklearn.metrics import confusion_matrix, classification_report, ConfusionMatrixDisplay\n\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")","metadata":{"execution":{"iopub.status.busy":"2022-10-06T17:52:01.828622Z","iopub.execute_input":"2022-10-06T17:52:01.829711Z","iopub.status.idle":"2022-10-06T17:52:04.301300Z","shell.execute_reply.started":"2022-10-06T17:52:01.829644Z","shell.execute_reply":"2022-10-06T17:52:04.299990Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dtype= {'bidFloorPrice'  :     'float16' ,\n 'eventTimestamp'  :   'uint64'  , \n 'has_won' :    'uint8' ,\n   'sentPrice'  :    'float16' ,\n   'winBid' :     'float16' ,\n   'unitDisplayType' :  'category',\n   'brandName':    'category',\n   'bundleId'  :    'category',\n   'appVersion' :   'category',\n   'correctModelName' :     'category',\n  'countryCode' :   'category',\n  'deviceId' :   'category',\n  'osAndVersion'  :   'category',\n  'connectionType' :    'category',\n  'c1'    :    'category',\n  'c2'  :    'category',\n  'c3' :    'category',\n  'c4'   :    'category',\n  'size'  :   'category',\n  'mediationProviderVersion':  'category'}\n\ndtype1= {'bidFloorPrice'  :     'float16' ,\n 'eventTimestamp'  :   'uint64'   ,\n   'sentPrice'  :    'float16' ,\n   'unitDisplayType' :  'category',\n   'brandName':    'category',\n   'bundleId'  :    'category',\n   'appVersion' :   'category',\n   'correctModelName' :     'category',\n  'countryCode' :   'category',\n  'deviceId' :   'category',\n  'osAndVersion'  :   'category',\n  'connectionType' :    'category',\n  'c1'    :    'category',\n  'c2'  :    'category',\n  'c3' :    'category',\n  'c4'   :    'category',\n  'size'  :   'category',\n  'mediationProviderVersion':  'category'}","metadata":{"execution":{"iopub.status.busy":"2022-10-06T17:52:04.303869Z","iopub.execute_input":"2022-10-06T17:52:04.304298Z","iopub.status.idle":"2022-10-06T17:52:04.314102Z","shell.execute_reply.started":"2022-10-06T17:52:04.304230Z","shell.execute_reply":"2022-10-06T17:52:04.312786Z"},"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', engine ='c',dtype=dtype)\ntest = pd.read_csv('/kaggle/input/digital-turbine-auction-bid-price-prediction/test_data.csv', engine ='c',dtype=dtype1)","metadata":{"execution":{"iopub.status.busy":"2022-10-06T17:52:04.315629Z","iopub.execute_input":"2022-10-06T17:52:04.317019Z","iopub.status.idle":"2022-10-06T17:52:51.507118Z","shell.execute_reply.started":"2022-10-06T17:52:04.316978Z","shell.execute_reply":"2022-10-06T17:52:51.505746Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.info()","metadata":{"execution":{"iopub.status.busy":"2022-10-06T17:52:51.510713Z","iopub.execute_input":"2022-10-06T17:52:51.511299Z","iopub.status.idle":"2022-10-06T17:52:51.568089Z","shell.execute_reply.started":"2022-10-06T17:52:51.511225Z","shell.execute_reply":"2022-10-06T17:52:51.566380Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def concatenated_df(train_data, test_data):\n    return pd.concat([train_data, test_data], sort=True).reset_index(drop=True)\n\ndef divide_df(all_data):\n    return all_data.loc[:7321632], all_data.loc[7321633:].drop(['winBid', 'has_won'], axis=1)","metadata":{"execution":{"iopub.status.busy":"2022-10-06T17:52:51.569746Z","iopub.execute_input":"2022-10-06T17:52:51.570155Z","iopub.status.idle":"2022-10-06T17:52:51.579243Z","shell.execute_reply.started":"2022-10-06T17:52:51.570118Z","shell.execute_reply":"2022-10-06T17:52:51.577936Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"emb_imp = SimpleImputer(strategy='constant', fill_value= 'Unknown')\nemb = ['connectionType']\nemb_imp.fit(train[emb])\ntrain[emb] = emb_imp.fit_transform(train[emb])\ntest[emb] = emb_imp.transform(test[emb])\n\n\nemb_imp = SimpleImputer(strategy='constant', fill_value= 'Unknown')\nemb = ['countryCode']\nemb_imp.fit(train[emb])\ntrain[emb] = emb_imp.fit_transform(train[emb])\ntest[emb] = emb_imp.transform(test[emb])\n\n#train2 = train.fillna('None')","metadata":{"execution":{"iopub.status.busy":"2022-10-06T17:52:51.580818Z","iopub.execute_input":"2022-10-06T17:52:51.582051Z","iopub.status.idle":"2022-10-06T17:52:55.128147Z","shell.execute_reply.started":"2022-10-06T17:52:51.582007Z","shell.execute_reply":"2022-10-06T17:52:55.123181Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train[['countryCode', 'connectionType']]= train[[ 'countryCode', 'connectionType']].astype('category')\ntest[[ 'countryCode', 'connectionType']]= test[[ 'countryCode', 'connectionType']].astype('category')\n","metadata":{"execution":{"iopub.status.busy":"2022-10-06T17:52:55.133288Z","iopub.execute_input":"2022-10-06T17:52:55.134009Z","iopub.status.idle":"2022-10-06T17:52:59.601876Z","shell.execute_reply.started":"2022-10-06T17:52:55.133918Z","shell.execute_reply":"2022-10-06T17:52:59.597357Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.info()","metadata":{"execution":{"iopub.status.busy":"2022-10-06T17:52:59.608337Z","iopub.execute_input":"2022-10-06T17:52:59.610002Z","iopub.status.idle":"2022-10-06T17:52:59.678284Z","shell.execute_reply.started":"2022-10-06T17:52:59.609958Z","shell.execute_reply":"2022-10-06T17:52:59.671698Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"categorical_features_indices =np.where(train.dtypes == 'category')[0]\ncateg_cols = train.columns[categorical_features_indices]\ncateg_cols","metadata":{"execution":{"iopub.status.busy":"2022-10-06T17:52:59.681973Z","iopub.execute_input":"2022-10-06T17:52:59.682853Z","iopub.status.idle":"2022-10-06T17:52:59.731034Z","shell.execute_reply.started":"2022-10-06T17:52:59.682725Z","shell.execute_reply":"2022-10-06T17:52:59.723472Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len(train)","metadata":{"execution":{"iopub.status.busy":"2022-10-06T17:52:59.745138Z","iopub.execute_input":"2022-10-06T17:52:59.749372Z","iopub.status.idle":"2022-10-06T17:52:59.773798Z","shell.execute_reply.started":"2022-10-06T17:52:59.749076Z","shell.execute_reply":"2022-10-06T17:52:59.772051Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_all = concatenated_df(train, test)\n\n# Apply one-hot encoder to each column with categorical data\n#OH_encoder = OneHotEncoder(handle_unknown='ignore', sparse=False)\nL_encoder = OrdinalEncoder()\n#df_all[categ_cols]= df_all[categ_cols].categorize()\n#OH_cols = pd.DataFrame(OH_encoder.fit_transform(df_all[OH_col]))\nL_cols= pd.DataFrame(L_encoder.fit_transform(df_all[categ_cols]))\nL_cols.columns = categ_cols\n# Remove categorical columns (will replace with one-hot encoding)\nnum_cols = df_all.drop(categ_cols, axis=1)\n\n\n# Add one-hot encoded columns to numerical features\ndf_all = pd.concat([num_cols, L_cols], axis=1)\n\ndf_all['Timestamp'] = pd.to_datetime(df_all['eventTimestamp'], unit='ms')\n\ndf_all['Month'] = pd.to_datetime(df_all['Timestamp']).dt.month\n\ndf_all['Day'] = pd.to_datetime(df_all['Timestamp']).dt.day\n\ndf_all['Time'] = pd.to_datetime(df_all['Timestamp']).dt.time\n\ndf_all['Hour'] = pd.to_datetime(df_all['Timestamp']).dt.hour\n\ndf_all['Date'] = pd.to_datetime(df_all['Timestamp']).dt.dayofyear\n\ndf_all['Seconds'] = pd.to_timedelta(df_all['Timestamp'].dt.strftime('%H:%M:%S')).dt.total_seconds().astype(int)\n\ndf_all['Month']= df_all['Month'].astype('category')\ndf_all['Day']= df_all['Day'].astype('category')\ndf_all['Hour']= df_all['Hour'].astype('category')\ndf_all['Date']= df_all['Date'].astype('category')\ndf_all[categ_cols]= df_all[categ_cols].astype(int)\ndf_all[categ_cols]= df_all[categ_cols].astype('category')\n\ndf_all= df_all.drop(['Time', 'Timestamp'],axis=1).reset_index(drop=True)\ncategorical_features_indices =np.where(df_all.dtypes == 'category')[0]\ncateg_cols = df_all.columns[categorical_features_indices]\n\ndef agg_functions(df1):\n    features= ['c1','c3','deviceId','unitDisplayType','bundleId']\n    for x in tqdm(features):\n        t=df1.groupby(x)['winBid'].agg(['std','max','min','mean','median'])\n        t.columns=[x+c+'_bidWin' for c in t.columns]\n        t=t.astype({c:np.float32 for c in t.columns})\n        t.reset_index(inplace=True)\n#         display(t)\n        # display(t.T.to_dict('list'))\n        df1=df1.merge(t,on=x,how='left')\n        gc.collect()\n    return df1\n# AGGREGATE SPECIFIC FEATURES WITH WINBID\ndf_all=agg_functions(df_all)\n\n#train1, test1 = divide_df(df_all)\n\ndf_all","metadata":{"execution":{"iopub.status.busy":"2022-10-06T17:52:59.775787Z","iopub.execute_input":"2022-10-06T17:52:59.776184Z","iopub.status.idle":"2022-10-06T17:56:30.507573Z","shell.execute_reply.started":"2022-10-06T17:52:59.776151Z","shell.execute_reply":"2022-10-06T17:56:30.505956Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"categ_cols","metadata":{"execution":{"iopub.status.busy":"2022-10-06T17:56:30.509443Z","iopub.execute_input":"2022-10-06T17:56:30.509897Z","iopub.status.idle":"2022-10-06T17:56:30.519380Z","shell.execute_reply.started":"2022-10-06T17:56:30.509856Z","shell.execute_reply":"2022-10-06T17:56:30.517833Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_all[-41587:]","metadata":{"execution":{"iopub.status.busy":"2022-10-06T17:56:30.521176Z","iopub.execute_input":"2022-10-06T17:56:30.521747Z","iopub.status.idle":"2022-10-06T17:56:30.574018Z","shell.execute_reply.started":"2022-10-06T17:56:30.521652Z","shell.execute_reply":"2022-10-06T17:56:30.572631Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"a = pd.DataFrame(df_all.isnull().sum())\na.loc[a[0]>0]","metadata":{"execution":{"iopub.status.busy":"2022-10-06T17:56:30.575746Z","iopub.execute_input":"2022-10-06T17:56:30.576130Z","iopub.status.idle":"2022-10-06T17:56:31.233331Z","shell.execute_reply.started":"2022-10-06T17:56:30.576096Z","shell.execute_reply":"2022-10-06T17:56:31.231403Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_all['deviceIdmedian_bidWin']= df_all['deviceIdmedian_bidWin'].fillna( df_all['deviceIdmedian_bidWin'].mean())\ndf_all['deviceIdmean_bidWin']= df_all['deviceIdmean_bidWin'].fillna( df_all['deviceIdmean_bidWin'].mean())\ndf_all['deviceIdmin_bidWin']= df_all['deviceIdmin_bidWin'].fillna( df_all['deviceIdmin_bidWin'].mean() )\ndf_all['deviceIdmax_bidWin']=df_all['deviceIdmax_bidWin'].fillna( df_all['deviceIdmax_bidWin'].mean())\ndf_all['deviceIdstd_bidWin']=df_all['deviceIdstd_bidWin'].fillna( df_all['deviceIdstd_bidWin'].mean())","metadata":{"execution":{"iopub.status.busy":"2022-10-06T17:58:49.505543Z","iopub.execute_input":"2022-10-06T17:58:49.506435Z","iopub.status.idle":"2022-10-06T17:58:49.828456Z","shell.execute_reply.started":"2022-10-06T17:58:49.506375Z","shell.execute_reply":"2022-10-06T17:58:49.826848Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_all[categ_cols]= df_all[categ_cols].astype(int)","metadata":{"execution":{"iopub.status.busy":"2022-10-04T23:03:01.120795Z","iopub.execute_input":"2022-10-04T23:03:01.121478Z","iopub.status.idle":"2022-10-04T23:03:02.286423Z","shell.execute_reply.started":"2022-10-04T23:03:01.121440Z","shell.execute_reply":"2022-10-04T23:03:02.285412Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"a = pd.DataFrame(df_all.isnull().sum())\na.loc[a[0]>0]","metadata":{"execution":{"iopub.status.busy":"2022-10-04T23:03:05.057237Z","iopub.execute_input":"2022-10-04T23:03:05.057734Z","iopub.status.idle":"2022-10-04T23:03:05.594103Z","shell.execute_reply.started":"2022-10-04T23:03:05.057697Z","shell.execute_reply":"2022-10-04T23:03:05.592509Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train1, test1 = divide_df(df_all)","metadata":{"execution":{"iopub.status.busy":"2022-10-04T23:03:26.448332Z","iopub.execute_input":"2022-10-04T23:03:26.448844Z","iopub.status.idle":"2022-10-04T23:03:26.475348Z","shell.execute_reply.started":"2022-10-04T23:03:26.448811Z","shell.execute_reply":"2022-10-04T23:03:26.474245Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train1.to_csv('train1.csv', index=False)\ntest1.to_csv('test1.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2022-10-04T23:03:56.007788Z","iopub.execute_input":"2022-10-04T23:03:56.008147Z","iopub.status.idle":"2022-10-04T23:08:16.832443Z","shell.execute_reply.started":"2022-10-04T23:03:56.008117Z","shell.execute_reply":"2022-10-04T23:08:16.831349Z"},"trusted":true},"execution_count":null,"outputs":[]}]}