{"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\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","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import numpy as np \nimport pandas as pd \nimport json\nimport os\nfrom pandas.io.json import json_normalize\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nfrom plotly import tools\nimport plotly.offline as py\nimport plotly.graph_objs as go\n\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import TimeSeriesSplit, KFold\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.model_selection import train_test_split\n\npd.options.display.max_columns = None","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import torch \nfrom torch import nn\nimport seaborn as sns","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Google Analytics Customer Revenue Prediction\n"},{"metadata":{},"cell_type":"markdown","source":"## 1. Load Data and Format data"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"data_path = \"../input/ga-customer-revenue-prediction/\"\ntrain_df = pd.read_csv(data_path+ \"train.csv\")\ntest_df = pd.read_csv(data_path+ \"test.csv\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Extract json data from csv"},{"metadata":{"trusted":true},"cell_type":"code","source":"def load_df(csv_path='kaggle/train.csv', nrows=None):\n    JSON_COLUMNS = ['device', 'geoNetwork', 'totals', 'trafficSource']\n    df = pd.read_csv(csv_path,converters={column: json.loads for column in JSON_COLUMNS},dtype={'fullVisitorId': 'str'},nrows=nrows)\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\ntrain = load_df(csv_path = data_path+ \"train.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.info()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# 2. Exploratory Data Analysis (EDA)"},{"metadata":{},"cell_type":"markdown","source":"Since the goal is to predict the total revenue per user, so we want to explore the total_revenue grouped by each user"},{"metadata":{"trusted":true},"cell_type":"code","source":"train[\"totals.transactionRevenue\"] = train[\"totals.transactionRevenue\"].astype('float')\ngdf = train.groupby(\"fullVisitorId\")[\"totals.transactionRevenue\"].sum().reset_index()\n\nplt.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)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"not_none_transaction = sum(gdf[\"totals.transactionRevenue\"]>0)\nprint(\"There are %d transactions and %d transactions have consumptions, %.3f%% are transactions are >0\"%( \n                                                                                len(gdf), not_none_transaction,\n                                                                                100*not_none_transaction/len(gdf)))\nnot_none_records = pd.notnull(train[\"totals.transactionRevenue\"]).sum()\nprint(\"There are %d out of %d records with NaN values. %.3f%% transactions are Nan \"%(not_none_records, len(train[\"totals.transactionRevenue\"]),\n                                                                                      100*not_none_records/len(train[\"totals.transactionRevenue\"])))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"visit_cnt = train.groupby(\"fullVisitorId\")[[\"totals.hits\"]].sum().reset_index()\ndf = visit_cnt.sample(1000)\nplt.figure(figsize=(8,6))\nplt.scatter(range(df.shape[0]), np.sort(df[\"totals.hits\"]))\nplt.xlabel('index', fontsize=12)\nplt.ylabel('hits', fontsize=12)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, ax = plt.subplots(1,1, figsize=(20,8))\nplt.hist( x= np.sort(df[\"totals.hits\"]),orientation= \"vertical\",bins=50)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"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\ntrain['date'] = train['date'].apply(lambda x: datetime.date(int(str(x)[:4]), int(str(x)[4:6]), int(str(x)[6:])))\ncnt_srs = train.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":{},"cell_type":"markdown","source":"# 3. Data Preprocessing"},{"metadata":{"trusted":true},"cell_type":"code","source":"train['trafficSource.adwordsClickInfo.isVideoAd'].fillna(True, inplace=True)\ntrain['trafficSource.isTrueDirect'].fillna(False, inplace=True)\n\n# remove columns with only one distinct value\ncols_to_drop = [col for col in train.columns if train[col].nunique(dropna=False) == 1]\ntrain.drop(cols_to_drop, axis=1, inplace=True)\n\n#only one not null value\ntrain.drop(['trafficSource.campaignCode'], axis=1, inplace=True)\n\ntrain.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"num_cols = ['visitNumber', 'totals.hits', 'totals.pageviews', 'totals.bounces', 'totals.newVisits', 'totals.transactionRevenue']\n\nfor col in num_cols:\n    train[col] = train[col].fillna(0)\n    train[col] = train[col].astype(float)\n    train[col] = np.log1p(train[col])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train['trafficSource.adContent'] = train['trafficSource.adContent'].fillna(0)\ntrain['trafficSource.keyword'] = train['trafficSource.keyword'].fillna(0)\ntrain['trafficSource.adwordsClickInfo.adNetworkType'] = train['trafficSource.adwordsClickInfo.adNetworkType'].fillna(0)\ntrain['trafficSource.adwordsClickInfo.gclId'] = train['trafficSource.adwordsClickInfo.gclId'].fillna(0)\ntrain['trafficSource.adwordsClickInfo.page'] = train['trafficSource.adwordsClickInfo.page'].fillna(0)\ntrain['trafficSource.adwordsClickInfo.slot'] = train['trafficSource.adwordsClickInfo.slot'].fillna(0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train['device.browser'].nunique(),train['device.deviceCategory'].nunique()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train['browser_category'] = train['device.browser'] + '_' + train['device.deviceCategory']\ntrain['browser_operatingSystem'] = train['device.browser'] + '_' + train['device.operatingSystem']\ntrain['source_country'] = train['trafficSource.source'] + '_' + train['geoNetwork.country']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"no_use = [\"date\", \"fullVisitorId\", \"sessionId\", \"visitId\", \"visitStartTime\", 'totals.transactionRevenue', 'trafficSource.referralPath']\ncat_cols = [col for col in train.columns if col not in num_cols and col not in no_use]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"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}