{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":10038,"databundleVersionId":180088,"sourceType":"competition"}],"dockerImageVersionId":30587,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import numpy as np \nimport pandas as pd \nfrom datetime import datetime\nimport os\nfrom sklearn.preprocessing import LabelEncoder\nfrom pprint import pprint\nimport matplotlib.pyplot as plt\nimport seaborn as sns","metadata":{"execution":{"iopub.status.busy":"2023-12-05T01:21:00.885010Z","iopub.execute_input":"2023-12-05T01:21:00.885483Z","iopub.status.idle":"2023-12-05T01:21:02.125573Z","shell.execute_reply.started":"2023-12-05T01:21:00.885450Z","shell.execute_reply":"2023-12-05T01:21:02.124366Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import json\nimport plotly.graph_objs as go\nfrom plotly import tools\nimport plotly.offline as py\npy.init_notebook_mode(connected=True)\nfrom sklearn import model_selection, preprocessing, metrics\nimport lightgbm as lgb","metadata":{"execution":{"iopub.status.busy":"2023-12-05T02:16:18.878736Z","iopub.execute_input":"2023-12-05T02:16:18.879487Z","iopub.status.idle":"2023-12-05T02:16:20.136114Z","shell.execute_reply.started":"2023-12-05T02:16:18.879453Z","shell.execute_reply":"2023-12-05T02:16:20.135177Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test=pd.read_csv('/kaggle/input/ga-customer-revenue-prediction/test.csv')\ndf_train=pd.read_csv('/kaggle/input/ga-customer-revenue-prediction/train.csv')","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-12-05T00:18:47.180544Z","iopub.execute_input":"2023-12-05T00:18:47.182020Z","iopub.status.idle":"2023-12-05T00:19:33.049922Z","shell.execute_reply.started":"2023-12-05T00:18:47.181974Z","shell.execute_reply":"2023-12-05T00:19:33.048597Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def load_df(csv_path='/kaggle/input/ga-customer-revenue-prediction/train.csv', nrows=None):\n    JSON_COLUMNS = ['device', 'geoNetwork', 'totals', 'trafficSource']\n    \n    df = pd.read_csv(csv_path, \n                     converters={column: json.loads for column in JSON_COLUMNS}, \n                     dtype={'fullVisitorId': 'str'}, # Important!!\n                     nrows=nrows)\n    \n    for column in JSON_COLUMNS:\n        column_as_df = pd.json_normalize(df[column])\n        column_as_df.columns = [f\"{column}.{subcolumn}\" for subcolumn in column_as_df.columns]\n        df = df.drop(column, axis=1).merge(column_as_df, right_index=True, left_index=True)\n    print(f\"Loaded {os.path.basename(csv_path)}. Shape: {df.shape}\")\n    return df","metadata":{"execution":{"iopub.status.busy":"2023-12-05T01:21:06.811202Z","iopub.execute_input":"2023-12-05T01:21:06.811621Z","iopub.status.idle":"2023-12-05T01:21:06.820310Z","shell.execute_reply.started":"2023-12-05T01:21:06.811591Z","shell.execute_reply":"2023-12-05T01:21:06.818542Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\ntrain_df=load_df()\ntest_df=load_df('/kaggle/input/ga-customer-revenue-prediction/test.csv')","metadata":{"execution":{"iopub.status.busy":"2023-12-05T01:21:09.935018Z","iopub.execute_input":"2023-12-05T01:21:09.935434Z","iopub.status.idle":"2023-12-05T01:24:35.099385Z","shell.execute_reply.started":"2023-12-05T01:21:09.935404Z","shell.execute_reply":"2023-12-05T01:24:35.098320Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.head()","metadata":{"execution":{"iopub.status.busy":"2023-12-05T00:46:39.425725Z","iopub.execute_input":"2023-12-05T00:46:39.426188Z","iopub.status.idle":"2023-12-05T00:46:39.462652Z","shell.execute_reply.started":"2023-12-05T00:46:39.426146Z","shell.execute_reply":"2023-12-05T00:46:39.461304Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.info()","metadata":{"execution":{"iopub.status.busy":"2023-12-05T00:26:23.217107Z","iopub.execute_input":"2023-12-05T00:26:23.217566Z","iopub.status.idle":"2023-12-05T00:26:28.515054Z","shell.execute_reply.started":"2023-12-05T00:26:23.217528Z","shell.execute_reply":"2023-12-05T00:26:28.513766Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df['totals.transactionRevenue']=train_df['totals.transactionRevenue'].astype('float')\ngdf=train_df.groupby(\"fullVisitorId\")['totals.transactionRevenue'].sum().reset_index()","metadata":{"execution":{"iopub.status.busy":"2023-12-05T01:25:29.741393Z","iopub.execute_input":"2023-12-05T01:25:29.741807Z","iopub.status.idle":"2023-12-05T01:25:32.129806Z","shell.execute_reply.started":"2023-12-05T01:25:29.741776Z","shell.execute_reply":"2023-12-05T01:25:32.128500Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(8,6))\nplt.scatter(range(gdf.shape[0]),np.sort(np.log1p(gdf['totals.transactionRevenue'].values)))\nplt.xlabel('index',fontsize=12)\nplt.ylabel('TransactionRevenue',fontsize=12)","metadata":{"execution":{"iopub.status.busy":"2023-12-05T01:25:38.506777Z","iopub.execute_input":"2023-12-05T01:25:38.507216Z","iopub.status.idle":"2023-12-05T01:25:41.963183Z","shell.execute_reply.started":"2023-12-05T01:25:38.507181Z","shell.execute_reply":"2023-12-05T01:25:41.962024Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"nzi=pd.notnull(train_df['totals.transactionRevenue']).sum()\nnzr=(gdf['totals.transactionRevenue'] >0).sum()","metadata":{"execution":{"iopub.status.busy":"2023-12-05T00:37:05.155619Z","iopub.execute_input":"2023-12-05T00:37:05.156151Z","iopub.status.idle":"2023-12-05T00:37:05.166684Z","shell.execute_reply.started":"2023-12-05T00:37:05.156109Z","shell.execute_reply":"2023-12-05T00:37:05.165395Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Number of instances in train set with non-zero revenue : \", nzi, \" and ratio is : \", nzi / train_df.shape[0])\nprint(\"Number of unique customers with non-zero revenue : \", nzr, \"and the ratio is : \", nzr / gdf.shape[0])","metadata":{"execution":{"iopub.status.busy":"2023-12-05T00:38:25.870505Z","iopub.execute_input":"2023-12-05T00:38:25.871943Z","iopub.status.idle":"2023-12-05T00:38:25.878600Z","shell.execute_reply.started":"2023-12-05T00:38:25.871894Z","shell.execute_reply":"2023-12-05T00:38:25.877325Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Number of unique visitors in train set : \",train_df.fullVisitorId.nunique(), \" out of rows : \",train_df.shape[0])\nprint(\"Number of unique visitors in test set : \",test_df.fullVisitorId.nunique(), \" out of rows : \",test_df.shape[0])\nprint(\"Number of common visitors in train and test set : \",len(set(train_df.fullVisitorId.unique()).intersection(set(test_df.fullVisitorId.unique())) ))","metadata":{"execution":{"iopub.status.busy":"2023-12-05T00:47:15.361043Z","iopub.execute_input":"2023-12-05T00:47:15.361482Z","iopub.status.idle":"2023-12-05T00:47:17.068098Z","shell.execute_reply.started":"2023-12-05T00:47:15.361449Z","shell.execute_reply":"2023-12-05T00:47:17.066673Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"const_cols=[c for c in train_df.columns if train_df[c].nunique(dropna=False)==1]\nconst_cols","metadata":{"execution":{"iopub.status.busy":"2023-12-05T01:25:52.524020Z","iopub.execute_input":"2023-12-05T01:25:52.524469Z","iopub.status.idle":"2023-12-05T01:26:00.687340Z","shell.execute_reply.started":"2023-12-05T01:25:52.524436Z","shell.execute_reply":"2023-12-05T01:26:00.686183Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def horizontal_bar_chart(cnt_srs, color):\n    trace = go.Bar(\n        y=cnt_srs.index[::-1],\n        x=cnt_srs.values[::-1],\n        showlegend=False,\n        orientation = 'h',\n        marker=dict(\n            color=color,\n        ),\n    )\n    return trace\n\n","metadata":{"execution":{"iopub.status.busy":"2023-12-05T01:26:12.747713Z","iopub.execute_input":"2023-12-05T01:26:12.748533Z","iopub.status.idle":"2023-12-05T01:26:12.754855Z","shell.execute_reply.started":"2023-12-05T01:26:12.748491Z","shell.execute_reply":"2023-12-05T01:26:12.753656Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df['totals.transactionRevenue']=train_df['totals.transactionRevenue'].astype('float')\ncnt_srs=train_df.groupby('device.browser')['totals.transactionRevenue'].agg(['size','count','mean'])\ncnt_srs.columns = [\"count\", \"count of non-zero revenue\", \"mean\"]\ncnt_srs=cnt_srs.sort_values(by='count',ascending=False)\ntrace1=horizontal_bar_chart(cnt_srs['count'].head(10),'rgba(50, 171, 96, 0.6)')\ntrace2=horizontal_bar_chart(cnt_srs['count of non-zero revenue'].head(10),'rgba(50, 171, 96, 0.6)')\ntrace3=horizontal_bar_chart(cnt_srs['mean'].head(10),'rgba(50, 171, 96, 0.6)')","metadata":{"execution":{"iopub.status.busy":"2023-12-05T01:27:41.814922Z","iopub.execute_input":"2023-12-05T01:27:41.815340Z","iopub.status.idle":"2023-12-05T01:27:42.036093Z","shell.execute_reply.started":"2023-12-05T01:27:41.815308Z","shell.execute_reply":"2023-12-05T01:27:42.034342Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Device Category\ncnt_srs = train_df.groupby('device.deviceCategory')['totals.transactionRevenue'].agg(['size', 'count', 'mean'])\ncnt_srs.columns = [\"count\", \"count of non-zero revenue\", \"mean\"]\ncnt_srs = cnt_srs.sort_values(by=\"count\", ascending=False)\ntrace4 = horizontal_bar_chart(cnt_srs[\"count\"].head(10), 'rgba(71, 58, 131, 0.8)')\ntrace5 = horizontal_bar_chart(cnt_srs[\"count of non-zero revenue\"].head(10), 'rgba(71, 58, 131, 0.8)')\ntrace6 = horizontal_bar_chart(cnt_srs[\"mean\"].head(10), 'rgba(71, 58, 131, 0.8)')","metadata":{"execution":{"iopub.status.busy":"2023-12-05T01:26:19.492773Z","iopub.execute_input":"2023-12-05T01:26:19.493219Z","iopub.status.idle":"2023-12-05T01:26:19.703269Z","shell.execute_reply.started":"2023-12-05T01:26:19.493185Z","shell.execute_reply":"2023-12-05T01:26:19.702155Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Operating system\ncnt_srs = train_df.groupby('device.operatingSystem')['totals.transactionRevenue'].agg(['size', 'count', 'mean'])\ncnt_srs.columns = [\"count\", \"count of non-zero revenue\", \"mean\"]\ncnt_srs = cnt_srs.sort_values(by=\"count\", ascending=False)\ntrace7 = horizontal_bar_chart(cnt_srs[\"count\"].head(10), 'rgba(246, 78, 139, 0.6)')\ntrace8 = horizontal_bar_chart(cnt_srs[\"count of non-zero revenue\"].head(10),'rgba(246, 78, 139, 0.6)')\ntrace9 = horizontal_bar_chart(cnt_srs[\"mean\"].head(10),'rgba(246, 78, 139, 0.6)')\n","metadata":{"execution":{"iopub.status.busy":"2023-12-05T01:26:50.295514Z","iopub.execute_input":"2023-12-05T01:26:50.295976Z","iopub.status.idle":"2023-12-05T01:26:50.508856Z","shell.execute_reply.started":"2023-12-05T01:26:50.295940Z","shell.execute_reply":"2023-12-05T01:26:50.507798Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Creating two subplots\nfig = tools.make_subplots(rows=3, cols=3, vertical_spacing=0.04, \n                          subplot_titles=[\"Device Browser - Count\", \"Device Browser - Non-zero Revenue Count\", \"Device Browser - Mean Revenue\",\n                                          \"Device Category - Count\",  \"Device Category - Non-zero Revenue Count\", \"Device Category - Mean Revenue\", \n                                          \"Device OS - Count\", \"Device OS - Non-zero Revenue Count\", \"Device OS - Mean Revenue\"])\n\nfig.append_trace(trace1, 1, 1)\nfig.append_trace(trace2, 1, 2)\nfig.append_trace(trace3, 1, 3)\nfig.append_trace(trace4, 2, 1)\nfig.append_trace(trace5, 2, 2)\nfig.append_trace(trace6, 2, 3)\nfig.append_trace(trace7, 3, 1)\nfig.append_trace(trace8, 3, 2)\nfig.append_trace(trace9, 3, 3)\n\nfig['layout'].update(height=1200, width=1200, paper_bgcolor='rgb(233,233,233)', title=\"Device Plots\")\npy.iplot(fig, filename='device-plots')","metadata":{"execution":{"iopub.status.busy":"2023-12-05T01:28:45.014933Z","iopub.execute_input":"2023-12-05T01:28:45.015377Z","iopub.status.idle":"2023-12-05T01:28:46.241588Z","shell.execute_reply.started":"2023-12-05T01:28:45.015342Z","shell.execute_reply":"2023-12-05T01:28:46.240502Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import datetime\n\ndef scatter_plot(cnt_srs, color):\n    trace = go.Scatter(\n        x=cnt_srs.index[::-1],\n        y=cnt_srs.values[::-1],\n        showlegend=False,\n        marker=dict(\n            color=color,\n        ),\n    )\n    return trace\n","metadata":{"execution":{"iopub.status.busy":"2023-12-05T01:29:31.040788Z","iopub.execute_input":"2023-12-05T01:29:31.041296Z","iopub.status.idle":"2023-12-05T01:29:31.048403Z","shell.execute_reply.started":"2023-12-05T01:29:31.041249Z","shell.execute_reply":"2023-12-05T01:29:31.046917Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df['date']=train_df['date'].apply(lambda x : datetime.date(int(str(x)[:4]),int(str(x)[4:6]),int(str(x)[6:])))","metadata":{"execution":{"iopub.status.busy":"2023-12-05T01:33:05.392449Z","iopub.execute_input":"2023-12-05T01:33:05.392925Z","iopub.status.idle":"2023-12-05T01:33:07.310906Z","shell.execute_reply.started":"2023-12-05T01:33:05.392891Z","shell.execute_reply":"2023-12-05T01:33:07.309676Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cnt_srs=train_df.groupby('date')['totals.transactionRevenue'].agg(['size','count'])\ncnt_srs.columns=[\"count\", \"count of non-zero revenue\"]\ncnt_srs=cnt_srs.sort_index()\ntrace1 = scatter_plot(cnt_srs[\"count\"], 'red')\ntrace2 = scatter_plot(cnt_srs[\"count of non-zero revenue\"], 'blue')\nfig = tools.make_subplots(rows=2, cols=1, vertical_spacing=0.08,\n                          subplot_titles=[\"Date - Count\", \"Date - Non-zero Revenue count\"])\nfig.append_trace(trace1, 1, 1)\nfig.append_trace(trace2, 2, 1)\nfig['layout'].update(height=800, width=800, paper_bgcolor='rgb(233,233,233)', title=\"Date Plots\")\npy.iplot(fig, filename='date-plots')","metadata":{"execution":{"iopub.status.busy":"2023-12-05T01:36:29.043860Z","iopub.execute_input":"2023-12-05T01:36:29.044391Z","iopub.status.idle":"2023-12-05T01:36:29.396848Z","shell.execute_reply.started":"2023-12-05T01:36:29.044351Z","shell.execute_reply":"2023-12-05T01:36:29.395690Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df['date'] = test_df['date'].apply(lambda x: datetime.date(int(str(x)[:4]), int(str(x)[4:6]), int(str(x)[6:])))\ncnt_srs = test_df.groupby('date')['fullVisitorId'].size()\n\n\ntrace = scatter_plot(cnt_srs, 'red')\n\nlayout = go.Layout(\n    height=400,\n    width=800,\n    paper_bgcolor='rgb(233,233,233)',\n    title='Dates in Test set'\n)\n\ndata = [trace]\nfig = go.Figure(data=data, layout=layout)\npy.iplot(fig, filename=\"ActivationDate\")","metadata":{"execution":{"iopub.status.busy":"2023-12-05T01:38:54.316029Z","iopub.execute_input":"2023-12-05T01:38:54.316568Z","iopub.status.idle":"2023-12-05T01:38:56.226118Z","shell.execute_reply.started":"2023-12-05T01:38:54.316531Z","shell.execute_reply":"2023-12-05T01:38:56.224962Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Continent\ncnt_srs = train_df.groupby('geoNetwork.continent')['totals.transactionRevenue'].agg(['size', 'count', 'mean'])\ncnt_srs.columns = [\"count\", \"count of non-zero revenue\", \"mean\"]\ncnt_srs = cnt_srs.sort_values(by=\"count\", ascending=False)\ntrace1 = horizontal_bar_chart(cnt_srs[\"count\"].head(10), 'rgba(58, 71, 80, 0.6)')\ntrace2 = horizontal_bar_chart(cnt_srs[\"count of non-zero revenue\"].head(10), 'rgba(58, 71, 80, 0.6)')\ntrace3 = horizontal_bar_chart(cnt_srs[\"mean\"].head(10), 'rgba(58, 71, 80, 0.6)')\n\n\n#Sub-continent\ncnt_rs=train_df.groupby('geoNetwork.subContinent')['totals.transactionRevenue'].agg(['count','size','mean'])\ncnt_rs.columns=[\"count\", \"count of non-zero revenue\", \"mean\"]\ncnt_rs=cnt_rs.sort_values(by=\"count\",ascending=False)\ntrace4 = horizontal_bar_chart(cnt_srs[\"count\"], 'orange')\ntrace5 = horizontal_bar_chart(cnt_srs[\"count of non-zero revenue\"], 'orange')\ntrace6 = horizontal_bar_chart(cnt_srs[\"mean\"], 'orange')\n\n# Network domain\ncnt_rs=train_df.groupby('geoNetwork.networkDomain')['totals.transactionRevenue'].agg(['count','size','mean'])\ncnt_rs.columns=[\"count\", \"count of non-zero revenue\", \"mean\"]\ncnt_rs=cnt_rs.sort_values(by=\"count\",ascending=False)\ntrace7 = horizontal_bar_chart(cnt_srs[\"count\"].head(10), 'blue')\ntrace8 = horizontal_bar_chart(cnt_srs[\"count of non-zero revenue\"].head(10), 'blue')\ntrace9 = horizontal_bar_chart(cnt_srs[\"mean\"].head(10), 'blue')\n #Creating two subplots\nfig = tools.make_subplots(rows=3, cols=3, vertical_spacing=0.08, horizontal_spacing=0.15, \n                          subplot_titles=[\"Continent - Count\", \"Continent - Non-zero Revenue Count\", \"Continent - Mean Revenue\",\n                                          \"Sub Continent - Count\",  \"Sub Continent - Non-zero Revenue Count\", \"Sub Continent - Mean Revenue\",\n                                          \"Network Domain - Count\", \"Network Domain - Non-zero Revenue Count\", \"Network Domain - Mean Revenue\"])\n\nfig.append_trace(trace1, 1, 1)\nfig.append_trace(trace2, 1, 2)\nfig.append_trace(trace3, 1, 3)\nfig.append_trace(trace4, 2, 1)\nfig.append_trace(trace5, 2, 2)\nfig.append_trace(trace6, 2, 3)\nfig.append_trace(trace7, 3, 1)\nfig.append_trace(trace8, 3, 2)\nfig.append_trace(trace9, 3, 3)\n\nfig['layout'].update(height=1500, width=1200, paper_bgcolor='rgb(233,233,233)', title=\"Geography Plots\")\npy.iplot(fig, filename='geo-plots')","metadata":{"execution":{"iopub.status.busy":"2023-12-05T01:49:48.513720Z","iopub.execute_input":"2023-12-05T01:49:48.514446Z","iopub.status.idle":"2023-12-05T01:49:49.515375Z","shell.execute_reply.started":"2023-12-05T01:49:48.514403Z","shell.execute_reply":"2023-12-05T01:49:49.514552Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Continent\ncnt_srs = train_df.groupby('trafficSource.source')['totals.transactionRevenue'].agg(['size', 'count', 'mean'])\ncnt_srs.columns = [\"count\", \"count of non-zero revenue\", \"mean\"]\ncnt_srs = cnt_srs.sort_values(by=\"count\", ascending=False)\ntrace1 = horizontal_bar_chart(cnt_srs[\"count\"].head(10), 'green')\ntrace2 = horizontal_bar_chart(cnt_srs[\"count of non-zero revenue\"].head(10), 'green')\ntrace3 = horizontal_bar_chart(cnt_srs[\"mean\"].head(10), 'green')\n\n# Sub-continent\ncnt_srs = train_df.groupby('trafficSource.medium')['totals.transactionRevenue'].agg(['size', 'count', 'mean'])\ncnt_srs.columns = [\"count\", \"count of non-zero revenue\", \"mean\"]\ncnt_srs = cnt_srs.sort_values(by=\"count\", ascending=False)\ntrace4 = horizontal_bar_chart(cnt_srs[\"count\"], 'purple')\ntrace5 = horizontal_bar_chart(cnt_srs[\"count of non-zero revenue\"], 'purple')\ntrace6 = horizontal_bar_chart(cnt_srs[\"mean\"], 'purple')\n# Creating two subplots\nfig = tools.make_subplots(rows=2, cols=3, vertical_spacing=0.08, horizontal_spacing=0.15, \n                          subplot_titles=[\"Traffic Source - Count\", \"Traffic Source - Non-zero Revenue Count\", \"Traffic Source - Mean Revenue\",\n                                          \"Traffic Source Medium - Count\",  \"Traffic Source Medium - Non-zero Revenue Count\", \"Traffic Source Medium - Mean Revenue\"\n                                          ])\n\nfig.append_trace(trace1, 1, 1)\nfig.append_trace(trace2, 1, 2)\nfig.append_trace(trace3, 1, 3)\nfig.append_trace(trace4, 2, 1)\nfig.append_trace(trace5, 2, 2)\nfig.append_trace(trace6, 2, 3)\n\nfig['layout'].update(height=1000, width=1200, paper_bgcolor='rgb(233,233,233)', title=\"Traffic Source Plots\")\npy.iplot(fig, filename='traffic-source-plots')","metadata":{"execution":{"iopub.status.busy":"2023-12-05T01:51:31.814501Z","iopub.execute_input":"2023-12-05T01:51:31.815227Z","iopub.status.idle":"2023-12-05T01:51:32.733888Z","shell.execute_reply.started":"2023-12-05T01:51:31.815190Z","shell.execute_reply":"2023-12-05T01:51:32.732609Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Page views\ncnt_srs = train_df.groupby('totals.pageviews')['totals.transactionRevenue'].agg(['size', 'count', 'mean'])\ncnt_srs.columns = [\"count\", \"count of non-zero revenue\", \"mean\"]\ncnt_srs = cnt_srs.sort_values(by=\"count\", ascending=False)\ntrace1 = horizontal_bar_chart(cnt_srs[\"count\"].head(60), 'cyan')\ntrace2 = horizontal_bar_chart(cnt_srs[\"count of non-zero revenue\"].head(60), 'cyan')\ntrace5 = horizontal_bar_chart(cnt_srs[\"mean\"].head(60), 'cyan')\n\n# Hits\ncnt_srs = train_df.groupby('totals.hits')['totals.transactionRevenue'].agg(['size', 'count', 'mean'])\ncnt_srs.columns = [\"count\", \"count of non-zero revenue\", 'mean']\ncnt_srs = cnt_srs.sort_values(by=\"count\", ascending=False)\ntrace3 = horizontal_bar_chart(cnt_srs[\"count\"].head(60), 'black')\ntrace4 = horizontal_bar_chart(cnt_srs[\"count of non-zero revenue\"].head(60), 'black')\n# Creating two subplots\nfig = tools.make_subplots(rows=2, cols=3, vertical_spacing=0.08, horizontal_spacing=0.15, \n                          subplot_titles=[\"Total Pageviews - Count\", \"Total Pageviews - Non-zero Revenue Count\", \"Total Pageviews - Mean Revenue\",\n                                          \"Total Hits - Count\",  \"Total Hits - Non-zero Revenue Count\", \"Total Hits - Mean Revenue\"])\n\nfig.append_trace(trace1, 1, 1)\nfig.append_trace(trace2, 1, 2)\nfig.append_trace(trace5, 1, 3)\nfig.append_trace(trace3, 2, 1)\nfig.append_trace(trace4, 2, 2)\nfig.append_trace(trace6, 2, 3)\n\nfig['layout'].update(height=1200, width=900, paper_bgcolor='rgb(233,233,233)', title=\"Visitor Profile Plots\")\npy.iplot(fig, filename='visitor-profile-plots')","metadata":{"execution":{"iopub.status.busy":"2023-12-05T01:53:20.562872Z","iopub.execute_input":"2023-12-05T01:53:20.563415Z","iopub.status.idle":"2023-12-05T01:53:21.027037Z","shell.execute_reply.started":"2023-12-05T01:53:20.563377Z","shell.execute_reply":"2023-12-05T01:53:21.025912Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Variables not in test but in train : \", set(train_df.columns).difference(set(test_df.columns)))","metadata":{"execution":{"iopub.status.busy":"2023-12-05T01:56:07.990730Z","iopub.execute_input":"2023-12-05T01:56:07.991296Z","iopub.status.idle":"2023-12-05T01:56:07.997970Z","shell.execute_reply.started":"2023-12-05T01:56:07.991257Z","shell.execute_reply":"2023-12-05T01:56:07.996680Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cols_to_drop = const_cols + ['sessionId']\ntrain_df=train_df.drop(cols_to_drop+[\"trafficSource.campaignCode\"],axis=1)\ntest_df=test_df.drop(cols_to_drop,axis=1)","metadata":{"execution":{"iopub.status.busy":"2023-12-05T01:58:02.930705Z","iopub.execute_input":"2023-12-05T01:58:02.931239Z","iopub.status.idle":"2023-12-05T01:58:04.800121Z","shell.execute_reply.started":"2023-12-05T01:58:02.931200Z","shell.execute_reply":"2023-12-05T01:58:04.798932Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df[\"totals.transactionRevenue\"].fillna(0,inplace=True)\ntrain_y = train_df[\"totals.transactionRevenue\"].values\ntrain_id = train_df[\"fullVisitorId\"].values\ntest_id = test_df[\"fullVisitorId\"].values","metadata":{"execution":{"iopub.status.busy":"2023-12-05T01:59:16.340420Z","iopub.execute_input":"2023-12-05T01:59:16.340895Z","iopub.status.idle":"2023-12-05T01:59:16.350082Z","shell.execute_reply.started":"2023-12-05T01:59:16.340850Z","shell.execute_reply":"2023-12-05T01:59:16.348976Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# label encode the categorical variables and convert the numerical variables to float\ncat_cols = [\"channelGrouping\", \"device.browser\", \n            \"device.deviceCategory\", \"device.operatingSystem\", \n            \"geoNetwork.city\", \"geoNetwork.continent\", \n            \"geoNetwork.country\", \"geoNetwork.metro\",\n            \"geoNetwork.networkDomain\", \"geoNetwork.region\", \n            \"geoNetwork.subContinent\", \"trafficSource.adContent\", \n            \"trafficSource.adwordsClickInfo.adNetworkType\", \n            \"trafficSource.adwordsClickInfo.gclId\", \n            \"trafficSource.adwordsClickInfo.page\", \n            \"trafficSource.adwordsClickInfo.slot\", \"trafficSource.campaign\",\n            \"trafficSource.keyword\", \"trafficSource.medium\", \n            \"trafficSource.referralPath\", \"trafficSource.source\",\n            'trafficSource.adwordsClickInfo.isVideoAd', 'trafficSource.isTrueDirect']\nfor col in cat_cols:\n    print(col)\n    lbl = preprocessing.LabelEncoder()\n    lbl.fit(list(train_df[col].values.astype('str')) + list(test_df[col].values.astype('str')))\n    train_df[col] = lbl.transform(list(train_df[col].values.astype('str')))\n    test_df[col] = lbl.transform(list(test_df[col].values.astype('str')))\nnum_cols = [\"totals.hits\", \"totals.pageviews\", \"visitNumber\", \"visitStartTime\", 'totals.bounces',  'totals.newVisits']    \nfor col in num_cols:\n    train_df[col] = train_df[col].astype(float)\n    test_df[col] = test_df[col].astype(float)\n    ","metadata":{"execution":{"iopub.status.busy":"2023-12-05T02:10:47.348777Z","iopub.execute_input":"2023-12-05T02:10:47.349391Z","iopub.status.idle":"2023-12-05T02:14:17.931627Z","shell.execute_reply.started":"2023-12-05T02:10:47.349345Z","shell.execute_reply":"2023-12-05T02:14:17.930550Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dev_df=train_df[train_df['date']<=datetime.date(2017,5,31)]\nval_df = train_df[train_df['date']>datetime.date(2017,5,31)]\ndev_y=np.log1p(dev_df[\"totals.transactionRevenue\"].values)\nval_y = np.log1p(val_df[\"totals.transactionRevenue\"].values)\ndev_X = dev_df[cat_cols + num_cols] \nval_X = val_df[cat_cols + num_cols] \ntest_X = test_df[cat_cols + num_cols] \n","metadata":{"execution":{"iopub.status.busy":"2023-12-05T02:16:28.027954Z","iopub.execute_input":"2023-12-05T02:16:28.028453Z","iopub.status.idle":"2023-12-05T02:16:28.728286Z","shell.execute_reply.started":"2023-12-05T02:16:28.028419Z","shell.execute_reply":"2023-12-05T02:16:28.726964Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# custom function to run light gbm model\ndef run_lgb(train_X, train_y, val_X, val_y, test_X):\n    params = {\n        \"objective\" : \"regression\",\n        \"metric\" : \"rmse\", \n        \"num_leaves\" : 30,\n        \"min_child_samples\" : 100,\n        \"learning_rate\" : 0.1,\n        \"bagging_fraction\" : 0.7,\n        \"feature_fraction\" : 0.5,\n        \"bagging_frequency\" : 5,\n        \"bagging_seed\" : 2018,\n        \"verbosity\" : -1\n    }\n    \n    lgtrain = lgb.Dataset(train_X, label=train_y)\n    lgval = lgb.Dataset(val_X, label=val_y)\n    model = lgb.train(params, lgtrain, 1000, valid_sets=[lgval], early_stopping_rounds=100, verbose_eval=100)\n    \n    pred_test_y = model.predict(test_X, num_iteration=model.best_iteration)\n    pred_val_y = model.predict(val_X, num_iteration=model.best_iteration)\n    return pred_test_y, model, pred_val_y\n\n# Training the model #\npred_test, model, pred_val = run_lgb(dev_X, dev_y, val_X, val_y, test_X)","metadata":{"execution":{"iopub.status.busy":"2023-12-05T02:16:33.474714Z","iopub.execute_input":"2023-12-05T02:16:33.475802Z","iopub.status.idle":"2023-12-05T02:16:52.943289Z","shell.execute_reply.started":"2023-12-05T02:16:33.475757Z","shell.execute_reply":"2023-12-05T02:16:52.942379Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn import metrics\npred_val[pred_val<0] = 0\nval_pred_df = pd.DataFrame({\"fullVisitorId\":val_df[\"fullVisitorId\"].values})\nval_pred_df[\"transactionRevenue\"] = val_df[\"totals.transactionRevenue\"].values\nval_pred_df[\"PredictedRevenue\"] = np.expm1(pred_val)\n#print(np.sqrt(metrics.mean_squared_error(np.log1p(val_pred_df[\"transactionRevenue\"].values), np.log1p(val_pred_df[\"PredictedRevenue\"].values))))\nval_pred_df = val_pred_df.groupby(\"fullVisitorId\")[[\"transactionRevenue\", \"PredictedRevenue\"]].sum().reset_index()\nprint(np.sqrt(metrics.mean_squared_error(np.log1p(val_pred_df[\"transactionRevenue\"].values), np.log1p(val_pred_df[\"PredictedRevenue\"].values))))","metadata":{"execution":{"iopub.status.busy":"2023-12-05T02:26:17.027174Z","iopub.execute_input":"2023-12-05T02:26:17.028170Z","iopub.status.idle":"2023-12-05T02:26:17.311002Z","shell.execute_reply.started":"2023-12-05T02:26:17.028130Z","shell.execute_reply":"2023-12-05T02:26:17.309833Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub_df = pd.DataFrame({\"fullVisitorId\":test_id})\npred_test[pred_test<0] = 0\nsub_df[\"PredictedLogRevenue\"] = np.expm1(pred_test)\nsub_df = sub_df.groupby(\"fullVisitorId\")[\"PredictedLogRevenue\"].sum().reset_index()\nsub_df.columns = [\"fullVisitorId\", \"PredictedLogRevenue\"]\nsub_df[\"PredictedLogRevenue\"] = np.log1p(sub_df[\"PredictedLogRevenue\"])\nsub_df.to_csv(\"baseline_lgb.csv\", index=False)","metadata":{"execution":{"iopub.status.busy":"2023-12-05T02:27:20.940580Z","iopub.execute_input":"2023-12-05T02:27:20.942943Z","iopub.status.idle":"2023-12-05T02:27:25.811537Z","shell.execute_reply.started":"2023-12-05T02:27:20.942880Z","shell.execute_reply":"2023-12-05T02:27:25.810451Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Feature Importance\nfig,ax=plt.subplots(figsize=(12,18))\nlgb.plot_importance(model, max_num_features=50, height=0.8, ax=ax)\nax.grid(False)\nplt.title(\"LightGBM - Feature Importance\", fontsize=15)\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2023-12-05T02:28:53.353178Z","iopub.execute_input":"2023-12-05T02:28:53.353609Z","iopub.status.idle":"2023-12-05T02:28:54.062437Z","shell.execute_reply.started":"2023-12-05T02:28:53.353577Z","shell.execute_reply":"2023-12-05T02:28:54.061262Z"},"trusted":true},"execution_count":null,"outputs":[]}]}