{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Imports","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install plotly_express","execution_count":null,"outputs":[]},{"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\n\nimport os\nimport json\nimport numpy as np\nimport pandas as pd\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport plotly_express as px\nfrom plotly import tools\nimport plotly.offline as py\npy.init_notebook_mode(connected=True)\nimport plotly.graph_objs as go\n%matplotlib inline\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 5GB 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","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Data Loading","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def load_df(csv_path, 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","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df = load_df('/kaggle/input/ga-customer-revenue-prediction/train.csv')\ntest_df = load_df('/kaggle/input/ga-customer-revenue-prediction/test.csv')\ntrain_df.to_csv('./train.csv', index=False)\ntest_df.to_csv('./test.csv', index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df = pd.read_csv('./train.csv', low_memory=False)\ntest_df = pd.read_csv('./test.csv', low_memory=False)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Initial Analysis","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df['device.isMobile'] = train_df['device.isMobile'].astype(int)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df[['totals.visits', 'totals.hits', 'totals.pageviews', 'totals.bounces', 'totals.newVisits', 'totals.transactionRevenue']] = train_df[['totals.visits', 'totals.hits', 'totals.pageviews', 'totals.bounces', 'totals.newVisits', 'totals.transactionRevenue']].astype(float)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Target Variable\ntrain_df['totals.transactionRevenue'] = train_df['totals.transactionRevenue'].fillna(0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.describe()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# In-Depth Analysis","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"## Inspecting Null Values","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"null_df = pd.DataFrame(train_df.isnull().sum()*100/train_df.shape[0], columns=['null_pct']).sort_values(by='null_pct', ascending=True)\nnull_df = null_df[null_df['null_pct'] > 0]\nax = null_df.plot(kind='barh', figsize=(10,7), color=\"coral\", fontsize=13, legend=False)\nfor i in ax.patches:\n    ax.text(i.get_width()+.3, i.get_y()+0.1, str(round(i.get_width(), 2))+'%', fontsize=15, color='dimgrey')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"null_df.index","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Dropping Mostly-Null Columns \ntrain_df = train_df.drop([\n    'sessionId', 'visitId', \\\n    'trafficSource.campaignCode', 'trafficSource.adContent', 'trafficSource.adwordsClickInfo.gclId', \\\n    'trafficSource.adwordsClickInfo.page', 'trafficSource.adwordsClickInfo.slot',\\\n    'trafficSource.adwordsClickInfo.adNetworkType', 'trafficSource.adwordsClickInfo.isVideoAd' \\\n], axis=1)\ntrain_df.shape","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Inspecting Categorical Columns","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"cat_df = pd.DataFrame(train_df.apply(lambda x: x.nunique()).sort_values(), columns=['num_uniques'])\nna_cols = cat_df[cat_df['num_uniques'] == 1].index\ncat_df = cat_df[cat_df['num_uniques'] != 1]\ntrain_df = train_df.drop(na_cols, axis=1)\ncat_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.shape","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Target Variable Analysis","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"Since we are predicting the natural log of sum of all transactions of the user, let us sum up the transaction revenue at user level and take a log and then do a scatter plot.","execution_count":null},{"metadata":{"trusted":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\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 6))\nfig.suptitle('Target Variable - Original vs Log')\nax1.scatter(range(gdf.shape[0]), np.sort(gdf[\"totals.transactionRevenue\"].values))\nax2.scatter(range(gdf.shape[0]), np.sort(np.log1p(gdf[\"totals.transactionRevenue\"].values)))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"In this competition, the data set is so unbalanced that it's hard to say whether our solution can beat all-zeros, because most of the customers don't bring in any real revenue. And if a customer will pay, the minimum of transaction revenue is no less than 1E+07.\n\nThis is in line with what was explained in the competition overview:\n> The 80/20 rule has proven true for many businesses–only a small percentage of customers produce most of the revenue. As such, marketing teams are challenged to make appropriate investments in promotional strategies.\n\nIn this case, the ratio is even worse:","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"print(f\"Percentage of Customers who brought Revenue: {round(100 * sum(gdf['totals.transactionRevenue'] > 0) / gdf['totals.transactionRevenue'].shape[0], 2)}%\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"The log operation normalizes the target and reduces the spread enough for a model to be able to predict it.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Number of unique visitors in train set : \",train_df.fullVisitorId.nunique(), \"/\", train_df.shape[0])\nprint(\"Number of unique visitors in test set : \",test_df.fullVisitorId.nunique(), \"/\", 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())) ))\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df['totals.transactionRevenue'] = train_df['totals.transactionRevenue'].replace({0: np.nan})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"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","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Device Information","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# 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# Creating two subplots\nfig = tools.make_subplots(rows=1, cols=3, vertical_spacing=0.04, \n                          subplot_titles=[\"Count\", \"Non-zero Revenue Count\", \"Mean Revenue\"])\n\nfig.append_trace(trace1, 1, 1)\nfig.append_trace(trace2, 1, 2)\nfig.append_trace(trace3, 1, 3)\n\nfig['layout'].update(height=1200, width=1200, paper_bgcolor='rgb(233,233,233)', title=\"Device Browser\")\npy.iplot(fig)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"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)\ntrace1 = horizontal_bar_chart(cnt_srs[\"count\"].head(10), 'rgba(71, 58, 131, 0.8)')\ntrace2 = horizontal_bar_chart(cnt_srs[\"count of non-zero revenue\"].head(10), 'rgba(71, 58, 131, 0.8)')\ntrace3 = horizontal_bar_chart(cnt_srs[\"mean\"].head(10), 'rgba(71, 58, 131, 0.8)')\n# Creating two subplots\nfig = tools.make_subplots(rows=1, cols=3, vertical_spacing=0.04, \n                          subplot_titles=[\"Count\", \"Non-zero Revenue Count\", \"Mean Revenue\"])\n\nfig.append_trace(trace1, 1, 1)\nfig.append_trace(trace2, 1, 2)\nfig.append_trace(trace3, 1, 3)\n\nfig['layout'].update(height=1200, width=1200, paper_bgcolor='rgb(233,233,233)', title=\"Device Category\")\npy.iplot(fig)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"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)\ntrace1 = horizontal_bar_chart(cnt_srs[\"count\"].head(10), 'rgba(246, 78, 139, 0.6)')\ntrace2 = horizontal_bar_chart(cnt_srs[\"count of non-zero revenue\"].head(10),'rgba(246, 78, 139, 0.6)')\ntrace3 = horizontal_bar_chart(cnt_srs[\"mean\"].head(10),'rgba(246, 78, 139, 0.6)')\n# Creating two subplots\nfig = tools.make_subplots(rows=1, cols=3, vertical_spacing=0.04, \n                          subplot_titles=[\"Count\", \"Non-zero Revenue Count\", \"Mean Revenue\"])\n\nfig.append_trace(trace1, 1, 1)\nfig.append_trace(trace2, 1, 2)\nfig.append_trace(trace3, 1, 3)\n\nfig['layout'].update(height=1200, width=1200, paper_bgcolor='rgb(233,233,233)', title=\"Operating System\")\npy.iplot(fig)\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Inferences:\n\n* Device Browser distribution looks similar on both the count and count of non-zero revenue plots\n* On the device category front, Desktop seem to have higher percentage of non-zero revenue counts compared to Mobile Devices.\n* In device operating system, though the number of counts is more from windows, the number of counts where revenue is not zero is more for Macintosh.\n* Chrome OS also has higher percentage of non-zero revenue counts\n* On the mobile OS side, iOS has more percentage of non-zero revenue counts compared to Android","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"## Geographical Information","execution_count":null},{"metadata":{"trusted":true},"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# Creating two subplots\nfig = tools.make_subplots(rows=1, cols=3, vertical_spacing=0.08, horizontal_spacing=0.15, \n                          subplot_titles=[\"Count\", \"Non-zero Revenue Count\", \"Mean Revenue\"])\n\nfig.append_trace(trace1, 1, 1)\nfig.append_trace(trace2, 1, 2)\nfig.append_trace(trace3, 1, 3)\n\nfig['layout'].update(height=1500, width=1200, paper_bgcolor='rgb(233,233,233)', title=\"Continent\")\npy.iplot(fig)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# 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)\ntrace1 = horizontal_bar_chart(cnt_srs[\"count\"], 'orange')\ntrace2 = horizontal_bar_chart(cnt_srs[\"count of non-zero revenue\"], 'orange')\ntrace3 = horizontal_bar_chart(cnt_srs[\"mean\"], 'orange')\n\n# Creating two subplots\nfig = tools.make_subplots(rows=1, cols=3, vertical_spacing=0.08, horizontal_spacing=0.15, \n                          subplot_titles=[\"Count\", \"Non-zero Revenue Count\", \"Mean Revenue\"])\n\nfig.append_trace(trace1, 1, 1)\nfig.append_trace(trace2, 1, 2)\nfig.append_trace(trace3, 1, 3)\n\nfig['layout'].update(height=1500, width=1200, paper_bgcolor='rgb(233,233,233)', title=\"Sub Continent\")\npy.iplot(fig)\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Inferences:\n\n* On the continent plot, we can see that America has both higher number of counts as well as highest number of counts where the revenue is non-zero\n* Though Asia and Europe have high number of counts, the number of non-zero revenue counts from these continents are comparatively low.\n* These two points hold true for the Sub Continents plot as well.","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"## Traffic Information","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# Source\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# Creating two subplots\nfig = tools.make_subplots(rows=1, cols=3, vertical_spacing=0.08, horizontal_spacing=0.15, \n                          subplot_titles=[\"Count\", \"Non-zero Revenue Count\", \"Mean Revenue\"])\n\nfig.append_trace(trace1, 1, 1)\nfig.append_trace(trace2, 1, 2)\nfig.append_trace(trace3, 1, 3)\n\nfig['layout'].update(height=1500, width=1200, paper_bgcolor='rgb(233,233,233)', title=\"Traffic Source\")\npy.iplot(fig)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Medium\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)\ntrace1 = horizontal_bar_chart(cnt_srs[\"count\"], 'purple')\ntrace2 = horizontal_bar_chart(cnt_srs[\"count of non-zero revenue\"], 'purple')\ntrace3 = horizontal_bar_chart(cnt_srs[\"mean\"], 'purple')\n\n# Creating two subplots\nfig = tools.make_subplots(rows=1, cols=3, vertical_spacing=0.08, horizontal_spacing=0.15, \n                          subplot_titles=[\"Count\", \"Non-zero Revenue Count\", \"Mean Revenue\"])\n\nfig.append_trace(trace1, 1, 1)\nfig.append_trace(trace2, 1, 2)\nfig.append_trace(trace3, 1, 3)\n\nfig['layout'].update(height=1500, width=1200, paper_bgcolor='rgb(233,233,233)', title=\"Traffic Medium\")\npy.iplot(fig)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Inferences:\n\n* In the traffic source plot, even though Youtube has high number of counts in the dataset, the number of non-zero revenue counts are very less.\n* Google plex has a high ratio of non-zero revenue count to total count in the traffic source plot.\n* On the traffic source medium, \"referral\" has more number of non-zero revenue count compared to \"organic\" medium.","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"## User Activity Information","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"gdf = train_df.groupby(\"fullVisitorId\").agg({'totals.hits': 'sum', 'totals.pageviews': 'sum', 'totals.transactionRevenue': 'sum'})\ngdf['isPayingVisitor'] = gdf['totals.transactionRevenue'] > 0","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"px.scatter(gdf, x='totals.hits', facet_col='isPayingVisitor')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"px.scatter(gdf, x='totals.pageviews', facet_col='isPayingVisitor')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Inferences:\n\n* People with a higher(>300) number of \"hits\" tend to have a higher chance of being paying customers.\n* This holds true for \"pageviews\" as well and the distinction is clearer, suggesting that \"pageviews\" might be a more important feature than \"hits\"","execution_count":null}],"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":4,"nbformat_minor":4}