{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","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":30732,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-06-09T12:46:35.321055Z","iopub.execute_input":"2024-06-09T12:46:35.322050Z","iopub.status.idle":"2024-06-09T12:46:35.331817Z","shell.execute_reply.started":"2024-06-09T12:46:35.321981Z","shell.execute_reply":"2024-06-09T12:46:35.330558Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport json\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\ncolor = sns.color_palette()\n\n%matplotlib inline\n\nfrom plotly import tools\nimport plotly.offline as py\npy.init_notebook_mode(connected=True)\nimport plotly.graph_objs as go\n\nfrom sklearn import model_selection, preprocessing, metrics\nimport lightgbm as lgb\n\npd.options.mode.chained_assignment = None\npd.options.display.max_columns = 999","metadata":{"execution":{"iopub.status.busy":"2024-06-09T12:46:35.334680Z","iopub.execute_input":"2024-06-09T12:46:35.335121Z","iopub.status.idle":"2024-06-09T12:46:35.348871Z","shell.execute_reply.started":"2024-06-09T12:46:35.335084Z","shell.execute_reply":"2024-06-09T12:46:35.347750Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train = pd.read_csv(\"/kaggle/input/ga-customer-revenue-prediction/train.csv\") \ndf_test = pd.read_csv(\"/kaggle/input/ga-customer-revenue-prediction/test.csv\")\nsample = pd.read_csv(\"/kaggle/input/ga-customer-revenue-prediction/sample_submission.csv\")","metadata":{"execution":{"iopub.status.busy":"2024-06-09T12:46:35.350468Z","iopub.execute_input":"2024-06-09T12:46:35.350800Z","iopub.status.idle":"2024-06-09T12:47:07.118698Z","shell.execute_reply.started":"2024-06-09T12:46:35.350773Z","shell.execute_reply":"2024-06-09T12:47:07.117320Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train.head(3)","metadata":{"execution":{"iopub.status.busy":"2024-06-09T12:47:07.120904Z","iopub.execute_input":"2024-06-09T12:47:07.121279Z","iopub.status.idle":"2024-06-09T12:47:07.138466Z","shell.execute_reply.started":"2024-06-09T12:47:07.121249Z","shell.execute_reply":"2024-06-09T12:47:07.137279Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test.head(3)","metadata":{"execution":{"iopub.status.busy":"2024-06-09T12:47:07.139925Z","iopub.execute_input":"2024-06-09T12:47:07.140265Z","iopub.status.idle":"2024-06-09T12:47:07.158756Z","shell.execute_reply.started":"2024-06-09T12:47:07.140237Z","shell.execute_reply":"2024-06-09T12:47:07.157642Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample.head(3)","metadata":{"execution":{"iopub.status.busy":"2024-06-09T12:47:07.160356Z","iopub.execute_input":"2024-06-09T12:47:07.160845Z","iopub.status.idle":"2024-06-09T12:47:07.173934Z","shell.execute_reply.started":"2024-06-09T12:47:07.160804Z","shell.execute_reply":"2024-06-09T12:47:07.172488Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import json\n\n# Load the data\ndf = df_train\n\n# Function to parse JSON columns\ndef parse_json(df, column_name):\n    json_df = pd.json_normalize(df[column_name].apply(json.loads))\n    json_df.columns = [f\"{column_name}_{sub_col}\" for sub_col in json_df.columns]\n    df = df.drop(column_name, axis=1)\n    return pd.concat([df, json_df], axis=1)\n\n# Parse JSON columns\njson_columns = ['device', 'geoNetwork', 'totals', 'trafficSource']\nfor column in json_columns:\n    df = parse_json(df, column)\n\n# Convert date to datetime format\ndf['date'] = pd.to_datetime(df['date'], format='%Y%m%d')\n\n# Convert visitStartTime to datetime\ndf['visitStartTime'] = pd.to_datetime(df['visitStartTime'], unit='s')\n\n# Convert categorical features to numerical using one-hot encoding\ncategorical_columns = ['channelGrouping', 'socialEngagementType']\ndf = pd.get_dummies(df, columns=categorical_columns)\n\n# Handling missing values (fill with 0 for simplicity)\ndf = df.fillna(0)\n\n# Drop irrelevant columns (example: 'fullVisitorId', 'sessionId' may be irrelevant for model training)\ndf = df.drop(['sessionId', 'visitId'], axis=1)\n\n# Save the preprocessed dataframe to a new CSV file\ndf_train= df \ndf_train.head()","metadata":{"execution":{"iopub.status.busy":"2024-06-09T12:47:07.175204Z","iopub.execute_input":"2024-06-09T12:47:07.175584Z","iopub.status.idle":"2024-06-09T12:48:44.472881Z","shell.execute_reply.started":"2024-06-09T12:47:07.175554Z","shell.execute_reply":"2024-06-09T12:48:44.471550Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Function to remove columns where all values are \"not available in demo dataset\"\ndef remove_na_columns(dataframe, na_value=\"not available in demo dataset\"):\n    return dataframe.loc[:, (dataframe != na_value).any(axis=0)]\n\ndf_train = remove_na_columns(df_train)\ndf_train.head()","metadata":{"execution":{"iopub.status.busy":"2024-06-09T12:48:44.476228Z","iopub.execute_input":"2024-06-09T12:48:44.476594Z","iopub.status.idle":"2024-06-09T12:48:50.843584Z","shell.execute_reply.started":"2024-06-09T12:48:44.476566Z","shell.execute_reply":"2024-06-09T12:48:50.842436Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train['geoNetwork_continent'].value_counts()","metadata":{"execution":{"iopub.status.busy":"2024-06-09T12:48:50.844968Z","iopub.execute_input":"2024-06-09T12:48:50.845312Z","iopub.status.idle":"2024-06-09T12:48:51.036991Z","shell.execute_reply.started":"2024-06-09T12:48:50.845284Z","shell.execute_reply":"2024-06-09T12:48:51.035810Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train['geoNetwork_subContinent'].value_counts()","metadata":{"execution":{"iopub.status.busy":"2024-06-09T12:48:51.038813Z","iopub.execute_input":"2024-06-09T12:48:51.039736Z","iopub.status.idle":"2024-06-09T12:48:51.249547Z","shell.execute_reply.started":"2024-06-09T12:48:51.039696Z","shell.execute_reply":"2024-06-09T12:48:51.248140Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train['geoNetwork_country'].value_counts()","metadata":{"execution":{"iopub.status.busy":"2024-06-09T12:48:51.251363Z","iopub.execute_input":"2024-06-09T12:48:51.251882Z","iopub.status.idle":"2024-06-09T12:48:51.454361Z","shell.execute_reply.started":"2024-06-09T12:48:51.251823Z","shell.execute_reply":"2024-06-09T12:48:51.453143Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Get the top 5 most frequent values\ntop_5_sources = df_train['trafficSource_source'].value_counts().nlargest(5).index.tolist()\n\n# Replace all other values with the top value\ndef replace_other(source):\n  if source not in top_5_sources:\n    source = top_5_sources[0]  # Replace with the most frequent source\n  return source\n\ndf_train['trafficSource_source'] = df_train['trafficSource_source'].apply(replace_other)","metadata":{"execution":{"iopub.status.busy":"2024-06-09T12:48:51.455977Z","iopub.execute_input":"2024-06-09T12:48:51.456599Z","iopub.status.idle":"2024-06-09T12:48:52.066713Z","shell.execute_reply.started":"2024-06-09T12:48:51.456560Z","shell.execute_reply":"2024-06-09T12:48:52.065493Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train['trafficSource_keyword'].value_counts()","metadata":{"execution":{"iopub.status.busy":"2024-06-09T12:48:52.068285Z","iopub.execute_input":"2024-06-09T12:48:52.068641Z","iopub.status.idle":"2024-06-09T12:48:52.219171Z","shell.execute_reply.started":"2024-06-09T12:48:52.068612Z","shell.execute_reply":"2024-06-09T12:48:52.217773Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train['trafficSource_source'].value_counts()","metadata":{"execution":{"iopub.status.busy":"2024-06-09T12:48:52.220493Z","iopub.execute_input":"2024-06-09T12:48:52.220855Z","iopub.status.idle":"2024-06-09T12:48:52.390737Z","shell.execute_reply.started":"2024-06-09T12:48:52.220826Z","shell.execute_reply":"2024-06-09T12:48:52.389536Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Get the top 5 most frequent values\ntop_5_sources = df_train['trafficSource_source'].value_counts().nlargest(5).index.tolist()\n\n# Replace all other values with the top value\ndef replace_other(source):\n  if source not in top_5_sources:\n    source = top_5_sources[0]  # Replace with the most frequent source\n  return source\n\ndf_train['trafficSource_source'] = df_train['trafficSource_source'].apply(replace_other)","metadata":{"execution":{"iopub.status.busy":"2024-06-09T12:48:52.392220Z","iopub.execute_input":"2024-06-09T12:48:52.392653Z","iopub.status.idle":"2024-06-09T12:48:52.983543Z","shell.execute_reply.started":"2024-06-09T12:48:52.392616Z","shell.execute_reply":"2024-06-09T12:48:52.982202Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train['trafficSource_medium'].value_counts()","metadata":{"execution":{"iopub.status.busy":"2024-06-09T12:48:52.985059Z","iopub.execute_input":"2024-06-09T12:48:52.985550Z","iopub.status.idle":"2024-06-09T12:48:53.175950Z","shell.execute_reply.started":"2024-06-09T12:48:52.985508Z","shell.execute_reply":"2024-06-09T12:48:53.174746Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Get the top 5 most frequent values\ntop_5_sources = df_train['trafficSource_medium'].value_counts().nlargest(5).index.tolist()\n\n# Replace all other values with the top value\ndef replace_other(source):\n  if source not in top_5_sources:\n    source = top_5_sources[0]  # Replace with the most frequent source\n  return source\n\ndf_train['trafficSource_medium'] = df_train['trafficSource_medium'].apply(replace_other)","metadata":{"execution":{"iopub.status.busy":"2024-06-09T12:48:53.177397Z","iopub.execute_input":"2024-06-09T12:48:53.177784Z","iopub.status.idle":"2024-06-09T12:48:53.745382Z","shell.execute_reply.started":"2024-06-09T12:48:53.177742Z","shell.execute_reply":"2024-06-09T12:48:53.743947Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#df_train['device_browser'].value_counts()\n\n# Get the top 5 most frequent values\ntop_6_sources = df_train['device_browser'].value_counts().nlargest(6).index.tolist()\n\n# Replace all other values with the top value\ndef replace_other(source):\n  if source not in top_6_sources:\n    source = top_6_sources[0]  # Replace with the most frequent source\n  return source\n\ndf_train['device_browser'] = df_train['device_browser'].apply(replace_other)","metadata":{"execution":{"iopub.status.busy":"2024-06-09T12:48:53.746890Z","iopub.execute_input":"2024-06-09T12:48:53.747252Z","iopub.status.idle":"2024-06-09T12:48:54.302980Z","shell.execute_reply.started":"2024-06-09T12:48:53.747220Z","shell.execute_reply":"2024-06-09T12:48:54.301676Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# df_train['device_operatingSystem'].value_counts()\n\n# Get the top 5 most frequent values\ntop_6_sources = df_train['device_operatingSystem'].value_counts().nlargest(6).index.tolist()\n\n# Replace all other values with the top value\ndef replace_other(source):\n  if source not in top_6_sources:\n    source = top_6_sources[0]  # Replace with the most frequent source\n  return source\n\ndf_train['device_operatingSystem'] = df_train['device_operatingSystem'].apply(replace_other)","metadata":{"execution":{"iopub.status.busy":"2024-06-09T12:48:54.304356Z","iopub.execute_input":"2024-06-09T12:48:54.304707Z","iopub.status.idle":"2024-06-09T12:48:54.869287Z","shell.execute_reply.started":"2024-06-09T12:48:54.304681Z","shell.execute_reply":"2024-06-09T12:48:54.868106Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train = df_train.drop(['visitStartTime', 'geoNetwork_region', 'geoNetwork_metro','geoNetwork_city','geoNetwork_networkDomain','trafficSource_campaign','trafficSource_keyword', 'geoNetwork_country', 'geoNetwork_continent','device_isMobile'], axis=1)","metadata":{"execution":{"iopub.status.busy":"2024-06-09T12:48:54.873551Z","iopub.execute_input":"2024-06-09T12:48:54.873895Z","iopub.status.idle":"2024-06-09T12:48:55.355296Z","shell.execute_reply.started":"2024-06-09T12:48:54.873869Z","shell.execute_reply":"2024-06-09T12:48:55.354116Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train[\"totals_transactionRevenue\"] = df_train[\"totals_transactionRevenue\"].astype('float')\n\nplt.figure(figsize=(8,6))\nplt.scatter(range(df_train.shape[0]), np.sort(np.log1p(df_train[\"totals_transactionRevenue\"].values)))\nplt.xlabel('index', fontsize=12)\nplt.ylabel('TransactionRevenue', fontsize=12)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-06-09T12:48:55.356631Z","iopub.execute_input":"2024-06-09T12:48:55.356944Z","iopub.status.idle":"2024-06-09T12:48:57.631617Z","shell.execute_reply.started":"2024-06-09T12:48:55.356919Z","shell.execute_reply":"2024-06-09T12:48:57.630396Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.ticker as ticker\n# Filter out non-zero values\nnon_zero_values = df_train['totals_transactionRevenue'][df_train['totals_transactionRevenue'].ne(0)]\n\n# Drop outliers using IQR method\nQ1 = non_zero_values.quantile(0.25)\nQ3 = non_zero_values.quantile(0.75)\nIQR = Q3 - Q1\nlower_bound = Q1 - 1.5 * IQR\nupper_bound = Q3 + 1.5 * IQR\nfiltered_values = non_zero_values[(non_zero_values > lower_bound) & (non_zero_values < upper_bound)]\n\n# Sort the filtered non-zero values in descending order\nfiltered_values_sorted = filtered_values.sort_values(ascending=False).reset_index(drop=True)\n\n\n# Plot the individual non-zero values in descending order\nplt.figure(figsize=(10, 6))\nplt.plot(filtered_values_sorted, 'o')\nplt.title('Individual Non-zero Values of totals_transactionRevenue (Descending Order)')\nplt.xlabel('Index')\nplt.ylabel('Transaction Revenue in cents')\n\nplt.gca().yaxis.set_major_formatter(ticker.FuncFormatter(lambda x, _: f'{int(x):,}'))\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-06-09T12:48:57.633124Z","iopub.execute_input":"2024-06-09T12:48:57.633491Z","iopub.status.idle":"2024-06-09T12:48:57.931002Z","shell.execute_reply.started":"2024-06-09T12:48:57.633459Z","shell.execute_reply":"2024-06-09T12:48:57.929915Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"gdf = df_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()","metadata":{"execution":{"iopub.status.busy":"2024-06-09T12:48:57.932749Z","iopub.execute_input":"2024-06-09T12:48:57.933200Z","iopub.status.idle":"2024-06-09T12:49:02.696095Z","shell.execute_reply.started":"2024-06-09T12:48:57.933160Z","shell.execute_reply":"2024-06-09T12:49:02.695031Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"nzi = df_train['totals_transactionRevenue'].ne(0).sum()\nprint(\"Number of instances in train set with non-zero revenue : \", nzi, \" and ratio is : \", nzi / df_train.shape[0])\n\nnzr = (gdf[\"totals_transactionRevenue\"]>0).sum()\nprint(\"Number of unique customers with non-zero revenue : \", nzr, \"and the ratio is : \", nzr / gdf.shape[0])","metadata":{"execution":{"iopub.status.busy":"2024-06-09T12:49:02.697400Z","iopub.execute_input":"2024-06-09T12:49:02.697770Z","iopub.status.idle":"2024-06-09T12:49:02.708491Z","shell.execute_reply.started":"2024-06-09T12:49:02.697740Z","shell.execute_reply":"2024-06-09T12:49:02.707276Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Calculate the total sum of 'totals_transactionRevenue' and print it\ntotal_sum = gdf['totals_transactionRevenue'].sum()\ntotal_sum_int = int(total_sum)\nprint(f'total revenue from customers is ${(total_sum_int) / 100}')","metadata":{"execution":{"iopub.status.busy":"2024-06-09T12:49:02.710061Z","iopub.execute_input":"2024-06-09T12:49:02.710496Z","iopub.status.idle":"2024-06-09T12:49:02.719254Z","shell.execute_reply.started":"2024-06-09T12:49:02.710457Z","shell.execute_reply":"2024-06-09T12:49:02.717899Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Group by date and count the number of users (rows) for each date\ndate_counts = df_train.groupby('date').size()\n\n# Filter out non-zero values for totals_transactionRevenue\nnon_zero_df = df_train[df_train['totals_transactionRevenue'].ne(0)]\n\n# Group by date and count the number of users (rows) with non-zero transactionRevenue for each date\nnon_zero_date_counts = non_zero_df.groupby('date').size()\n\n# Plot the counts of rows for each date\nplt.figure(figsize=(14, 7))\n\n# Plot the total counts in red\nplt.subplot(2, 1, 1)\nplt.plot(date_counts.index, date_counts.values, 'r', label='Total Users')\nplt.title('Number of Users per Date')\nplt.xlabel('Date')\nplt.ylabel('Number of Users')\nplt.legend()\n\n# Plot the counts of non-zero transactionRevenue in blue\nplt.subplot(2, 1, 2)\nplt.plot(non_zero_date_counts.index, non_zero_date_counts.values, 'b', label='Users with Non-zero Transaction Revenue')\nplt.title('Number of Users with Non-zero Transaction Revenue per Date')\nplt.xlabel('Date')\nplt.ylabel('Number of Users')\nplt.legend()\n\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-06-09T12:49:02.720897Z","iopub.execute_input":"2024-06-09T12:49:02.721281Z","iopub.status.idle":"2024-06-09T12:49:03.428110Z","shell.execute_reply.started":"2024-06-09T12:49:02.721249Z","shell.execute_reply":"2024-06-09T12:49:03.426849Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train.head()","metadata":{"execution":{"iopub.status.busy":"2024-06-09T12:49:03.429740Z","iopub.execute_input":"2024-06-09T12:49:03.430165Z","iopub.status.idle":"2024-06-09T12:49:03.463410Z","shell.execute_reply.started":"2024-06-09T12:49:03.430125Z","shell.execute_reply":"2024-06-09T12:49:03.462193Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train.info()","metadata":{"execution":{"iopub.status.busy":"2024-06-09T12:49:03.464948Z","iopub.execute_input":"2024-06-09T12:49:03.465297Z","iopub.status.idle":"2024-06-09T12:49:04.888716Z","shell.execute_reply.started":"2024-06-09T12:49:03.465267Z","shell.execute_reply":"2024-06-09T12:49:04.887588Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# List of columns to drop\ncolumns_to_drop = ['trafficSource_isTrueDirect', 'trafficSource_referralPath', \n                   'trafficSource_adwordsClickInfo.page', 'trafficSource_adwordsClickInfo.slot', \n                   'trafficSource_adwordsClickInfo.gclId', 'trafficSource_adwordsClickInfo.adNetworkType', \n                   'trafficSource_adwordsClickInfo.isVideoAd', 'trafficSource_adContent', \n                   'trafficSource_campaignCode','fullVisitorId']\ndf_train = df_train.drop(columns_to_drop, axis=1)\n\n# Convert the specified columns to integer type (assuming no missing values)\nfor col in ['totals_visits', 'totals_hits', 'totals_pageviews', 'totals_bounces', 'totals_newVisits']:\n  df_train[col] = df_train[col].astype(int)\n\ndf_train = pd.get_dummies(df_train)","metadata":{"execution":{"iopub.status.busy":"2024-06-09T12:51:49.434678Z","iopub.execute_input":"2024-06-09T12:51:49.435172Z","iopub.status.idle":"2024-06-09T12:51:52.304099Z","shell.execute_reply.started":"2024-06-09T12:51:49.435139Z","shell.execute_reply":"2024-06-09T12:51:52.302449Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train.head()","metadata":{"execution":{"iopub.status.busy":"2024-06-09T12:52:21.199608Z","iopub.execute_input":"2024-06-09T12:52:21.200037Z","iopub.status.idle":"2024-06-09T12:52:21.249768Z","shell.execute_reply.started":"2024-06-09T12:52:21.200003Z","shell.execute_reply":"2024-06-09T12:52:21.248382Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train.corr()['totals_transactionRevenue'].sort_values(ascending=False)","metadata":{"execution":{"iopub.status.busy":"2024-06-09T12:55:39.588525Z","iopub.execute_input":"2024-06-09T12:55:39.589032Z","iopub.status.idle":"2024-06-09T12:55:50.288128Z","shell.execute_reply.started":"2024-06-09T12:55:39.588995Z","shell.execute_reply":"2024-06-09T12:55:50.286825Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"corr = df_train.corr()['totals_transactionRevenue']\nleast_correlated = corr.abs().sort_values(ascending=True)\ncolumns_to_drop = least_correlated.head(50).index[1:]\ndf_train = df_train.drop(columns_to_drop, axis=1) # Drop the least correlated 50 columns\n\ndf_train.head()","metadata":{"execution":{"iopub.status.busy":"2024-06-09T13:01:47.542555Z","iopub.execute_input":"2024-06-09T13:01:47.543573Z","iopub.status.idle":"2024-06-09T13:01:58.298587Z","shell.execute_reply.started":"2024-06-09T13:01:47.543528Z","shell.execute_reply":"2024-06-09T13:01:58.297199Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# NOTEBOOK STOPPED, I WILL USE THIS TO REPROCESS MY CODE","metadata":{}},{"cell_type":"code","source":"df_train = pd.read_csv(\"/kaggle/input/ga-customer-revenue-prediction/train.csv\") \n\n\n# JSON PARSE\ndf = df_train\ndef parse_json(df, column_name):\n    json_df = pd.json_normalize(df[column_name].apply(json.loads))\n    json_df.columns = [f\"{column_name}_{sub_col}\" for sub_col in json_df.columns]\n    df = df.drop(column_name, axis=1)\n    return pd.concat([df, json_df], axis=1)\njson_columns = ['device', 'geoNetwork', 'totals', 'trafficSource']\nfor column in json_columns:\n    df = parse_json(df, column)\ndf_train= df \n\n\ndf_train['date'] = pd.to_datetime(df_train['date'], format='%Y%m%d')\ndf_train[\"totals_transactionRevenue\"] = df_train[\"totals_transactionRevenue\"].astype('float')\ndf_train['totals_transactionRevenue'] = df_train['totals_transactionRevenue'].fillna(0)\n\n\n# Get the top 5 most frequent values\ntop_5_sources = df_train['trafficSource_source'].value_counts().nlargest(5).index.tolist()\ndef replace_other(source):\n  if source not in top_5_sources:\n    source = top_5_sources[0]# Replace with the most frequent source\n  return source\ndf_train['trafficSource_source'] = df_train['trafficSource_source'].apply(replace_other)\n\n\n# Get the top 5 most frequent values\ntop_5_sources = df_train['trafficSource_source'].value_counts().nlargest(5).index.tolist()\ndef replace_other(source):\n  if source not in top_5_sources:\n    source = top_5_sources[0]  # Replace with the most frequent source\n  return source\ndf_train['trafficSource_source'] = df_train['trafficSource_source'].apply(replace_other)\n\n\n# Get the top 5 most frequent values\ntop_5_sources = df_train['trafficSource_medium'].value_counts().nlargest(5).index.tolist()\ndef replace_other(source):\n  if source not in top_5_sources:\n    source = top_5_sources[0]  # Replace with the most frequent source\n  return source\ndf_train['trafficSource_medium'] = df_train['trafficSource_medium'].apply(replace_other)\n\n\n# Get the top 6 most frequent values\ntop_6_sources = df_train['device_browser'].value_counts().nlargest(6).index.tolist()\ndef replace_other(source):\n  if source not in top_6_sources:\n    source = top_6_sources[0]  # Replace with the most frequent source\n  return source\ndf_train['device_browser'] = df_train['device_browser'].apply(replace_other)\n\n\n# Get the top 6 most frequent values\ntop_6_sources = df_train['device_operatingSystem'].value_counts().nlargest(6).index.tolist()\ndef replace_other(source):\n  if source not in top_6_sources:\n    source = top_6_sources[0]  # Replace with the most frequent source\n  return source\ndf_train['device_operatingSystem'] = df_train['device_operatingSystem'].apply(replace_other)\n\n\n# Get the top 6 most frequent values\ntop_6_sources = df_train['channelGrouping'].value_counts().nlargest(6).index.tolist()\ndef replace_other(source):\n  if source not in top_6_sources:\n    source = top_6_sources[0]  # Replace with the most frequent source\n  return source\ndf_train['channelGrouping'] = df_train['channelGrouping'].apply(replace_other)\n\n\n# Get the top 10 most frequent values\ntop_10_sources = df_train['geoNetwork_subContinent'].value_counts().nlargest(10).index.tolist()\ndef replace_other(source):\n  if source not in top_10_sources:\n    source = top_10_sources[8]\n  return source\ndf_train['geoNetwork_subContinent'] = df_train['geoNetwork_subContinent'].apply(replace_other)\n\n\n# Convert the specified columns to integer type (assuming no missing values)\nfor col in ['totals_visits', 'totals_hits', 'totals_pageviews', 'totals_bounces', 'totals_newVisits']:\n    df_train[col] = df_train[col].fillna(0)\n    df_train[col] = df_train[col].astype(int)\n\n    \n# Combine the lists of columns to drop\ncolumns_to_drop = ['sessionId', 'visitId', 'visitStartTime', 'geoNetwork_region', \n                  'geoNetwork_metro', 'geoNetwork_city', 'geoNetwork_networkDomain', \n                  'trafficSource_campaign', 'trafficSource_keyword', 'geoNetwork_country', \n                  'geoNetwork_continent', 'device_isMobile', 'trafficSource_isTrueDirect', \n                  'trafficSource_referralPath', 'trafficSource_adwordsClickInfo.page', \n                  'trafficSource_adwordsClickInfo.slot', 'trafficSource_adwordsClickInfo.gclId', \n                  'trafficSource_adwordsClickInfo.adNetworkType', 'trafficSource_adwordsClickInfo.isVideoAd', \n                  'trafficSource_adContent', 'trafficSource_campaignCode','socialEngagementType']\ndf_train = df_train.drop(columns_to_drop, axis=1)\n\n\n# Find columns with not available in demo dataset value\ncols_to_drop = [col for col in df_train.columns if df_train[col].isin(['not available in demo dataset']).any()]\ndf_train = df_train.drop(cols_to_drop, axis=1)","metadata":{"execution":{"iopub.status.busy":"2024-06-09T15:21:36.404857Z","iopub.execute_input":"2024-06-09T15:21:36.405325Z","iopub.status.idle":"2024-06-09T15:23:27.817723Z","shell.execute_reply.started":"2024-06-09T15:21:36.405290Z","shell.execute_reply":"2024-06-09T15:23:27.816215Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Convert the 'date' column to a numeric format (e.g., timestamp)\ndf_train['date'] = pd.to_datetime(df_train['date']).astype(int) / 10**9\ndf_train = df_train.drop(['fullVisitorId'], axis=1)\ndf_train = pd.get_dummies(df_train)\ntrain = df_train\ntrain","metadata":{"execution":{"iopub.status.busy":"2024-06-09T15:23:27.820014Z","iopub.execute_input":"2024-06-09T15:23:27.820449Z","iopub.status.idle":"2024-06-09T15:23:31.139655Z","shell.execute_reply.started":"2024-06-09T15:23:27.820393Z","shell.execute_reply":"2024-06-09T15:23:31.138461Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train = pd.read_csv(\"/kaggle/input/ga-customer-revenue-prediction/test.csv\") \n\n\n# JSON PARSE\ndf = df_train\ndef parse_json(df, column_name):\n    json_df = pd.json_normalize(df[column_name].apply(json.loads))\n    json_df.columns = [f\"{column_name}_{sub_col}\" for sub_col in json_df.columns]\n    df = df.drop(column_name, axis=1)\n    return pd.concat([df, json_df], axis=1)\njson_columns = ['device', 'geoNetwork', 'totals', 'trafficSource']\nfor column in json_columns:\n    df = parse_json(df, column)\ndf_train= df \n\n\ndf_train['date'] = pd.to_datetime(df_train['date'], format='%Y%m%d')\n\n\n# Get the top 5 most frequent values\ntop_5_sources = df_train['trafficSource_source'].value_counts().nlargest(5).index.tolist()\ndef replace_other(source):\n  if source not in top_5_sources:\n    source = top_5_sources[0]# Replace with the most frequent source\n  return source\ndf_train['trafficSource_source'] = df_train['trafficSource_source'].apply(replace_other)\n\n\n# Get the top 5 most frequent values\ntop_5_sources = df_train['trafficSource_source'].value_counts().nlargest(5).index.tolist()\ndef replace_other(source):\n  if source not in top_5_sources:\n    source = top_5_sources[0]  # Replace with the most frequent source\n  return source\ndf_train['trafficSource_source'] = df_train['trafficSource_source'].apply(replace_other)\n\n\n# Get the top 5 most frequent values\ntop_5_sources = df_train['trafficSource_medium'].value_counts().nlargest(5).index.tolist()\ndef replace_other(source):\n  if source not in top_5_sources:\n    source = top_5_sources[0]  # Replace with the most frequent source\n  return source\ndf_train['trafficSource_medium'] = df_train['trafficSource_medium'].apply(replace_other)\n\n\n# Get the top 6 most frequent values\ntop_6_sources = df_train['device_browser'].value_counts().nlargest(6).index.tolist()\ndef replace_other(source):\n  if source not in top_6_sources:\n    source = top_6_sources[0]  # Replace with the most frequent source\n  return source\ndf_train['device_browser'] = df_train['device_browser'].apply(replace_other)\n\n\n# Get the top 6 most frequent values\ntop_6_sources = df_train['device_operatingSystem'].value_counts().nlargest(6).index.tolist()\ndef replace_other(source):\n  if source not in top_6_sources:\n    source = top_6_sources[0]  # Replace with the most frequent source\n  return source\ndf_train['device_operatingSystem'] = df_train['device_operatingSystem'].apply(replace_other)\n\n\n# Get the top 6 most frequent values\ntop_6_sources = df_train['channelGrouping'].value_counts().nlargest(6).index.tolist()\ndef replace_other(source):\n  if source not in top_6_sources:\n    source = top_6_sources[0]  # Replace with the most frequent source\n  return source\ndf_train['channelGrouping'] = df_train['channelGrouping'].apply(replace_other)\n\n\n# Get the top 10 most frequent values\ntop_10_sources = df_train['geoNetwork_subContinent'].value_counts().nlargest(10).index.tolist()\ndef replace_other(source):\n  if source not in top_10_sources:\n    source = top_10_sources[8]\n  return source\ndf_train['geoNetwork_subContinent'] = df_train['geoNetwork_subContinent'].apply(replace_other)\n\n\n# Convert the specified columns to integer type (assuming no missing values)\nfor col in ['totals_visits', 'totals_hits', 'totals_pageviews', 'totals_bounces', 'totals_newVisits']:\n    df_train[col] = df_train[col].fillna(0)\n    df_train[col] = df_train[col].astype(int)\n\n\n# Find columns with not available in demo dataset value\ncols_to_drop = [col for col in df_train.columns if df_train[col].isin(['not available in demo dataset']).any()]\ndf_train = df_train.drop(cols_to_drop, axis=1)\n\ndf_test = df_train","metadata":{"execution":{"iopub.status.busy":"2024-06-09T15:23:31.141525Z","iopub.execute_input":"2024-06-09T15:23:31.141858Z","iopub.status.idle":"2024-06-09T15:25:12.449436Z","shell.execute_reply.started":"2024-06-09T15:23:31.141830Z","shell.execute_reply":"2024-06-09T15:25:12.448102Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Extract the test IDs\ntest_id = df_test['fullVisitorId']\ndf_test = df_test.drop(['fullVisitorId'], axis=1)\n\n# Convert the 'date' column to a numeric format (e.g., timestamp)\ndf_test['date'] = pd.to_datetime(df_test['date']).astype(int) / 10**9","metadata":{"execution":{"iopub.status.busy":"2024-06-09T15:25:12.452318Z","iopub.execute_input":"2024-06-09T15:25:12.452764Z","iopub.status.idle":"2024-06-09T15:25:13.117043Z","shell.execute_reply.started":"2024-06-09T15:25:12.452726Z","shell.execute_reply":"2024-06-09T15:25:13.115853Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Combine the lists of columns to drop\ncolumns_to_drop = ['sessionId', 'socialEngagementType', 'visitId', 'visitStartTime', \n                   'device_isMobile', 'geoNetwork_continent', 'geoNetwork_country', \n                   'geoNetwork_networkDomain', 'totals_bounces', 'trafficSource_campaign', \n                   'trafficSource_keyword', 'trafficSource_isTrueDirect', \n                   'trafficSource_adwordsClickInfo.page', 'trafficSource_adwordsClickInfo.slot', \n                   'trafficSource_adwordsClickInfo.gclId', 'trafficSource_adwordsClickInfo.adNetworkType', \n                   'trafficSource_adwordsClickInfo.isVideoAd', 'trafficSource_referralPath', \n                   'trafficSource_adContent']\n\ndf_test = df_test.drop(columns_to_drop, axis=1)\n\ndf_test = pd.get_dummies(df_test)","metadata":{"execution":{"iopub.status.busy":"2024-06-09T15:25:13.118344Z","iopub.execute_input":"2024-06-09T15:25:13.118732Z","iopub.status.idle":"2024-06-09T15:25:16.387476Z","shell.execute_reply.started":"2024-06-09T15:25:13.118700Z","shell.execute_reply":"2024-06-09T15:25:16.386096Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test","metadata":{"execution":{"iopub.status.busy":"2024-06-09T15:25:16.389268Z","iopub.execute_input":"2024-06-09T15:25:16.389713Z","iopub.status.idle":"2024-06-09T15:25:16.440321Z","shell.execute_reply.started":"2024-06-09T15:25:16.389671Z","shell.execute_reply":"2024-06-09T15:25:16.438927Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Find the columns that are not shared between the two dataframes\ntrain_columns = set(train.columns)\ntest_columns = set(df_test.columns)\n\n# Symmetric difference of columns in both dataframes\ncolumns_to_drop_train = train_columns.symmetric_difference(test_columns) - {'totals_transactionRevenue'}\ncolumns_to_drop_test = train_columns.symmetric_difference(test_columns)\n\n# Drop the columns\ndf_train = train.drop(columns=columns_to_drop_train, errors='ignore')\ndf_test = df_test.drop(columns=columns_to_drop_test, errors='ignore')","metadata":{"execution":{"iopub.status.busy":"2024-06-09T15:25:16.442164Z","iopub.execute_input":"2024-06-09T15:25:16.442562Z","iopub.status.idle":"2024-06-09T15:25:16.797034Z","shell.execute_reply.started":"2024-06-09T15:25:16.442529Z","shell.execute_reply":"2024-06-09T15:25:16.795733Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import lightgbm as lgb\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report\nfrom imblearn.over_sampling import SMOTE\n\n# Create a binary target variable\ndf_train['is_transaction'] = df_train['totals_transactionRevenue'].apply(lambda x: 1 if x > 0 else 0)\n\n# Prepare the features and target\nx = df_train.drop(['totals_transactionRevenue', 'is_transaction'], axis=1)\ny = df_train['is_transaction']\n\n# Split the data\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.05, random_state=42, stratify=y)\n\nimport lightgbm as lgb\nfrom sklearn.metrics import mean_squared_error\n\n# Custom function to run LightGBM\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    \n    # Define the early stopping and logging callbacks\n    callbacks = [\n        lgb.early_stopping(stopping_rounds=100),\n        lgb.log_evaluation(period=100)\n    ]\n    \n    model = lgb.train(params, lgtrain, 1000, valid_sets=[lgval], callbacks=callbacks)\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# Split the data for validation\ndev_X, val_X, dev_y, val_y = train_test_split(x_train, y_train, test_size=0.05, random_state=42)\n\n# Training the model\npred_test, model, pred_val = run_lgb(dev_X, dev_y, val_X, val_y, x_test)\n\n# Evaluate the model\nmse = mean_squared_error(y_test, pred_test)\nprint(f'Mean Squared Error: {mse}')\n\n# Save the model to a file\nmodel.save_model('lightgbm_model.txt')","metadata":{"execution":{"iopub.status.busy":"2024-06-09T15:25:16.798624Z","iopub.execute_input":"2024-06-09T15:25:16.799044Z","iopub.status.idle":"2024-06-09T15:25:33.687889Z","shell.execute_reply.started":"2024-06-09T15:25:16.799005Z","shell.execute_reply":"2024-06-09T15:25:33.686502Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load the model from the file\nmodel = lgb.Booster(model_file='lightgbm_model.txt')\n\n# You can now use the model to make predictions\npredictions = model.predict(df_test)\n\n# Create a DataFrame for the submission\nsubmission = pd.DataFrame({\n    'fullVisitorId': test_id,\n    'PredictedLogRevenue': predictions\n})\n\n# Save the submission DataFrame to a CSV file\nsubmission.to_csv('submission.csv', index=False)\n\nsubmission.head()","metadata":{"execution":{"iopub.status.busy":"2024-06-09T15:28:12.665079Z","iopub.execute_input":"2024-06-09T15:28:12.665676Z","iopub.status.idle":"2024-06-09T15:28:18.739546Z","shell.execute_reply.started":"2024-06-09T15:28:12.665623Z","shell.execute_reply":"2024-06-09T15:28:18.738113Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission","metadata":{"execution":{"iopub.status.busy":"2024-06-09T15:33:17.400664Z","iopub.execute_input":"2024-06-09T15:33:17.401186Z","iopub.status.idle":"2024-06-09T15:33:17.416723Z","shell.execute_reply.started":"2024-06-09T15:33:17.401150Z","shell.execute_reply":"2024-06-09T15:33:17.415221Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission = submission.groupby('fullVisitorId', as_index=False).sum()\nsubmission","metadata":{"execution":{"iopub.status.busy":"2024-06-09T15:37:01.972081Z","iopub.execute_input":"2024-06-09T15:37:01.972660Z","iopub.status.idle":"2024-06-09T15:37:04.833209Z","shell.execute_reply.started":"2024-06-09T15:37:01.972612Z","shell.execute_reply":"2024-06-09T15:37:04.831519Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission.to_csv('new_submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2024-06-09T15:38:06.783550Z","iopub.execute_input":"2024-06-09T15:38:06.784085Z","iopub.status.idle":"2024-06-09T15:38:09.023702Z","shell.execute_reply.started":"2024-06-09T15:38:06.784049Z","shell.execute_reply":"2024-06-09T15:38:09.022454Z"},"trusted":true},"execution_count":null,"outputs":[]}]}