{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"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 in \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 \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"../input\"))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\nimport json\nfrom pandas.io.json import json_normalize\nimport plotly.graph_objs as go\n\nfrom plotly import tools\nimport plotly.offline as py\npy.init_notebook_mode(connected=True)\n\n\ndef load_df(csv_path='../input/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 = 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\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"scrolled":true,"_uuid":"cded78624e33b24b5964d814538965d09d517292"},"cell_type":"code","source":"train_df = load_df()\ntest_df = load_df(\"../input/test.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"8d9c50577c8b27d7ae13a0aef1fe78aa1c49cb03"},"cell_type":"code","source":"train_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"55dee559385028f3394ea5cf99d9c42c7f8cf561","scrolled":true},"cell_type":"code","source":"train_df[\"totals.transactionRevenue\"] = train_df[\"totals.transactionRevenue\"].astype('float')\ngdf = train_df.groupby(\"fullVisitorId\")[\"totals.transactionRevenue\"].sum().reset_index()\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"ca95c29459fb9fbef5876f53c1df78ab3c96993b","scrolled":true},"cell_type":"code","source":"nzi = pd.notnull(train_df[\"totals.transactionRevenue\"]).sum()\nnzr = (gdf[\"totals.transactionRevenue\"]>0).sum()\nprint(\"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])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"scrolled":true,"_uuid":"6a519b4ee7031a6f91f32b4ddd97d4eaa6e8062e"},"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())) ))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"3b3e6ce0e5922b08d4881d41b4b13f07f9b24e58"},"cell_type":"code","source":"const_cols = [c for c in train_df.columns if train_df[c].nunique(dropna=False)==1 ]\nprint(\"Total number of columns: \", train_df.shape[1])\nprint(\"Total columns with single value (including NA): \",len(const_cols))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"ed3488d4acc3f2610581a0bb5ddf6c6ebb2eb29e","scrolled":true},"cell_type":"code","source":"\nconst_cols","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"48c730f62085f8a65fb232f7c7fe66b3a2fde65a"},"cell_type":"code","source":"print(\"Variables not in test but in train : \", set(train_df.columns).difference(set(test_df.columns)))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"b3b69cd7d7feea8e705e287007408a2de1235e78"},"cell_type":"code","source":"cols_to_drop = const_cols + ['sessionId']\n\ntrain_df = train_df.drop(cols_to_drop + [\"trafficSource.campaignCode\"], axis=1)\ntest_df = test_df.drop(cols_to_drop, axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a1a7873266393e368b786a56809fc76a9f2bb64a"},"cell_type":"code","source":"const_cols_na = [c for c in train_df.columns if train_df[c].nunique()==1 ]\nprint(\"Total number of columns: \", train_df.shape[1])\nprint(\"Total columns with single value (without NA): \",len(const_cols_na))\nconst_cols_na","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"94a11a3ef2e998ce5fd79a52101c7a8dc1627614"},"cell_type":"code","source":"#Convert VisitStartTime from POSIX format to pandas date time\ntrain_df[\"date\"] = pd.to_datetime(train_df[\"date\"],format=\"%Y%m%d\")\ntrain_df[\"visitStartTime\"] = pd.to_datetime(train_df[\"visitStartTime\"],unit='s')\ntrain_df.select_dtypes('object').describe()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"scrolled":true,"_uuid":"6858b587e71387b314ab605606fc29e92ef2e656"},"cell_type":"code","source":"train_df.select_dtypes(exclude=('object')).head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"cf1ddcbb358677423794aef0b299fd0b6b49e567"},"cell_type":"code","source":"train_df.visitNumber.describe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"3b998306a9651448e2186cc26db8354325229350"},"cell_type":"code","source":"\"90 percent of sessions have visitNumber lower than {} times.\".format(np.percentile(list(train_df.visitNumber),90))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"41d4b0d11d9f064e3b91d624cf72b6f0242467b8"},"cell_type":"code","source":"import collections\n\ntmp_least_10_visitNumbers_list = collections.Counter(list(train_df.visitNumber)).most_common()[:-10-1:-1]\ntmp_most_10_visitNumbers_list = collections.Counter(list(train_df.visitNumber)).most_common(10)\nleast_visitNumbers = []\nmost_visitNumbers = []\nfor i in tmp_least_10_visitNumbers_list:\n    least_visitNumbers.append(i[0])\nfor i in tmp_most_10_visitNumbers_list:\n    most_visitNumbers.append(i[0])\nprint(\"10 most_common visitNumbers are {} times and 10 least_common visitNumbers are {} times\".format(most_visitNumbers,least_visitNumbers))\nprint(\"Max visitnumber: \",train_df.visitNumber.max())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"scrolled":true,"_uuid":"c2b470e4b65ca13599ceb326f372d9f3c75d658e"},"cell_type":"code","source":"repetitive_users = list(np.sort(list(collections.Counter(list(train_df[\"fullVisitorId\"])).values())))\n\"25% percentile: {}, 50% percentile: {}, 75% percentile: {}, 88% percentile: {}, 96% percentile: {}\".format(\nnp.percentile(repetitive_users,q=25),np.percentile(repetitive_users,q=50),\nnp.percentile(repetitive_users,q=75),np.percentile(repetitive_users,q=88), np.percentile(repetitive_users,q=96))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"scrolled":true,"_uuid":"14ffc71dbee87e77999d1ce3a1312a2ff0db99c2"},"cell_type":"code","source":"train_df['VisitCount']=train_df.groupby(['fullVisitorId'])['visitStartTime'].rank(ascending=True)\ntrain_df[train_df['VisitCount']>1].head()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"92dfcf22620d4497e27cc5a88c768a18e42d437b"},"cell_type":"code","source":"test_df['VisitCount']=test_df.groupby(['fullVisitorId'])['visitStartTime'].rank(ascending=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"d9fa772aea9c0755e69ad395bf96b6b8c6f9c7c6"},"cell_type":"code","source":"\nimport datetime\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\n#train_df['date'] = train_df['date'].apply(lambda x: datetime.date(int(str(x)[:4]), int(str(x)[4:6]), int(str(x)[6:])))\ncnt_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()\n#cnt_srs.index = cnt_srs.index.astype('str')\ntrace1 = scatter_plot(cnt_srs[\"count\"], 'red')\ntrace2 = scatter_plot(cnt_srs[\"count of non-zero revenue\"], 'blue')\n\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')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f3be2b543b958ede155a0d4d1f34f0004ddf4f3e"},"cell_type":"code","source":"test_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"ea558bb2725991e93e03b5f54702abbaa3ddd8c9"},"cell_type":"code","source":"test_df[\"date\"] = pd.to_datetime(test_df[\"date\"],format=\"%Y%m%d\")\ntest_df[\"visitStartTime\"] = pd.to_datetime(test_df[\"visitStartTime\"],unit='s')\n#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\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"2bdc41543ab53c26138e805dc9aa9ebdaad1487c"},"cell_type":"code","source":"train_df['sess_date_dow'] = train_df['date'].dt.day_name()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"7ace76cc6e089561d029ece1baa803f6e2e891d9"},"cell_type":"code","source":"test_df['sess_date_dow'] = test_df['date'].dt.day_name()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"scrolled":true,"_uuid":"706246745797a41285fc6ecb3d12aad4d6ad7aaf"},"cell_type":"code","source":"train_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"scrolled":false,"_uuid":"b5f588ee6897bbc027190565827ac914000c21e0"},"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# Device Browser\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)')\n\n# 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)')\n\n# 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\n# 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')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"c7658d859f72bbf2cfbbedaca3f3e71a4caf5582","scrolled":true},"cell_type":"code","source":"\n# 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# Sub-continent\ncnt_srs = train_df.groupby('geoNetwork.subContinent')['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\"], '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_srs = train_df.groupby('geoNetwork.networkDomain')['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), '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\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')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a60154a4b0858f89d108b36d8f2344e815160c9a"},"cell_type":"code","source":"\n# TrafficSource\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# Trafficmedium\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\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')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"850b61156a0f2abb7f9b9460618f1cbc6f2be900"},"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')\ntrace6 = horizontal_bar_chart(cnt_srs[\"mean\"].head(60), 'black')\n\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')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"0501fcb12e6939a7c5f7f499792fe174954ab2e8"},"cell_type":"code","source":"# Impute 0 for missing target values\ntrain_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","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"b27f17a338b8a5497104ddac0cb8e50ba689dd60"},"cell_type":"code","source":"train_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"scrolled":true,"_uuid":"6e8415244599a08dc2f0a90c1920bea2f1040cb7"},"cell_type":"code","source":"from sklearn import model_selection, preprocessing, metrics\nimport lightgbm as lgb\n# 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','sess_date_dow']\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')))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"686416a9f25cee02603e1209ac61f05bd00f4baa"},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f7b937086de95a664c6b74f5d40f4aac8df27f2a"},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}